<template>
    <div>
        <el-card style="margin-top: 10px" class="box-card">
            <el-form ref="group" :rules="rules" :model="group" label-width="80px">
                <el-form-item label="店铺" prop="shop_id">
                    <el-select v-model="group.shop_id" :disabled="true">
                        <el-option v-for="store in stores" :key="store.id" :label="store.name" :value="store.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="活动标题" prop="title">
                    <el-input type="textarea" v-model="group.title" style="width: 500px;"></el-input>
                </el-form-item>
                <el-form-item label="团购商品">
                    <el-button @click="importGoods()">从商品列表导入</el-button>
                    <el-input placeholder="搜索商品名称、编码" v-model="groupGoodsSearch.external_sku_id"
                        style="margin-left: 20px; width: 400px;">
                        <el-button slot="append" @click="getGroupGoodsList();">查询</el-button>
                    </el-input>
                    <div style="display: flex; align-items: center;">
                        <span style="margin-right: 20px;">商品状态</span>
                        <el-radio-group v-model="groupGoodsSearch.has_stock" @change="getGroupGoodsList()">
                            <el-radio :label="0">全部</el-radio>
                            <el-radio :label="1">在售中</el-radio>
                            <el-radio :label="-1">已售罄</el-radio>
                        </el-radio-group>
                    </div>
                    <div style="display: flex; align-items: center;">
                        <span style="margin-right: 20px;">商品分类</span>
                        <el-radio-group v-model="groupGoodsSearch.type_id" size="small" @change="getGroupGoodsList()">
                            <el-radio-button label="0">全部</el-radio-button>
                            <el-radio-button v-for="goodsType in types" :key="goodsType.id" :label="goodsType.id">
                                {{goodsType.name}}</el-radio-button>
                        </el-radio-group>
                    </div>
                    <el-table ref="multipleTableGroup" v-loading="groupLoading" :data="groupGoods.data" border
                        style="width: 100%" height="800" :row-key="getRowKeys">
                        <el-table-column type="selection" :reserve-selection="true" width="55">
                        </el-table-column>
                        <el-table-column label="排序">
                            <template slot-scope="scope">
                                <el-input v-model="scope.row.sort" placeholder="排序"
                                    @change="handleCellChange(scope.row)"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="goods_name" label=" 商品名称">
                        </el-table-column>
                        <el-table-column prop="external_sku_id" label="编码">
                        </el-table-column>
                        <el-table-column prop="category_name" label="分类">
                        </el-table-column>
                        <el-table-column prop="stock" label="库存">
                        </el-table-column>
                        <el-table-column label="限购数量">
                            <template slot-scope="scope">
                                <el-input v-model="scope.row.limit_buy" placeholder="限购数量"
                                    @change="handleCellChange(scope.row)"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column label="价格">
                            <template slot-scope="scope">
                                <el-input v-model="scope.row.price_in_fen" placeholder="价格"
                                    @change="handleCellChange(scope.row)"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="options" label="操作">
                            <template slot-scope="scope">
                                <!-- <el-button @click="setTop(scope.row)" type="text" size="small">置顶</el-button> -->
                                <el-button @click="remove(scope.row)" type="text" size="small">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div
                        style="display: flex; justify-content: space-between; align-items: center; line-height: 32px; margin-top: 20px;">
                        <el-button type="danger" size="small" @click="batchRemove();">批量删除</el-button>
                        <el-pagination @size-change="handleSizeChangeGroup" @current-change="getGroupGoodsList"
                            :current-page.sync="groupGoods.meta.current_page" :page-sizes="[20, 30, 50, 100]"
                            :page-size="groupGoods.meta.per_page" layout="sizes, prev, pager, next"
                            :total="groupGoods.meta.total">
                        </el-pagination>
                    </div>
                </el-form-item>
                <el-form-item label="团购时间" prop="datetimerange">
                    <el-date-picker v-model="group.datetimerange" type="datetimerange" range-separator="至"
                        start-placeholder="开始时间" end-placeholder="结束时间" value-format="yyyy-MM-dd HH:mm:ss">
                    </el-date-picker>
                </el-form-item>
                <el-form-item style="display: flex; justify-content: flex-end;">
                    <el-button type="success" @click="onEdit();">修改团购</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <el-dialog :title="dialogTitle" :visible.sync="centerDialogVisible" width="80%" :close-on-click-modal="false">
            <el-form ref="goodsList" :model="goodsList" label-width="80px">
                <el-form-item label="商品分类" prop="type_id">
                    <el-radio-group v-model="goodsList.type_id" size="small" @change="goodsSearch()">
                        <el-radio-button label="0">全部</el-radio-button>
                        <el-radio-button v-for="goodsType in types" :key="goodsType.id" :label="goodsType.id">
                            {{goodsType.name}}</el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="商品品牌" prop="brand_id">
                    <el-radio-group v-model="goodsList.brand_id" size="small" @change="goodsSearch()">
                        <el-radio-button label="0">全部</el-radio-button>
                        <el-radio-button v-for="goodsBrand in brands" :key="goodsBrand.id" :label="goodsBrand.id">
                            {{goodsBrand.name}}</el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="搜索" prop="goods_keyword">
                    <el-input placeholder="搜索商品名称、编码" v-model="goodsList.goods_keyword" style="width: 400px;">
                    </el-input>
                    <el-radio-group v-model="goodsList.has_stock" style="margin: 0 30px">
                        <el-radio :label="1">有库存</el-radio>
                        <el-radio :label="0">全部</el-radio>
                    </el-radio-group>
                    <el-button type="primary" size="small" @click="goodsSearch();">查询</el-button>
                    <el-button size="small" @click="resetForm()">重置</el-button>
                </el-form-item>
            </el-form>
            <el-table ref="multipleTable" @select="handleSelect" v-loading="goodsLoading" :data="goods.data" border
                style="width: 100%" height="520" :row-key="getRowKeys" @select-all="selectCurrentGoods">
                <el-table-column type="selection" :reserve-selection="true" width="55">
                </el-table-column>
                <el-table-column label="商品信息">
                    <template slot-scope="scope">
                        {{scope.row.goods.title + ' ' + scope.row.title}}
                    </template>
                </el-table-column>
                <el-table-column label="编码">
                    <template slot-scope="scope">
                        {{scope.row.goods.goods_code + '_' + scope.row.sku_code}}
                    </template>
                </el-table-column>
                <el-table-column label="品牌">
                    <template slot-scope="scope">
                        {{scope.row.goods.brand ? scope.row.goods.brand.name : ''}}
                    </template>
                </el-table-column>
                <el-table-column prop="goods.type.name" label="分类">
                </el-table-column>
                <el-table-column prop="num" label="库存">
                </el-table-column>
            </el-table>
            <div style="display: flex; flex-direction: row-reverse; align-items: center; margin-top: 10px;">
                <el-pagination @size-change="handleSizeChange" @current-change="goodsSearch"
                    :current-page.sync="goods.meta.current_page" :page-sizes="[20, 30, 50, 100]"
                    :page-size="goods.meta.per_page" layout="sizes, prev, pager, next" :total="goods.meta.total">
                </el-pagination>
            </div>
            <span slot="footer" class="dialog-footer">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <div>
                        <el-button @click="toggleSelection(1)">全选</el-button>
                        <el-button @click="toggleSelection(0)">取消全选</el-button>
                    </div>
                    <div>已选 {{selectNum}} 件</div>
                    <div>
                        <el-button type="primary" @click="addGoods();">确 定</el-button>
                        <el-button @click="centerDialogVisible = false">取 消</el-button>
                    </div>
                </div>
            </span>
        </el-dialog>
    </div>
