<template>
    <div class="page" :class="{ 'page--iphoneX': iphoneX }">
        <!-- 基本信息 -->
        <div class="form-card">
            <div class="head">
                <div class="tit">基本信息</div>
                <div class="switch"></div>
            </div>
            <section class="form-item">
                <div class="label">
                    <span class="required">*</span>
                    店铺：
                </div>
                <div class="box">
                    <!-- <picker
                        :mode="'selector'"
                        :range="storeList"
                        :range-key="'name'"
                        @change="pickerStoreChange"
                    > -->
                    <input
                        type="text"
                        v-model="baseInfo._storeName"
                        :disabled="true"
                        placeholder="请选择"
                    />
                    <!-- </picker> -->
                </div>
            </section>
            <section class="form-item">
                <div class="label">
                    <span class="required">*</span>
                    商品条码：
                </div>
                <div class="box">
                    <input
                        type="text"
                        v-model="baseInfo.barCode"
                        @confirm="getBarCodeGood"
                    />
                </div>
                <div class="tool code-tool">
                    <span class="generate" @click="createBarcode()">生成</span>
                    <my-image
                        class="scan-img"
                        @click="scan"
                        src="/static/icon/scan.png"
                    ></my-image>
                </div>
            </section>

            <section class="form-item">
                <div class="label">
                    <span class="required">*</span>
                    商品标题：
                </div>
                <div class="box">
                    <input type="text" v-model="baseInfo.name" />
                </div>
            </section>
            <section class="form-item">
                <div class="label">
                    <span class="required hide">*</span>
                    初始销量：
                </div>
                <div class="box">
                    <input type="number" v-model="baseInfo.initialSale" />
                </div>
            </section>

            <section class="form-item">
                <div class="label">
                    <span class="required">*</span>
                    分类：
                </div>
                <div class="box">
                    <div
                        class="type-tip"
                        v-if="cateList.length === 0"
                        @touchstart.stop
                    >
                        加载中...
                    </div>
                    <div
                        class="type-item"
                        v-for="(item, index) of typeList"
                        :key="index"
                    >
                        <picker
                            :mode="'multiSelector'"
                            :range="cateList"
                            :range-key="'name'"
                            @columnchange="typeColumnchange"
                            @change="pickerTypeChange($event, index)"
                        >
                            <input
                                type="text"
                                :disabled="true"
                                :value="item.name"
                                placeholder="请选择"
                            />
                        </picker>
                        <span
                            class="remove-text"
                            @click="typeRemove(index, item)"
                            >删除</span
                        >
                    </div>
                    <div class="add-type" @click="addType">增加分类</div>
                </div>
            </section>
        </div>
        <!-- 规格 -->
        <div class="form-card sepc-card">
            <div class="head">
                <div class="tit">规格</div>
                <div class="switch"></div>
            </div>
            <section class="form-item">
                <div class="label">
                    <span class="required">*</span>
                    规格数目：
                </div>
                <div class="box">
                    <ul class="spec-list">
                        <li
                            :class="{ on: specIndex === 0 }"
                            @click="specClick(0)"
                        >
                            单品
                        </li>
                        <li
                            :class="{ on: specIndex === 1 }"
                            @click="specClick(1)"
                        >
                            一种
                        </li>
                        <li
                            :class="{ on: specIndex === 2 }"
                            @click="specClick(2)"
                        >
                            两种
                        </li>
                        <li
                            :class="{ on: specIndex === 3 }"
                            @click="specClick(3)"
                        >
                            三种
                        </li>
                    </ul>
                </div>
            </section>
            <section
                class="form-item"
                v-if="specIndex === 1 || specIndex === 2 || specIndex === 3"
            >
                <div class="label">
                    <span class="required">*</span>
                    规格一：
                </div>
                <div class="box">
                    <div class="spec-view" @click="specEdit(1)">
                        <span class="text" :class="{ dis: !specData1 }">{{
                            specData1 | arrView
                        }}</span>
                        <my-image
                            class="spec-link"
                            src="/static/common/arrows_left.png"
                        ></my-image>
                    </div>
                </div>
            </section>
            <section
                class="form-item"
                v-if="specIndex === 2 || specIndex === 3"
            >
                <div class="label">
                    <span class="required">*</span>
                    规格二：
                </div>
                <div class="box">
                    <div class="spec-view" @click="specEdit(2)">
                        <span class="text" :class="{ dis: !specData2 }">{{
                            specData2 | arrView
                        }}</span>
                        <my-image
                            class="spec-link"
                            src="/static/common/arrows_left.png"
                        ></my-image>
                    </div>
                </div>
            </section>
            <section class="form-item" v-if="specIndex === 3">
                <div class="label">
                    <span class="required">*</span>
                    规格三：
                </div>
                <div class="box">
                    <div class="spec-view" @click="specEdit(3)">
                        <span class="text" :class="{ dis: !specData3 }">{{
                            specData3 | arrView
                        }}</span>
                        <my-image
                            class="spec-link"
                            src="/static/common/arrows_left.png"
                        ></my-image>
                    </div>
                </div>
            </section>

            <!-- 单品 -->
            <black v-if="specIndex === 0">
                <section class="form-item">
                    <div class="label">
                        <span class="required">*</span>
                        价格：
                    </div>
                    <div class="box">
                        <input type="digit" v-model="baseInfo.price" />
                    </div>
                    <div class="tool">
                        <span class="">元</span>
                    </div>
                </section>
                <section class="form-item">
                    <div class="label">
                        <span class="required hide">*</span>
                        进货价：
                    </div>
                    <div class="box">
                        <input type="digit" v-model="baseInfo.supplyPrice" />
                    </div>
                    <div class="tool">
                        <span class="">元</span>
                    </div>
                </section>

                <section class="form-item">
                    <div class="label">
                        <span class="required hide">*</span>
                        成本：
                    </div>
                    <div class="box">
                        <input type="digit" v-model="baseInfo.cost" />
                    </div>
                    <div class="tool">
                        <span class="">元</span>
                    </div>
                </section>
                <section class="form-item">
                    <div class="label">
                        <span class="required hide">*</span>
                        划线价：
                    </div>
                    <div class="box">
                        <input type="digit" v-model="baseInfo.tagPrice" />
                    </div>
                    <div class="tool">
                        <span class="">元</span>
                    </div>
                </section>
                <section class="form-item">
                    <div class="label">
                        <span class="required">*</span>
                        重量：
                    </div>
                    <div class="box">
                        <input type="number" v-model="baseInfo.weight" />
                    </div>
                    <div class="tool">
                        <span class="">克</span>
                    </div>
                </section>

                <section class="form-item">
                    <div class="label">
                        <span class="required">*</span>
                        库存：
                    </div>
                    <div class="box">
                        <input type="number" v-model="baseInfo.stock" />
                    </div>
                </section>

                <section class="form-item">
                    <div class="label">
                        <span class="required">*</span>
                        sku编码：
                    </div>
                    <div class="box">
                        <input type="digit" v-model="baseInfo.skuCode" />
                    </div>
                    <div class="tool code-tool">
                        <span class="generate" @click="generateCode('skuCode')"
                            >生成</span
                        >
                    </div>
                </section>
            </black>
            <black v-if="specIndex !== 0">
                <section
                    class="spec-item"
                    v-for="item of skuTableData"
                    :key="item.key"
                >
                    <div class="spec-head" @click="specForm(item)">
                        <span class="name">组合一：{{ item.key }}</span>
                        <my-image
                            class="img"
                            src="/static/common/arrows_left.png"
                        ></my-image>
                    </div>
                    <div class="con">
                        <div class="con-item">
                            价格<span class="required">*</span>：{{
                                item.price
                            }}
                        </div>
                        <div class="con-item">
                            库存<span class="required">*</span>：{{
                                item.stock
                            }}
                        </div>
                    </div>
                </section>
            </black>
        </div>
        <!-- 图片 -->
        <div class="form-card img-card">
            <section class="form-img-item">
                <div class="tit"><span class="required">*</span>封面图</div>
                <div class="list">
                    <easy-upload
                        :types="'image'"
                        :value="mainImage"
                        :uploadCount="1"
                        :openCilp="true"
                        @change="minImgChange"
                    ></easy-upload>
                </div>
            </section>
            <section class="form-img-item">
                <div class="tit"><span class="required">*</span>主图</div>
                <div class="list">
                    <easy-upload
                        :types="'image'"
                        :value="productForm.images"
                        :uploadCount="100"
                        @change="imagesChange"
                    ></easy-upload>
                </div>
            </section>
            <section class="form-img-item">
                <div class="tit">
                    <span class="required hide">*</span>详情图
                </div>
                <div class="list">
                    <easy-upload
                        :types="'image'"
                        :value="productForm.detailImages"
                        :uploadCount="100"
                        @change="detailImagesChange"
                    ></easy-upload>
                </div>
            </section>
            <section class="form-img-item">
                <div class="tit">
                    <span class="required hide">*</span>视频封面
                </div>
                <div class="list">
                    <easy-upload
                        :types="'image'"
                        :value="videoConver"
                        :uploadCount="1"
                        @change="videoConverChange"
                    ></easy-upload>
                </div>
            </section>
            <section class="form-img-item">
                <div class="tit">
                    <span class="required hide">*</span>视频<span
                        class="gray-text"
                        >(视频文件最大不超过100M)</span
                    >
                </div>
                <div class="list">
                    <easy-upload
                        :types="'video'"
                        v-model="video"
                        :upload_max="100"
                        :uploadCount="1"
                        @change="videoChange"
                    ></easy-upload>
                </div>
            </section>
            <section class="form-item" style="border-top: 1px solid #f1f1f1;margin-top:10px;">
                <div class="label">
                    <span class="required hide">*</span>
                    商品描述：
                </div>
                <div class="box">
                    <textarea
                        v-model="baseInfo.summary"
                        :maxlength="1048"
                        :auto-height="true"
                    ></textarea>
                </div>
            </section>
        </div>
        <!-- 其他 -->
        <div class="form-card">
            <div class="head">
                <div class="tit">其他信息</div>
                <div class="switch">
                    <switch :checked="showOther" @change="otherChange"></switch>
                </div>
            </div>
            <block v-if="showOther">
                <section class="form-item">
                    <div class="label">
                        <span class="required">*</span>
                        商品编码：
                    </div>
                    <div class="box">
                        <input type="text" v-model="baseInfo.code" />
                    </div>
                    <div class="tool code-tool">
                        <span class="generate" @click="generateCode('code')"
                            >生成</span
                        >
                    </div>
                </section>
                <section class="form-item">
                    <div class="label">
                        <span class="required">*</span>
                        模板详情：
                    </div>
                    <div class="box">
                        <radio-group @change="tempChange">
                            <label>
                                <radio
                                    :value="true"
                                    :checked="productForm.useTemplate === true"
                                />
                                <text>是</text>
                            </label>
                            <label>
                                <radio
                                    :value="false"
                                    :checked="productForm.useTemplate === false"
                                />
                                <text>否</text>
                            </label>
                        </radio-group>
                    </div>
                </section>
                <section class="form-item">
                    <div class="label">
                        <span class="required">*</span>
                        出售方式：
                    </div>
                    <div class="box">
                        <picker
                            :mode="'selector'"
                            :range="sellType"
                            :range-key="'key'"
                            @change="pickerStatusChange"
                        >
                            <input
                                type="text"
                                :disabled="true"
                                v-model="baseInfo._statusName"
                                placeholder="请选择"
                            />
                        </picker>
                    </div>
                </section>
                <section class="form-item">
                    <div class="label">
                        <span class="required hide">*</span>
                        限购数：
                    </div>
                    <div class="box">
                        <input
                            type="number"
                            v-model="baseInfo.maxBuyableCount"
                        />
                    </div>
                </section>
                <section class="form-item">
                    <div class="label">
                        <span class="required hide">*</span>
                        起购数：
                    </div>
                    <div class="box">
                        <input type="number" v-model="baseInfo.minBuyCount" />
                    </div>
                </section>
                <!-- <section class="form-item">
                    <div class="label">
                        <span class="required">*</span>
                        供应商：
                    </div>
                    <div class="box">
                        <picker :mode="'selector'" :range="supplierList">
                            <input
                                type="text"
                                :disabled="true"
                                placeholder="请选择"
                            />
                        </picker>
                    </div>
                </section> -->
            </block>
        </div>

        <div class="btns">
            <button type="button" class="btn" @click="save('back')">
                保存返回
            </button>
            <button type="button" class="btn" @click="save('next')">
                保存继续
            </button>
        </div>

        <div class="spec-set-modal"></div>
    </div>
