<template>
    <div class="app-container">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" label-position="left">
            <el-form-item label="商品类型" prop="typeEnum">
                <div class="shop_type_box" :class="{ disabled: form.id }">
                    <div class="item" v-for="(item, index) in shopTypes" :key="index"
                        :class="{ active: shopTypesActive == index }" @click="changeTypeEnum(index)">
                        <div class="s_title">{{ item.label }}</div>
                        <div class="intro">（{{ item.intro }}）</div>
                        <div class="active_dot">
                            <i class="el-icon-check"></i>
                        </div>
                    </div>
                </div>
            </el-form-item>
            <el-form-item label="商品名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入商品名称" style="width: 500px;"></el-input>
            </el-form-item>
            <el-form-item label="单位">
                <el-select v-model="form.unitId" placeholder="请选择单位" style="width: 500px;" @change="selectUnitt">
                    <el-option :label="item.name" :value="item.id" v-for="item in units" :key="item.id"></el-option>
                </el-select>
                <el-button type="primary" plain icon="el-icon-plus" @click="$refs.addUnitRef.show()">添加单位</el-button>
                <addUnit ref="addUnitRef" @success="tbShopUnit" />
            </el-form-item>
            <el-form-item label="商品分类" prop="categoryId">
                <el-select v-model="form.categoryId" placeholder="请选择商品分类" style="width: 500px;">
                    <el-option :label="item.name" :value="item.id" v-for="item in categorys" :key="item.id"></el-option>
                </el-select>
                <el-button type="primary" plain icon="el-icon-plus"
                    @click="$refs.addClassifyRef.show()">添加分类</el-button>
                <addClassify ref="addClassifyRef" @success="tbShopCategoryGet" />
            </el-form-item>
            <el-form-item label="商品图片">
                <uploadImg ref="uploadImg" :limit="9" @success="uploadSuccess" @remove="uploadRemove" />
                <div class="tips">注：第一张图为商品封面图，图片尺寸为750×750(可拖动图片排序)</div>
            </el-form-item>
            <el-form-item label="套餐商品" v-if="shopTypes[shopTypesActive].typeEnum == 'group'">
                <el-table :data="form.groupSnap" border v-if="form.groupSnap.length">
                    <el-table-column label="标题" prop="title">
                        <template v-slot="scope">
                            <el-input v-model="scope.row.title" placeholder="请输入标题：自选小吃"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="商品信息">
                        <template v-slot="scope">
                            <div class="shop_list">
                                <div class="item" v-for="item in scope.row.goods" :key="item.id">
                                    <span class="dot"></span>
                                    <div class="name">
                                        <div class="t">{{ item.name }}</div>
                                    </div>
                                    <i class="del el-icon-delete"></i>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="几选几">
                        <template v-slot="scope">
                            <span>{{ scope.row.goods.length }}选</span>
                            <el-input-number v-model="scope.row.number" controls-position="right"
                                :min="1"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="160">
                        <template v-slot="scope">
                            <el-button type="text" @click="tableAddShop(scope.$index, scope.row.goods)">添加商品</el-button>
                            <el-button type="text" @click="form.groupSnap.splice(scope.$index, 1)">删除分组</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-button type="text" @click="$refs.shopListRef.show()">添加分组</el-button>
                <shopList ref="shopListRef" @success="selectShopRes" />
            </el-form-item>
            <el-form-item label="规格属性" v-if="shopTypes[shopTypesActive].typeEnum != 'sku'">
                <el-table :data="form.skuList" border>
                    <el-table-column label="售价" prop="salePrice">
                        <template v-slot="scope">
                            <el-input-number v-model="scope.row.salePrice" controls-position="right"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column label="会员价" prop="memberPrice">
                        <template v-slot="scope">
                            <el-input-number v-model="scope.row.memberPrice"
                                controls-position="right"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column label="成本价" prop="costPrice">
                        <template v-slot="scope">
                            <el-input-number v-model="scope.row.costPrice" controls-position="right"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column label="原价" prop="originPrice">
                        <template v-slot="scope">
                            <el-input-number v-model="scope.row.originPrice"
                                controls-position="right"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column label="库存数量" prop="stockNumber">
                        <template v-slot="scope">
                            <el-input-number v-model="scope.row.stockNumber" :disabled="!!form.id"
                                controls-position="right"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column label="分销金额" prop="firstShared">
                        <template v-slot="scope">
                            <el-input-number v-model="scope.row.firstShared"
                                controls-position="right"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column label="商品条码">
                        <template v-slot="scope">
                            <el-input v-model="scope.row.barCode" disabled></el-input>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="tips" v-if="form.isShowMall">注：小程序商城必须设置库存数量大于0</div>
            </el-form-item>
            <el-form-item label="选择规格" v-if="shopTypes[shopTypesActive].typeEnum == 'sku' && !form.id">
                <el-select v-model="form.specId" placeholder="请选择规格" style="width: 500px;" @change="selectSpecHandle">
                    <el-option :label="item.name" :value="item.id" v-for="item in specList" :key="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item :label="item.name" v-if="selectSpec.length && !isEditor" v-for="item in selectSpec"
                :key="item.name">
                <el-checkbox-group v-model="item.selectSpecResult" @change="selectSpecResultChange">
                    <el-checkbox :label="item" v-for="(item, index) in item.value