</template>


<script>
import { storeList } from "../../api/shop";
import { showGroup, editGroup, getGroupGoods } from "../../api/group";
import { goods_types, Brand_goods_types } from "../../api/rankingData";
import { getGoodsList } from "../../api/goods";
export default {
    data() {
        return {
            group: {
                shop_id: '',
                title: "",
                is_save_preview: 1,
                datetimerange: [],
                start_time: '',
                end_time: ''
            },
            rules: {
                shop_id: [
                    { required: true, message: '请选择店铺' },
                ],
                title: [
                    { required: true, message: '请输入活动标题', trigger: 'blur' },
                ],
                datetimerange: [
                    { required: true, message: '请选择团购时间', trigger: 'blur' },
                ],
            },
            groupGoods: {
                data: [],
                meta: {
                    total: 0,
                    current_page: 1,
                    per_page: 20,
                },
            },
            groupGoodsSearch: {
                external_sku_id: "",
                has_stock: 1,
                page: 1,
                per_page: 20,
                group_id: 0,
                delete_ids: [],
                new_ids: [],
                type_id: 0,
            },
            groupLoading: false,
            goodsLoading: true,
            goods: {
                data: [],
                meta: {
                    total: 0,
                    current_page: 1,
                    per_page: 20,
                }
            },
            centerDialogVisible: false,
            stores: [],
            types: [],
            brands: [],
            goodsList: {
                goods_keyword: "",
                has_stock: 1,
                type_id: 0,
                brand_id: 0,
                delete_ids: [],
                new_ids: [],
                has_ids: [],
            },
            goodsListPage: {
                page: 1,
                per_page: 20,
            },
            dialogTitle: "您的商品库中已有 0 件商品",
            selectNum: 0,
            selectGoods: [],
            deleteGoods: [],
            allGoods: [],
            changeData: [],
        }
    },
    mounted() {
        this.getStoreList();
        this.groupGoodsSearch.group_id = parseInt(this.$route.query.id);
        this.getGoupInfo(this.$route.query.id);
        this.getGroupGoodsList();
        this.getbrandType();
        this.getgoodsType();
    },
    methods: {
        getStoreList() {
            let params = {
                page: 0,
                per_page: 999,
                plat_id: 1
            };
            storeList(params).then((res) => {
                this.stores = res.data.data;
            });
        },
        onEdit() {
            this.group.new_ids = this.goodsList.has_ids;
            let changeData = [];
            this.changeData.forEach((v, k) => {
                if (v) {
                    changeData.push(v);
                }
            })
            this.group.change_data = changeData;
            this.group.delete_ids = this.groupGoodsSearch.delete_ids;
            this.$refs.group.validate((valid) => {
                if (valid) {
                    editGroup(this.groupGoodsSearch.group_id, this.group).then((res) => {
                        this.$message(res.data.message);
                        // this.$router.push({ path: "GROUP_MANAGEMENT" });
                    })
                } else {
                    return false;
                }
            });
        },
        handleSizeChangeGroup(val) {
            this.groupGoodsSearch.per_page = val;
            this.getGroupGoodsList();
        },
        getGroupGoodsList(page = 1) {
            this.groupGoodsSearch.page = page;
            this.groupGoodsSearch.new_ids = this.goodsList.new_ids;
            getGroupGoods(this.groupGoodsSearch).then((res) => {
                this.groupGoods = res.data;
                this.groupGoods.data.forEach((sku, index) => {
                    if (undefined !== this.changeData[sku.id]) {
                        this.groupGoods.data[index].sort = this.changeData[sku.id].sort;
                        this.groupGoods.data[index].limit_buy = this.changeData[sku.id].limit_buy;
                        this.groupGoods.data[index].price_in_fen = this.changeData[sku.id].price_in_fen;
                    }
                })
                this.groupGoods.meta.per_page = parseInt(this.groupGoods.meta.per_page);
            })
        },
        getGoupInfo(id) {
            showGroup(id).then((res) => {
                this.group = res.data.data;
                this.group.datetimerange = [this.group.start_time, this.group.end_time];
            })
        },
        getgoodsType() {
            let params = {
                per_page: 9999,
            };
            goods_types(params).then((res) => {
                this.types = res.data.data;
            });
        },
        getbrandType() {
            let params = {
                per_page: 9999,
            };
            Brand_goods_types(params).then((res) => {
                this.brands = res.data.data;
            });
        },
        batchRemove() {
            this.$refs.multipleTableGroup.selection.forEach((row) => {
                this.groupGoodsSearch.delete_ids.push(row.id);
                let index = this.goodsList.has_ids.indexOf(row.id);
                if (index > 0) {
                    delete this.goodsList.has_ids[index];
                }
            })
            this.$refs.multipleTableGroup.clearSelection();
            this.getGroupGoodsList();
        },
        remove(row) {
            this.groupGoodsSearch.delete_ids.push(row.id);
            this.goodsList.has_ids.forEach((v, k) => {
                if (v == row.id) {
                    delete this.goodsList.has_ids[k];
                }
            })
            this.getGroupGoodsList();
        },
        handleCellChange(row) {
            this.changeData[row.id] = {
                id: row.id,
                sort: row.sort,
                limit_buy: row.limit_buy,
                price_in_fen: row.price_in_fen,
            };
        },
        // 从商品列表导入
        importGoods() {
            if (this.group.shop_id) {
                this.dialogTitle = "您的商品库中已有 " + this.groupGoods.meta.total + " 件商品";
                this.goodsSearch();
                this.centerDialogVisible = true;
            } else {
                this.$message.error('请先选择店铺');
            }
        },
        goodsSearch(page = 1) {
            this.goodsList.page = page;
            this.goodsList.per_page = this.goodsListPage.per_page;
            this.goodsList.group_id = this.groupGoodsSearch.group_id;
            this.goodsList.delete_ids = this.groupGoodsSearch.delete_ids;
            this.goodsLoading = true;
            getGoodsList(this.goodsList).then((res) => {
                this.goods = res.data;
                this.goods.meta.per_page = parseInt(this.goods.meta.per_page);
                this.goods.data.forEach((row, i) => {
                    if (undefined !== this.selectGoods[row.id]) {
                        this.$refs.multipleTable.toggleRowSelection(row, true);
                    }
                })
                this.goodsLoading = false;
            })
            if (1 === page) {
                this.getAllGoods(this.goodsList);
            }
        },
        getAllGoods(params) {
            params.page = 1;
            params.per_page = 9999;
            getGoodsList(params).then((res) => {
                this.allGoods = res.data.data;
            })
        },
        handleSizeChange(val) {
            this.goodsListPage.per_page = val;
            this.goodsSearch();
        },
        getRowKeys(row) {
            return row.id;
        },
        toggleSelection(isAll) {
            if (isAll) {
                this.allGoods.forEach((sku, i) => {
                    if (undefined === this.selectGoods[sku.id]) {
                        this.selectNum++;
                    }
                    this.selectGoods[sku.id] = 1;
                })
                this.goods.data.forEach((row, i) => {
                    this.$refs.multipleTable.toggleRowSelection(row, true);
                })
            } else {
                this.allGoods.forEach((sku, i) => {
                    if (undefined !== this.selectGoods[sku.id]) {
                        delete this.selectGoods[sku.id];
                        this.selectNum--;
                    }
                })
                this.$refs.multipleTable.clearSelection();
            }
        },
        handleSelect(selection, row) {
            if (undefined === this.selectGoods[row.id]) {
                this.selectGoods[row.id] = 1;
                this.selectNum++;
            } else {
                delete this.selectGoods[row.id];
                this.selectNum--;
            }
        },
        resetForm() {
            this.$refs.goodsList.resetFields();
            this.goodsSearch();
        },
        addGoods() {
            this.selectGoods.forEach((v, k) => {
                if (k !== undefined) {
                    this.goodsList.new_ids.push(k)
                    this.goodsList.has_ids.push(k)
                }
            })
            this.getGroupGoodsList();
            this.$refs.goodsList.resetFields();
            this.$refs.multipleTable.clearSelection();
            this.selectGoods = [];
            this.selectNum = 0;
            this.centerDialogVisible = false;
        },
        selectCurrentGoods(selection) {
            if (selection.length) {
                selection.forEach((row) => {
                    if (undefined === this.selectGoods[row.id]) {
                        this.selectGoods[row.id] = 1;
                    }
                })
                this.selectNum += selection.length;
            } else {
                this.goods.data.forEach((row) => {
                    if (undefined !== this.selectGoods[row.id]) {
                        delete this.selectGoods[row.id];
                    }
                })
                this.selectNum -= this.goods.data.length;
            }
        }
    }
}
</script>