</template>

<script>
import MyImage from "../../components/image/index";
import EasyUpload from "../../components/easy-upload/easy-upload";

export default {
    name: "",
    components: { MyImage, EasyUpload },
    filters: {
        arrView(val) {
            let str = "";
            if (val) {
                str += val.name + ": ";
                for (let item of val.list) {
                    str += item + ",";
                }
                str = str.replace(/,$/, "");
            }
            return str;
        },
    },

    // 数据
    data() {
        return {
            sellType: [
                { key: "立即出售", value: 1 },
                { key: "放入仓库", value: 0 },
            ], // 出售方式
            supplierList: ["测试供应商"], // 供应商
            storeList: [], // 店铺列表
            cateList: [], // 分类列表
            showOther: false, // 显示其他

            barCodeData: {}, // 条码扫描数据

            // 选中的分类列表 {id,name}
            typeList: [{}],

            // 基本信息表, _为前端临时用
            baseInfo: {
                storeId: "", // 店铺id
                _storeName: "", // 店铺名 前台显示用
                barCode: "", // 条码
                name: "", // 标题
                code: "", // 编码
                summary: "", // 描述
                productTypeIds: [], // 分类

                price: 0, // 价格
                supplyPrice: 0, // 进货价
                cost: 0, // 成本
                tagPrice: 0, //划线价，单位为分
                weight: 0, //商品重量，单位为g
                stock: 0, // 库存
                skuCode: "", // sku编码

                initialSale: 0, // 初始销量
                status: 1, // 出售方式 0-放入仓库（即没有上架），1-立即出售（即上架）
                _statusName: "立即出售",
                maxBuyableCount: 0, // 限购数
                minBuyCount: 0,

                mainImage: "", // 封面图 300 *300
            },
            productForm: {
                useTemplate: true, // 是否使用模板

                images: [], // 主图
                detailImages: [], // 详情图
                video: "",
                videoConver: "",
            },
            mainImage: [],
            videoConver: [],
            video: [],

            // 规格
            specIndex: 0,
            specData1: null, // {name,list,columnName}
            specData2: null, // {name,list,columnName}
            specData3: null, // {name,list,columnName}
            curSpecIndex: 0, // 当前编辑specData
            skuTableData: [], // sku表格数据  详情见initSkuTable
            skuAttrs: {}, // sku后台保存用
            submitLoading: false,
        };
    },
    onLoad() {
        this.reset();
        // this.getStore();
        if (this.user.storeId) {
            this.baseInfo.storeId = this.user.storeId;
            this.baseInfo._storeName = this.user.storeName;
        }
        this.getClassify(this.baseInfo.storeId);
    },

    async onShow() {
        // 规格设置
        console.log("specData", this.$store.state.common.specData);
        if (this.$store.state.common.specData) {
            switch (this.curSpecIndex) {
                case 1:
                    this.specData1 = this.$store.state.common.specData;
                    break;
                case 2:
                    this.specData2 = this.$store.state.common.specData;
                    break;
                case 3:
                    this.specData3 = this.$store.state.common.specData;
                    break;
            }
            this.$store.commit("common/update", {
                specData: null,
            });
            this.initSkuTable();
        }

        // sku值
        console.log("skuItem", this.$store.state.common.skuItem);
        if (this.$store.state.common.skuItem) {
            let d = this.$store.state.common.skuItem;
            let arr = [];
            for (let item of this.skuTableData) {
                if (item.key === d.key) {
                    arr.push(d);
                } else {
                    arr.push(item);
                }
            }
            this.$store.commit("common/update", {
                skuItem: null,
            });
            this.skuTableData = arr;
        }
    },

    // 函数
    methods: {
        // 获取店铺
        getStore() {
            this.api.get("/Store/GetShopList").then((res) => {
                this.storeList = res.data;
            });
        },

        // 获取分类
        getClassify(storeId) {
            this.api
                .get("/Product/GetProductType", {
                    storeId,
                })
                .then((res) => {
                    let arr = [res.data];
                    if (res.data[0].children) {
                        arr.push(res.data[0].children);
                    } else {
                        arr.push([]);
                    }
                    this.cateList = arr;
                });
        },

        // 条码回车
        barCodeKeyup() {
            let self = this;
            if (self.baseInfo.barCode) {
                self.getBarCodeGood();
            }
        },

        // 条码扫描
        scan() {
            let self = this;
            uni.scanCode({
                scanType: "barCode",
                success(res) {
                    console.log("扫码", res);
                    if (res.scanType === "EAN_13") {
                        let code = res.result;
                        self.baseInfo.barCode = code;
                        self.baseInfo.code = code;
                        self.baseInfo.skuCode = code;
                        uni.showLoading({
                            title: "识别条码中...",
                        });
                        self.getBarCodeGood();
                    } else {
                        self.fn.showToast("扫码失败,不是有效条码,请重新扫描");
                    }
                },
                fail(res) {
                    self.fn.showToast("扫码失败");
                    console.log("扫码失败：", res);
                },
            });
        },

        // 获取条码商品
        getBarCodeGood() {
            let self = this;
            this.api
                .get(
                    "/Product/GetProductByBarcode",
                    {
                        barcode: self.baseInfo.barCode,
                    },
                    { pass: true }
                )
                .then((res) => {
                    uni.hideLoading();
                    if (res.code === "200203") {
                        // 标准库存在
                        self.barCodeData = res.data;
                        self.pullBarCodeData();
                    } else if (res.code === "200202") {
                        // 其他门店存在
                        self.barCodeData = res.data;
                        self.fn
                            .showModal({
                                content: "该条码在其他门店存在数据，是否复制",
                            })
                            .then((res) => {
                                if (res.confirm) {
                                    self.pullBarCodeData();
                                }
                            });
                    } else if (res.code === "200201") {
                        // 当前门店存在
                        self.barCodeData = res.data;
                        self.fn
                            .showModal({
                                content:
                                    "该条码在当前门店存在已有数据，是否去编辑",
                            })
                            .then((res) => {
                                if (res.confirm) {
                                    self.router.replace({
                                        path: "/pages/manage/edit-good-form",
                                        query: {
                                            id: self.barCodeData.baseInfo.id,
                                        },
                                    });
                                }
                            });
                    } else {
                        self.fn.showToast("当前条码无已有商品数据");
                    }
                });
        },

        // 赋值条码数据
        pullBarCodeData() {
            let data = this.barCodeData;
            this.baseInfo = {
                ...data.baseInfo,
            };
            if (data.baseInfo.mainImage) {
                this.mainImage = [data.baseInfo.mainImage];
            } else {
                this.mainImage = [];
            }
            if (data.video) {
                this.video = [data.video];
            } else {
                this.video = [];
            }
            this.productForm.useTemplate = data.useTemplate;
            this.productForm.images = data.images;
            this.productForm.detailImages = data.detailImages;

            // 店铺不变
            if (this.user.storeId) {
                this.baseInfo.storeId = this.user.storeId;
                this.baseInfo._storeName = this.user.storeName;
            }

            // 状态
            this.baseInfo.status = 1;
            this.baseInfo._statusName = "立即出售";

            // 价格处理
            this.baseInfo.price = this.baseInfo.price / 100;
            this.baseInfo.supplyPrice = this.baseInfo.supplyPrice / 100;
            this.baseInfo.cost = this.baseInfo.cost / 100;
            this.baseInfo.tagPrice = this.baseInfo.tagPrice / 100;

            //编码 sku吗 等于条码
            if (!this.baseInfo.code) {
                this.baseInfo.code = this.baseInfo.barCode;
            }
            if (!this.baseInfo.skuCode) {
                this.baseInfo.skuCode = this.baseInfo.barCode;
            }

            // 多规格还原
            this.specClick(0);
            this.specData1 = null;
            this.specData2 = null;
            this.specData3 = null;
            this.curSpecIndex = 0;
            this.skuTableData = [];
            this.skuAttrs = {};

            console.log(this.baseInfo);

            this.$forceUpdate();
        },

        // 生成编码
        generateCode(name) {
            // 后台编码生成方式
            const timestamp = Date.parse(new Date());
            this.baseInfo[name] = timestamp;
        },
        //随机生成13位条形码
        createBarcode() {
            const timestamp = Date.parse(new Date());
            this.baseInfo.barCode = timestamp;
            if (!this.baseInfo.code) {
                this.baseInfo.code = timestamp;
            }
            if (!this.baseInfo.skuCode) {
                this.baseInfo.skuCode = timestamp;
            }
        },

        // 其他面板切换
        otherChange(e) {
            this.showOther = !this.showOther;
        },

        // 模板详情切换
        tempChange(e) {
            let val = e.target.value;
            if (val === "true") {
                this.productForm.useTemplate = true;
            } else {
                this.productForm.useTemplate = false;
            }
        },

        // 主图
        minImgChange(e) {
            this.baseInfo.mainImage = e[0] || "";
        },
        // 视频图
        videoConverChange(e) {
            this.productForm.videoConver = e[0] || "";
        },
        // 视频
        videoChange(e) {
            this.productForm.video = e[0] || "";
        },

        // 封面图
        imagesChange(e) {
            this.productForm.images = e;
        },

        // 详情图
        detailImagesChange(e) {
            this.productForm.detailImages = e;
        },

        // picker变化
        // 店铺
        pickerStoreChange(e) {
            let index = e.target.value;
            let val = this.storeList[index];
            this.baseInfo.storeId = val.id;
            this.baseInfo._storeName = val.name;
            this.typeList = [{}];
            this.cateList = [];
            this.getClassify(val.id);
        },

        // 分类
        addType() {
            this.typeList.push({});
        },
        typeRemove(i) {
            this.typeList.splice(i, 1);
            this.typeList = [...this.typeList];
            let ids = [];
            for (let item of this.baseInfo.productTypeIds) {
                if (item !== val.id) {
                    ids.push(item);
                }
            }
            this.baseInfo.productTypeIds = ids;
        },
        pickerTypeChange(e, typeListIndex) {
            let index1 = e.detail.value[0] || 0;
            let index2 = e.detail.value[1] || 0;
            let name = this.cateList[0][index1].name;
            let id = this.cateList[0][index1].id;
            if (this.cateList[1].length) {
                name += "/" + this.cateList[1][index2].name;
                id = this.cateList[1][index2].id;
            }
            this.typeList[typeListIndex].name = name;
            this.typeList[typeListIndex].id = id;
            this.typeList = [...this.typeList];
            let ids = [];
            for (let item of this.typeList) {
                if (item.id) {
                    ids.push(item.id);
                }
            }
            this.baseInfo.productTypeIds = ids;

            this.cateList[1] = this.cateList[0][0].children || [];
        },
        typeColumnchange(e) {
            let column = e.detail.column;
            let index = e.detail.value;
            if (column === 0) {
                let val = this.cateList[0][index];
                if (val.children) {
                    this.cateList[1] = val.children;
                } else {
                    this.cateList[1] = [];
                }
                this.$forceUpdate();
            }
        },

        // 出售方式
        pickerStatusChange(e) {
            let index = e.target.value;
            let val = this.sellType[index];
            this.baseInfo.status = val.value;
            this.baseInfo._statusName = val.key;
        },

        // 保存
        save(type) {
            if (this.submitLoading) {
                return;
            }
            let requiredFile1 = [
                {
                    key: "storeId",
                    msg: "请选择店铺",
                },
                {
                    key: "name",
                    msg: "请输入商品标题",
                },
                {
                    key: "code",
                    msg: "请输入商品编码",
                },
                {
                    key: "productTypeIds",
                    type: "array",
                    msg: "请选择分类",
                },
                {
                    key: "mainImage",
                    msg: "请上传封面图",
                },
            ];
            let requiredSku = [
                {
                    key: "price",
                    msg: "请输入价格",
                },
                {
                    key: "weight",
                    type: "number",
                    msg: "请输入重量",
                },
                {
                    key: "stock",
                    type: "number",
                    msg: "请输入库存",
                },
                {
                    key: "skuCode",
                    msg: "请输入sku编码",
                },
            ];
            let requiredFile2 = [
                {
                    key: "images",
                    type: "array",
                    msg: "请上传主图",
                },
                // {
                //     key: "detailImages",
                //     type: "array",
                //     msg: "请上传详情图",
                // }
            ];

            for (let item of requiredFile1) {
                if (item.type === "array") {
                    if (this.baseInfo[item.key].length === 0) {
                        return this.fn.showToast(item.msg);
                    }
                } else if (item.type === "number") {
                    if (!this.baseInfo[item.key]) {
                        if (String(this.baseInfo[item.key]) !== "0") {
                            return this.fn.showToast(item.msg);
                        }
                    }
                } else {
                    if (!this.baseInfo[item.key]) {
                        return this.fn.showToast(item.msg);
                    }
                }
            }

            for (let item of requiredFile2) {
                if (item.type === "array") {
                    if (this.productForm[item.key].length === 0) {
                        return this.fn.showToast(item.msg);
                    }
                } else if (item.type === "number") {
                    if (!this.productForm[item.key]) {
                        if (String(this.productForm[item.key]) !== "0") {
                            return this.fn.showToast(item.msg);
                        }
                    }
                } else {
                    if (!this.productForm[item.key]) {
                        return this.fn.showToast(item.msg);
                    }
                }
            }
            // 规格判断
            let skuInfo = "";
            if (this.specIndex === 0) {
                for (let item of requiredSku) {
                    if (item.type === "array") {
                        if (this.baseInfo[item.key].length === 0) {
                            return this.fn.showToast(item.msg);
                        }
                    } else if (item.type === "number") {
                        if (!this.baseInfo[item.key]) {
                            if (String(this.baseInfo[item.key]) !== "0") {
                                return this.fn.showToast(item.msg);
                            }
                        }
                    } else {
                        if (!this.baseInfo[item.key]) {
                            return this.fn.showToast(item.msg);
                        }
                    }
                }
            } else {
                if (this.skuTableData.length === 0) {
                    return this.fn.showToast("请先选择规格");
                }
                // 价格转换
                let arr = JSON.parse(JSON.stringify(this.skuTableData));
                for (let item of arr) {
                    item.price = parseInt(Number(item.price) * 100);
                    item.supplyPrice = parseInt(Number(item.supplyPrice) * 100);
                    item.cost = parseInt(Number(item.cost) * 100);
                    item.tagPrice = parseInt(Number(item.tagPrice) * 100);
                }
                skuInfo = JSON.stringify({
                    skuAttrs: this.skuAttrs,
                    skus: arr,
                });
            }

            let sendData = {
                baseInfo: {
                    ...this.baseInfo,
                },
                ...this.productForm,
                hotSaleRecommendIds: [],
                businessRecommendIds: [],
                participated: false,
                participatedBox: false,
                skuInfo: skuInfo,
            };
            if (sendData.baseInfo.weight) {
                sendData.baseInfo.weight = Number(sendData.baseInfo.weight);
            }
            if (sendData.baseInfo.stock) {
                sendData.baseInfo.stock = Number(sendData.baseInfo.stock);
            }
            if (sendData.baseInfo.initialSale) {
                sendData.baseInfo.initialSale = Number(
                    sendData.baseInfo.initialSale
                );
            }
            //规格判断
            if (this.specIndex === 0) {
                sendData.baseInfo.price = parseInt(
                    Number(sendData.baseInfo.price) * 100
                );
                sendData.baseInfo.supplyPrice = parseInt(
                    Number(sendData.baseInfo.supplyPrice) * 100
                );
                sendData.baseInfo.cost = parseInt(
                    Number(sendData.baseInfo.cost) * 100
                );
                sendData.baseInfo.tagPrice = parseInt(
                    Number(sendData.baseInfo.tagPrice) * 100
                );
            }
            this.submitLoading = true;

            uni.showLoading({
                title: "提交中...",
                mask: true,
            });
            this.api
                .post("/product/SaveEdit", sendData, { pass: true })
                .then((res) => {
                    this.submitLoading = false;
                    uni.hideLoading();
                    if (res.success) {
                        if (type === "next") {
                            this.fn.showToast("保存成功");
                            this.reset();
                        } else {
                            this.fn.showToast("保存成功");
                            this.router.back();
                        }
                    } else {
                        this.fn.showModal({
                            content: res.message,
                            showCancel: false,
                        });
                    }
                });
        },

        // 重置
        reset() {
            this.typeList = [{}];
            this.baseInfo = {
                storeId: "", // 店铺id
                _storeName: "", // 店铺名 前台显示用
                barCode: "", // 条码
                name: "", // 标题
                code: "", // 编码
                summary: "", // 描述
                productTypeIds: [], // 分类

                price: 0, // 价格
                supplyPrice: 0, // 进货价
                cost: 0, // 成本
                tagPrice: 0, //划线价，单位为分
                weight: 0, //商品重量，单位为g
                stock: 0, // 库存
                skuCode: "", // sku编码

                initialSale: 0, // 初始销量
                status: 1, // 出售方式 0-放入仓库（即没有上架），1-立即出售（即上架）
                _statusName: "立即出售",
                maxBuyableCount: 0, // 限购数
                minBuyCount: 0,

                mainImage: "", // 主图 300 *300
            };
            this.productForm = {
                useTemplate: true, // 是否使用模板

                images: [], // 封面图
                detailImages: [], // 详情图
                video: "",
            };

            this.video = [];
            this.mainImage = [];
            if (this.user.storeId) {
                this.baseInfo.storeId = this.user.storeId;
                this.baseInfo._storeName = this.user.storeName;
            }

            this.specIndex = 0;
            this.specData1 = null;
            this.specData2 = null;
            this.specData3 = null;
            this.curSpecIndex = 0;
            this.skuTableData = [];
            this.skuAttrs = {};

            uni.pageScrollTo({
                scrollTop: 0,
            });
            this.$forceUpdate();
        },

        // 规格点击
        specClick(index) {
            this.specIndex = index;
            switch (index) {
                case 0:
                    this.specData1 = null;
                    this.specData2 = null;
                    this.specData3 = null;
                    this.skuTableData = [];
                    this.skuAttrs = {};
                    this.curSpecIndex = 0;
                    break;
                case 1:
                    this.specData2 = null;
                    this.specData3 = null;
                    break;
                case 2:
                    this.specData3 = null;
                    break;
            }
            if (index !== 0) {
                this.baseInfo.price = 0;
                this.baseInfo.supplyPrice = 0;
                this.baseInfo.cost = 0;
                this.baseInfo.tagPrice = 0;
                this.baseInfo.weight = 0;
                this.baseInfo.stock = 0;
                this.baseInfo.skuCode = "";
            }
        },

        // 规格设置
        specEdit(index) {
            switch (index) {
                case 1:
                    this.$store.commit("common/update", {
                        specData: this.specData1,
                    });
                    break;
                case 2:
                    this.$store.commit("common/update", {
                        specData: this.specData2,
                    });
                    break;
                case 3:
                    this.$store.commit("common/update", {
                        specData: this.specData3,
                    });
                    break;
            }
            this.curSpecIndex = index;
            this.router.push("/pages/manage/spec-edit");
        },

        // 规格表单
        specForm(item) {
            console.log(item);
            this.$store.commit("common/update", {
                skuItem: item,
            });
            this.router.push("/pages/manage/spec-item-form");
        },

        // 生成skuTable
        initSkuTable() {
            let arr = [];
            let skuAttrs = {};
            if (this.specData1) {
                for (let item of this.specData1.list) {
                    if (this.specData2) {
                        for (let item2 of this.specData2.list) {
                            if (this.specData3) {
                                for (let item3 of this.specData3.list) {
                                    let tabItem = this.initSkuItem({
                                        key: item + "-" + item2 + "-" + item3,
                                        [this.specData1.columnName]: item,
                                        [this.specData2.columnName]: item2,
                                        [this.specData3.columnName]: item3,
                                    });
                                    skuAttrs[
                                        this.specData1.columnName
                                    ] = this.specData1.name;
                                    skuAttrs[
                                        this.specData2.columnName
                                    ] = this.specData2.name;
                                    skuAttrs[
                                        this.specData3.columnName
                                    ] = this.specData3.name;
                                    arr.push(tabItem);
                                }
                            } else {
                                let tabItem = this.initSkuItem({
                                    key: item + "-" + item2,
                                    [this.specData1.columnName]: item,
                                    [this.specData2.columnName]: item2,
                                });
                                skuAttrs[
                                    this.specData1.columnName
                                ] = this.specData1.name;
                                skuAttrs[
                                    this.specData2.columnName
                                ] = this.specData2.name;
                                arr.push(tabItem);
                            }
                        }
                    } else {
                        let tabItem = this.initSkuItem({
                            key: item,
                            [this.specData1.columnName]: item,
                        });
                        skuAttrs[
                            this.specData1.columnName
                        ] = this.specData1.name;
                        arr.push(tabItem);
                    }
                }
            }

            let arr2 = [];
            for (let item of arr) {
                let f = false;
                for (let skuItem of this.skuTableData) {
                    if (item.key === skuItem.key) {
                        arr2.push(skuItem);
                        f = true;
                    }
                }
                if (!f) {
                    arr2.push(item);
                }
            }
            this.skuTableData = arr2;
            this.skuAttrs = skuAttrs;
        },

        // 生成sku某一项
        initSkuItem(obj = {}) {
            //
            //this.fn.guid()
            return {
                code: String(Date.now()), // 编码
                cost: 0, // 成本
                img:
                    "https://oss.ixiaokejia.com/images/common/20201021094129.png", // sku图
                key: "", //关键字
                order: 0, // 顺序
                price: 0,
                skuId: "",
                stock: 0, // 库存
                supplyPrice: 0, // 进货价
                tagPrice: 0, // 标签价
                weight: 0, // 重量
                ...obj,
            };
        },
    },

    // 数据计算
    computed: {
        user() {
            return this.$store.state.user.user;
        },
    },

    // 数据监听
    watch: {},
};
</script>