" :key="index"></el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item v-if="selectSpecResult && shopTypes[shopTypesActive].typeEnum == 'sku'">
                <el-table :data="form.skuList" border>
                    <el-table-column :label="item.label" :prop="item.value" v-for="(item, index) in specTableHeaders"
                        :key="index">
                    </el-table-column>
                    <el-table-column label="图片" prop="coverImg" width="80">

                        <template v-slot="scope">
                            <uploadImg type="text" :limit="1" @success="res => scope.row.coverImg = res[0]"
                                v-if="!scope.row.coverImg" />
                            <el-image style="width:30px;height:30px;" :src="scope.row.coverImg" v-else />
                        </template>
                    </el-table-column>
                    <el-table-column label="售价" prop="salePrice">
                        <template slot="header" slot-scope="scope">
                            <span>售价</span>
                            <i class="icon el-icon-edit" @click="batchNumber('salePrice')"></i>
                        </template>
                        <template slot-scope="scope">
                            <el-input-number v-model="scope.row.salePrice" controls-position="right"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column label="会员价" prop="memberPrice">
                        <template slot="header" slot-scope="scope">
                            <span>会员价</span>
                            <i class="icon el-icon-edit" @click="batchNumber('memberPrice')"></i>
                        </template>
                        <template slot-scope="scope">
                            <el-input-number v-model="scope.row.memberPrice"
                                controls-position="right"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column label="成本价" prop="costPrice">
                        <template slot="header" slot-scope="scope">
                            <span>成本价</span>
                            <i class="icon el-icon-edit" @click="batchNumber('costPrice')"></i>
                        </template>
                        <template slot-scope="scope">
                            <el-input-number v-model="scope.row.costPrice" controls-position="right"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column label="原价" prop="originPrice">
                        <template slot="header" slot-scope="scope">
                            <span>原价</span>
                            <i class="icon el-icon-edit" @click="batchNumber('originPrice')"></i>
                        </template>
                        <template slot-scope="scope">
                            <el-input-number v-model="scope.row.originPrice"
                                controls-position="right"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column label="库存数量" prop="stockNumber">
                        <template slot="header" slot-scope="scope">
                            <span>库存数量</span>
                            <i class="icon el-icon-edit" @click="batchNumber('stockNumber')" v-if="!form.id"></i>
                        </template>
                        <template slot-scope="scope">
                            <el-input-number v-model="scope.row.stockNumber" :disabled="!!form.id"
                                controls-position="right"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column label="分销金额" prop="firstShared">
                        <template slot="header" slot-scope="scope">
                            <span>分销金额</span>
                            <i class="icon el-icon-edit" @click="batchNumber('firstShared')"></i>
                        </template>
                        <template slot-scope="scope">
                            <el-input-number v-model="scope.row.firstShared"
                                controls-position="right"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column label="商品条码">
                        <template v-slot="scope">
                            <el-input v-model="scope.row.barCode" disabled></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="80">
                        <template v-slot="scope">
                            <el-button type="text" @click="form.skuList.splice(scope.$index, 1)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="tips" v-if="form.isShowMall">注：小程序商城必须设置库存数量大于0</div>
            </el-form-item>
            <el-form-item label="上架区域">
                <div class="shop_type_box">
                    <div class="item" :class="{ active: form.isShowCash }" @click="areaChange('isShowCash')">
                        <div class="s_title">收银台</div>
                        <div class="active_dot">
                            <i class="el-icon-check"></i>
                        </div>
                    </div>
                    <div class="item" :class="{ active: form.isShowMall }" @click="areaChange('isShowMall')">
                        <div class="s_title">小程序商城</div>
                        <div class="active_dot">
                            <i class="el-icon-check"></i>
                        </div>
                    </div>
                </div>
            </el-form-item>
            <el-form-item label="库存开关">
                <el-switch v-model="form.isStock" :active-value="1" :inactive-value="0"></el-switch>
                <div class="tips">注：关闭则不计算出入库数据</div>
            </el-form-item>
            <el-form-item label="标签打印">
                <el-switch v-model="form.enableLabel" :active-value="1" :inactive-value="0"></el-switch>
                <div class="tips">开启后: 收银完成后会自动打印对应数量的标签数</div>
            </el-form-item>
            <el-form-item label="打包费">
                <el-input-number v-model="form.packFee" controls-position="right" :min="0"></el-input-number>
                <div class="tips">单份商品打包费。注：店铺开启外卖模式下该数据才生效</div>
            </el-form-item>
            <el-form-item label="虚拟销量">
                <el-input-number v-model="form.baseSalesNumber" controls-position="right" :min="0"></el-input-number>
            </el-form-item>
            <el-form-item label="排序">
                <el-input-number v-model="form.sort" controls-position="right" :min="0"></el-input-number>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" v-loading="loading" @click="submitHandle">确定</el-button>
                <el-button @click="$router.back()">取消</el-button>
            </el-form-item>
        </el-form>
        <el-dialog title="批量修改" width="400px" :visible.sync="showBatchModal">
            <el-form :model="batchNumberForm">
                <el-form-item>
                    <el-input-number v-model="batchNumberForm.batchNumber" :min="0" controls-position="right"
                        style="width: 100%;"></el-input-number>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showBatchModal = false">取 消</el-button>
                <el-button type="primary" @click="batchNumberFormConfirm">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { tbShopUnit, tbShopCategoryGet, tbProductPost, tbProductSpecGet, tbProductGetDetail, tbProductPut } from "@/api/shop";
import addUnit from './components/addUnit'
import addClassify from './components/addClassify'
import shopList from '@/components/shopList'
import uploadImg from '@/components/uploadImg'
import settings from '@/settings'
import dayjs from 'dayjs'
import { RandomNumBoth } from "@/utils";

export default {
    components: {
        addUnit,
        addClassify,
        uploadImg,
        shopList
    },
    data() {
        return {
            shopTypesActive: 0,
            shopTypes: settings.typeEnum,
            specTableHeaders: [],
            specTableBodys: [],
            specId: '',
            specList: [],
            selectSpec: [],
            selectSpecResult: false,
            defaultSku: {
                salePrice: 0,
                memberPrice: 0,
                costPrice: 0,
                originPrice: 0,
                stockNumber: 0,
                firstShared: 0,
                barCode: `${localStorage.getItem('shopId')}${dayjs().valueOf()}`
            },
            tableAddShopIndex: null,
            isEditor: false,
            loading: false,
            form: {
                id: '',
                typeEnum: 'normal',
                name: '',
                unitId: '',
                unitName: '',
                categoryId: '', // 商品分类id
                coverImg: '',
                images: [],
                shopId: localStorage.getItem('shopId'),
                lowPrice: '',
                skuList: [],
                isShowMall: 1,
                isShowCash: 1,
                isStock: 0,
                packFee: 0,
                specId: '',
                baseSalesNumber: 0,
                sort: 0,
                groupSnap: [],
                specInfo: [],
                selectSpec: [],
                specTableHeaders: [],
                skuSnap: ''
            },
            rules: {
                typeEnum: [
                    {
                        required: true
                    }
                ],
                name: [
                    {
                        required: true,
                        trigger: 'blur',
                        message: '请输入商品名称'
                    }
                ],
                categoryId: [
                    {
                        required: true,
                        trigger: 'change',
                        message: '请选择商品分类'
                    }
                ]
            },
            units: [],
            categorys: [],
            // 批量修改规格
            showBatchModal: false,
            batchNumberKey: '',
            batchNumberForm: {
                batchNumber: 0
            }
        }
    },
    mounted() {
        this.tbShopUnit()
        this.tbShopCategoryGet()
        this.changeTypeEnum(0)

        if (this.$route.query.goods_id) {
            this.tbProductGetDetail()
        }
    },
    methods: {
        // 修改商家区域
        areaChange(key) {
            if (this.form[key] == 1) {
                this.form[key] = 0
            } else {
                this.form[key] = 1
            }
        },
        selectUnitt(e) {
            this.form.unitName = this.units.find(item => item.id == e).name
        },
        // 批量修改规格
        batchNumber(key) {
            this.batchNumberKey = key
            this.showBatchModal = true
        },
        // 确认批量修改规格
        batchNumberFormConfirm() {
            this.form.skuList.map(item => {
                item[this.batchNumberKey] = this.batchNumberForm.batchNumber
            })
            this.showBatchModal = false
            this.batchNumberForm.batchNumber = 0
        },
        // 商品详情
        async tbProductGetDetail() {
            try {
                const res = await tbProductGetDetail(this.$route.query.goods_id)

                // 赋值商品类型
                this.changeTypeEnum(this.shopTypes.findIndex(item => item.typeEnum == res.typeEnum))
                this.specTableHeaders = JSON.parse(res.specTableHeaders)
                this.selectSpec = JSON.parse(res.selectSpec)

                // 初始化上传图片
                this.$refs.uploadImg.fileList = res.images.map(item => {
                    return {
                        url: item
                    }
                })

                this.form = res
                if (res.typeEnum == 'sku') {
                    let skuList = [...res.skuList]
                    let specInfo = JSON.parse(res.specInfo)
                    this.isEditor = true
                    this.form.skuList = skuList.map((item, index) => {
                        specInfo[index].id = item.id
                        return specInfo[index]
                    })
                    this.selectSpecResult = true
                }
            } catch (error) {
                console.log(error)
            }
        },
        // 提交
        submitHandle() {
            this.$refs.formRef.validate(async faild => {
                try {
                    if (faild) {
                        this.loading = true
                        this.form.lowPrice = this.form.skuList[0].salePrice
                        this.form.coverImg = this.form.images[0]
                        this.form.selectSpec = JSON.stringify(this.selectSpec)
                        this.form.specTableHeaders = JSON.stringify(this.specTableHeaders)
                        this.form.specInfo = JSON.stringify(this.form.skuList)
                        if (this.form.id) {
                            await tbProductPut(this.form)
                        } else {
                            await tbProductPost(this.form)
                        }
                        this.$notify({
                            title: '成功',
                            message: `${this.form.id ? '编辑' : '添加'}成功`,
                            type: 'success'
                        });
                        this.$router.back()
                        this.loading = false
                    }
                } catch (error) {
                    this.loading = false
                    console.log(error)
                }
            })
        },
        // 给分组添加商品
        tableAddShop(index, goods) {
            this.tableAddShopIndex = index
            this.$refs.shopListRef.show([...goods])
        },
        // 分组选择商品
        selectShopRes(res) {
            if (this.tableAddShopIndex != null) {
                this.form.groupSnap[this.tableAddShopIndex].goods = res;
                this.tableAddShopIndex = null
            } else {
                this.form.groupSnap.push({
                    title: '',
                    goods: res,
                    number: 1
                })
            }
        },
        // 切换类型
        changeTypeEnum(index) {
            if (this.form.id) return
            this.shopTypesActive = index
            const typeEnum = this.shopTypes[index].typeEnum
            this.form.typeEnum = typeEnum

            if (typeEnum == 'sku') {
                this.tbProductSpecGet()
            } else {
                this.specId = ''
                this.form.specId = ''
                this.selectSpec = []
                this.selectSpecResult = ''
                this.form.skuList = [JSON.parse(JSON.stringify(this.defaultSku))]
            }
        },
        // 上传图片
        uploadSuccess(res) {
            this.form.images.push(res[0])
        },
        // 删除突破按
        uploadRemove(arr) {
            this.form.images = arr
        },
        // 选择规格属性
        selectSpecResultChange() {
            this.createSkuHeader()
            this.createSkuBody()
        },
        // 生成多规格表体
        createSkuBody() {
            let bodys = []
            let skuSnap = []
            for (let item of this.selectSpec) {
                if (item.selectSpecResult.length) {
                    let arr = []
                    for (let val of item.selectSpecResult) {
                        arr.push({
                            [item.name]: val
                        })
                    }
                    skuSnap.push({
                        name: item.name,
                        value: item.selectSpecResult.join(',')
                    })
                    bodys.push(arr)
                }
            }
            this.form.skuSnap = JSON.stringify(skuSnap)

            let arr = this.cartesian(bodys)
            // console.log(arr)
            let newarr = []

            const m = {
                coverImg: '',
                ...this.defaultSku
            }

            for (let item of arr) {
                if (Array.isArray(item)) {
                    let obj = {}
                    let specSnap = []
                    for (let v of item) {
                        for (let key in v) {
                            obj[`${key}`] = v[key]
                            specSnap.push(v[key])
                        }
                    }
                    newarr.push({
                        specSnap: specSnap.join(','),
                        ...m,
                        ...obj,
                        barCode: `${dayjs().valueOf()}${RandomNumBoth(1, 9999)}`
                    })
                } else {
                    let specSnap = []
                    for (let key in item) {
                        specSnap.push(item[key])
                    }
                    newarr.push({
                        specSnap: specSnap.join(','),
                        ...m,
                        ...item,
                        barCode: `${dayjs().valueOf()}${RandomNumBoth(1, 9999)}`
                    })
                }
            }
            this.form.skuList = []
            this.form.skuList = newarr
        },
        // 笛卡尔积算法
        cartesian(arr) {
            if (arr.length < 2) return arr[0] || [];
            return [].reduce.call(arr, (col, set) => {
                let res = [];
                col.forEach(c => {
                    set.forEach(s => {
                        let t = [].concat(Array.isArray(c) ? c : [c]);
                        t.push(s);
                        res.push(t);
                    })
                });
                return res;
            });
        },
        // 生成多规格表头
        createSkuHeader() {
            let i = 0
            const headers = []
            for (let item of this.selectSpec) {
                if (item.selectSpecResult.length) {
                    i++
                    headers.push({
                        label: item.name,
                        value: item.name
                    })
                }
            }
            this.selectSpecResult = i
            this.specTableHeaders = headers
        },
        // 选择规格
        selectSpecHandle(e) {
            this.isEditor = false
            const selectSpec = JSON.parse(JSON.stringify(this.specList.find(item => item.id == e).specList))
            for (let item in selectSpec) {
                selectSpec[item].selectSpecResult = []
            }
            this.selectSpec = selectSpec
            this.form.skuList = []
        },
        // 获取规格列表
        async tbProductSpecGet() {
            try {
                const res = await tbProductSpecGet({
                    shopId: localStorage.getItem('shopId'),
                    sort: 'id',
                    page: 0,
                    size: 100
                })
                this.specList = res.content
            } catch (error) { }
        },
        // 获取单位
        async tbShopUnit() {
            try {
                const res = await tbShopUnit({
                    shopId: localStorage.getItem('shopId'),
                    sort: 'id',
                    page: 0,
                    size: 100
                })
                this.units = res.content
            } catch (error) { }
        },
        // 商品分类列表
        async tbShopCategoryGet() {
            try {
                const res = await tbShopCategoryGet({
                    shopId: localStorage.getItem('shopId'),
                    sort: 'id',
                    page: 0,
                    size: 100
                })
                let categorys = []
                for (let item of res.content) {
                    categorys.push({
                        name: `|----${item.name}`,
                        id: item.id
                    })
                    if (item.childrenList.length) {
                        for (let val of item.childrenList) {
                            categorys.push({
                                name: `|----|----${val.name}`,
                                id: val.id
                            })
                        }
                    }
                }
                this.categorys = categorys
            } catch (error) {
                console.log('商品分类列表', error)
            }
        }
    }
}
</script>

<style scoped lang="scss">
.shop_list {
    .item {
        display: flex;
        align-items: center;

        .dot {
            $size: 6px;
            width: $size;
            height: $size;
            border-radius: 50%;
            background-color: #1890FF;
        }

        .name {
            flex: 1;
            margin-left: 10px;

            .t {
                color: #333;
                font-size: 14px;
                max-width: 100px;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
            }
        }

        .del {
            font-size: 14px;
            color: #999;

            &:hover {
                cursor: pointer;
                color: #555;
            }
        }
    }
}

.icon {
    font-size: 14px;
    color: #1890FF;
    margin-left: 10px;

    &:hover {
        cursor: pointer;
    }
}
</style>