<style lang="scss" scoped>
.page {
    padding-bottom: px(180);
}
.form-card {
    background-color: #fff;
    padding: 0 px(30);
    & ~ .form-card {
        margin-top: px(25);
    }
    .head {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: px(140);
        background-color: #fbfbfb;
        border-bottom: 1px solid #f1f1f1;
        border-top: 1px solid #f1f1f1;
        font-size: px(48);
    }
}
.required {
    color: #f00;
    font-size: px(44);
    &.hide {
        visibility: hidden;
    }
}
.form-item {
    display: flex;
    min-height: px(140);
    padding: px(30) 0;
    box-sizing: border-box;
    align-items: center;
    font-size: px(44);
    & ~ .form-item {
        border-top: 1px solid #f1f1f1;
    }
    .label {
        width: px(240);
        flex-shrink: 0;
        color: #999;
        margin-right: px(10);
    }
    .box {
        width: 100%;
        position: relative;
        input {
            width: 100%;
        }
    }
    .tool {
        flex-shrink: 0;
        color: #999;
        margin-left: px(10);
    }
    textarea,
    input {
        max-width: 100%;
        width: 100%;
    }
}
.code-tool {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .scan-img {
        flex-shrink: 0;
        width: px(80);
        height: px(80);
        /deep/ img {
            width: px(80);
            height: px(80);
        }
    }
    .generate {
        color: #0097d1;
        margin-right: px(30);
        flex-shrink: 0;
    }
}
radio-group {
    label ~ label {
        margin-left: px(40);
    }
}
.img-card {
    padding-top: px(30);
    padding-bottom: px(30);
}
.form-img-item {
    .tit {
        padding: px(30);
        font-size: px(44);
    }
}
.btns {
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 100;
}
button::after {
    border: none;
    display: none;
}
button::before {
    border: none;
    display: none;
}
.page--iphoneX {
    .btns {
        padding-bottom: px(30);
        background-color: rgb(0, 188, 38);
    }
}
.btn {
    background-color: rgb(0, 188, 38);
    color: #fff;
    border-radius: 0;
    font-size: px(50);
    border: none;
    width: 50%;
    & ~ .btn {
        border-left: 1px solid #999;
    }
}
.add-type {
    width: 100%;
    font-size: px(40);
    color: #0097d1;
    padding: px(20) 0;
}
.type-item {
    padding: px(20) 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #f1f1f1;
    .remove-text {
        color: red;
        flex-shrink: 0;
        margin-left: px(10);
        padding-left: px(30);
    }
}
.type-tip {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 100;
    background-color: rgba(0, 0, 0, 0.3);
    color: #fff;
    font-size: px(44);
    display: flex;
    justify-content: center;
    align-items: center;
    pointer-events: none;
}
.min-radio {
    transform: scale(0.8);
}
.spec-list {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    li {
        width: 25%;
        font-size: px(40);
        height: px(100);
        border: 1px solid #f1f1f1;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #999;
        & ~ li {
            // border-left: none;
        }
        &.on {
            color: rgb(0, 188, 38);
            border-color: rgb(0, 188, 38);
        }
    }
}
.spec-view {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    .text {
        font-size: px(40);
        &.dis {
            color: #999;
        }
    }
    .spec-link {
        width: px(50);
        height: px(50);
        margin-left: px(20);
        transform: rotate(180deg);
        /deep/ img {
            width: px(50);
            height: px(50);
        }
    }
}
.spec-item {
    border: 1px solid #f1f1f1;
    margin-top: px(30);
    .spec-head {
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #f9f9f9;
        border-bottom: 1px solid #f1f1f1;
        padding: px(0) px(30);
        height: px(120);
        line-height: px(100);
        font-size: px(44);

        .img {
            width: px(40);
            height: px(40);
            transform: rotate(180deg);
            /deep/ img {
                width: px(40);
                height: px(40);
            }
        }
    }
    .con {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: px(30) px(30);
    }
    .con-item {
        width: 50%;
        font-size: px(44);
        color: #333;
    }
}
.sepc-card {
    padding-bottom: px(30);
}
.gray-text {
    color: #999;
    display: inline-block;
    margin-left: px(10);
}
</style>