<template>
    <div class="app-container">
        <el-drawer v-model="editDrawer" size="100%" :before-close="handleCancel">
            <el-card class="box-card">
                <h3>商品介绍</h3>
                <el-form ref="goodsRef" :rules="rules" :model="goods" label-width="150px">
                    <el-form-item label="商品编号" prop="goodsSn">
                        <el-input v-model="goods.goodsSn" />
                    </el-form-item>
                    <el-form-item label="商品名称" prop="name">
                        <el-input v-model="goods.name" />
                    </el-form-item>
                    <!-- <el-form-item label="市场售价" prop="counterPrice">
                        <el-input v-model="goods.counterPrice" placeholder="0.00">
                            <template slot="append">元</template>
                        </el-input>
                    </el-form-item> -->
                    <el-form-item label="是否新品">
                        <el-radio-group v-model="goods.isNew">
                            <el-radio :label="true">新品</el-radio>
                            <el-radio :label="false">非新品</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="是否热卖">
                        <el-radio-group v-model="goods.isHot">
                            <el-radio :label="false">普通</el-radio>
                            <el-radio :label="true">热卖</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="是否在售">
                        <el-radio-group v-model="goods.isOnSale">
                            <el-radio :label="true">在售</el-radio>
                            <el-radio :label="false">未售</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="商品图片" prop="picUrl">
                        <el-upload :action="uploadPath" :show-file-list="false" :headers="headers"
                            :on-success="uploadPicUrl" class="avatar-uploader" accept=".jpg,.jpeg,.png,.gif">
                            <!-- <img v-if="goods.picUrl" :src="goods.picUrl" class="avatar" /> -->
                            <img v-if="goods.picUrl" :src="goods.picUrl" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>

                    <!-- <el-form-item label="设计图片" prop="designUrl">
                        <el-upload :action="uploadPath" :limit="1" :show-file-list="false" :headers="headers"
                            :on-success="uploadCdUrl" list-type="picture" class="avatar-uploader"
                            accept=".jpg,.jpeg,.png,.gif">
                            <img v-if="goods.designUrl" :src="goods.designUrl" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item> -->

                    <el-form-item label="宣传画廊">
                        <el-upload ref="uploadRef" v-model:file-list="fileList" :action="uploadPath" :limit="5"
                            :headers="headers" :on-exceed="uploadOverrun" :on-success="handleGalleryUrl"
                            :on-remove="handleRemove" multiple accept=".jpg,.jpeg,.png,.gif" list-type="picture-card">
                            <el-icon class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>

                    <el-form-item label="商品单位">
                        <el-input v-model="goods.unit" placeholder="件 / 个 / 盒" />
                    </el-form-item>

                    <el-form-item label="关键字">
                        <el-tag v-for="tag in keywords" :key="tag" closable type="primary" @close="handleClose(tag)">
                            {{ tag }}
                        </el-tag>
                        <el-input v-if="newKeywordVisible" ref="newKeywordInput" v-model="newKeyword"
                            class="input-new-keyword" @keyup.enter.native="handleInputConfirm"
                            @blur="handleInputConfirm" />
                        <el-button v-else class="button-new-keyword" type="primary" @click="showInput">+ 增加</el-button>
                    </el-form-item>

                    <!-- <el-form-item label="商品配件">
                        <el-select v-model="goodsParts" multiple collapse-tags collapse-tags-tooltip
                            style="width: 240px" @change="partsChange">
                            <el-option v-for="item in partsList" :key="item.id"
                                :label="item.partGoodsName ? item.partGoodsName : item.name"
                                :value="item.partGoodsId ? item.partGoodsId : item.id" />
                        </el-select>
                    </el-form-item> -->

                    <el-form-item label="所属分类">
                        <el-select v-model="goods.categoryId" placeholder="请选择" @change="handleCategoryChange">
                            <el-option v-for="item in categoryList" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="所属品牌商">
                        <el-select v-model="goods.brandId" clearable>
                            <el-option v-for="item in brandList" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="商品简介">
                        <el-input v-model="goods.brief" />
                    </el-form-item>

                    <el-form-item label="商品详细介绍">
                        <richTextEditor v-if="openEditor" :valueHtml='goods?.detail' @htmlChange="htmlChange" />
                    </el-form-item>
                </el-form>
            </el-card>

            <el-card class="box-card">
                <h3>商品规格</h3>
                <el-row :gutter="20" type="flex" align="middle" style="padding: 20px 0">
                    <el-col :span="10">
                        <el-button type="primary" @click="handleSpecificationShow">添加</el-button>
                    </el-col>
                </el-row>

                <el-table :data="specifications">
                    <el-table-column prop="specification" label="规格名" />
                    <el-table-column prop="value" label="规格值" align="center">
                        <template #default="scope">
                            <el-tag type="primary">
                                {{ scope.row.value }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="customSpec" label="自定义规格" align="center">
                        <template #default="scope">
                            <el-tag v-if="scope.row.customSpec" type="primary">
                                {{ scope.row.customSpec }}
                            </el-tag>
                            <el-tag v-else type="info">
                                {{ scope.row.customSpec }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column v-if="multipleSpec" align="center" label="操作" width="250"
                        class-name="small-padding fixed-width">
                        <template #default="scope">
                            <el-button type="primary" size="small"
                                @click="handleSpecificationEdit(scope.row, scope.$index)">
                                编辑
                            </el-button>
                            <el-button type="danger" size="small" @click="handleSpecificationDelete(scope.row)">删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <el-dialog v-model="specVisiable" :title="titleSpec" title="设置规格"
                    :before-close="handleSpecificationClose">
                    <el-form ref="specRef" :rules="rules" :model="specForm" status-icon label-position="left"
                        label-width="100px" style="width: 400px; margin-left: 50px">
                        <el-form-item label="规格名" prop="specification">
                            <el-select v-model="specForm.specification" :disabled="disabledSpec" placeholder="请选择规格名"
                                @change="dictChange">
                                <el-option v-for="item in dictList" :key="item.id" :label="item.dictName"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="规格值" prop="value">
                            <el-select v-model="specForm.value" multiple collapse-tags collapse-tags-tooltip
                                placeholder="请选择规格值" :disabled="disabledSpec" style="width: 240px"
                                @change="dictItemChange">
                                <el-option v-for="item in dictItemList" :key="item.id" :label="item.itemText"
                                    :value="item.itemText" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="自定义规格">
                            <el-switch v-model="specForm.customSpec" @change="dictSwitchChange" />
                        </el-form-item>
                    </el-form>
                    <template #footer class="dialog-footer">
                        <el-button @click="handleSpecificationClose">取消</el-button>
                        <el-button type="primary" @click="handleSpecificationAdd">确定</el-button>
                    </template>
                </el-dialog>
            </el-card>

            <select-spec ref="selectSpecRef" :specData="specifications" :products="products"
                @productsData="productsData" @handle-sort="handleSort" />

            <template #footer>
                <el-button @click="handleCancel">取消</el-button>
                <el-button type="primary" @click="handleEdit">更新商品</el-button>
            </template>
        </el-drawer>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from "vue";
import { detailGoods, editGoods, listCatAndBrand } from "@/services/api/commodityManage/list";
import { uploadPath } from "@/services/api/storage";
import { ElMessageBox, ElMessage, ElNotification } from "element-plus";
import { listGoods } from "@/services/api/commodityManage/list";
import { getDictList, getDictItemList } from '@/services/api/market/auxiliary'
import selectSpec from './components/selectSpec.vue'
import richTextEditor from '@/components/richTextEditor.vue'

let editDrawer = ref(false)
let newKeywordVisible = ref(false);
let newKeyword = ref("");
let keywords = ref([] as any);
let galleryFileList = ref([] as any);
let categoryIds = ref([] as any);
let categoryList = ref([] as any);
let brandList = ref([] as any);
let fileList = ref([] as any)
let uploadRef = ref()
let openEditor = ref(true) // 富文本在每次dialog关闭后都要销毁，所以可以用v-if销毁dom
let goods = ref({
    goodsSn: "",
    name: "",
    counterPrice: 0,
    gallery: [] as any,
    isHot: false,
    isNew: true,
    isOnSale: true,
    picUrl: "",
    // designUrl: '',
    unit: "",
    brandId: "",
    brief: "",
    detail: '<p></p>',
    categoryId: undefined,
    keywords: undefined
} as any);
let goodsParts = ref([] as any)
let specVisiable = ref(false);
let specForm = ref({ specification: "", value: "", picUrl: "", customSpec: false } as any);
let titleSpec = ref('添加规格')
let disabledSpec = ref(false)
let multipleSpec = ref(true);
let specifications = ref([] as any);
let specQueryId = ref(); // 查询id

let products = ref([] as any);
let partsCopy = [] as any; // 配件 copy
let selectSpecRef = ref();
let goodsRef = ref();
let rules = ref({
    goodsSn: [{ required: true, message: "商品编号不能为空", trigger: "blur" }],
    name: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
    picUrl: [{ required: true, message: "商品图片不能为空", trigger: ["blur", 'change'] }],
    // designUrl: [{ required: true, message: "设计图片不能为空", trigger: ["blur", 'change'] }],
});

let headers = computed(() => {
    return { Authorization: sessionStorage.getItem("token") };
});
let emits = defineEmits(['initShelves'])
let partsList = ref()
let initList = () => {
    listGoods({
        page: 1,
        limit: 10,
        sort: "add_time",
        order: "desc",
    }).then((res: any) => {
        if (res.code === 200) {
            partsList.value = res.data.list;
        }
    })
}
initList()

let init = (id: number) => {
    // 记录id
    if (!specQueryId.value) specQueryId.value = id
    detailGoods(id).then((res: any) => {
        if (res.code === 200) {
            // 转换宣传画廊
            if (!res.data.goods.gallery) res.data.goods.gallery = []
            res.data.goods.gallery.map((item: any) => {
                fileList.value.push({
                    url: item,
                    name: item.split('/')[item.split('/').length - 1]
                })
            })
            goods.value = res.data.goods;
            for (let s in res.data.parts) {
                goodsParts.value.push(res.data.parts[s].partGoodsId)
            }
            // 稍微调整一下前后端不一致
            if (goods.value?.brandId === 0) {
                goods.value!.brandId = '';
            }
            if (goods.value?.categoryId === 0) {
                goods.value!.categoryId = '';
            }
            if (goods.value?.keywords === "") {
                goods.value!.keywords = null;
            }
            specifications.value = res.data.specifications;
            selectSpecRef.value.setSpecifications(res.data.products)
            products.value = res.data.products
            categoryIds.value = res.data.categoryIds;
            partsCopy = res.data.parts
            galleryFileList.value = [];
            for (var i = 0; i < goods.value?.gallery.length; i++) {
                galleryFileList.value.push({
                    url: goods.value?.gallery[i],
                });
            }
            const keyword: any = res.data.goods.keywords;
            if (keyword !== null) {
                keywords.value = keyword.split(",");
            }
        }
        // console.log( .value, 'data');
    });

    listCatAndBrand().then((res: any) => {
        if (res.code === 200) {
            categoryList.value = res.data.categoryList;
            brandList.value = res.data.brandList;
        }
    });
}

let partsData = ref([] as any)
// 商品配件修改的值
let partsChange = (value: any) => {
    partsData.value = []
    // 计算出删除的配件
    let delParts = [] as any
    partsCopy.map((item: any, i: number) => {
        let index = value.indexOf(item.partGoodsId)
        if (index === -1) {
            item.deleted = true
            delParts.push(item)
        } else {
            partsData.value.splice(i, 1, item)
        }
    })
    // 计算新增的配件
    let addParts = [] as any
    let copy = [] as any
    partsCopy.map((item: any) => {
        copy.push(item.partGoodsId)
    });
    value.map((item: any) => {
        if (copy.indexOf(item) === -1) {
            addParts.push(item)
        }
    })

    partsList.value.map((item: any) => {
        addParts.map((res: any) => {
            if (res === item.id) {
                partsData.value.push({
                    partGoodsId: item.id,
                    partGoodsName: item.name
                })
            }
        })
    })

    partsData.value = [...delParts, ...partsData.value]
}

let htmlChange = (value: any) => nextTick(() => goods.value.detail = value)

let deleteData = [] as any //记录删除数据
let deleteParamsData = [] as any //记录规格属性子数据table删除数据
let deleteMainData = [] as any //记录规格属性子数据table删除数据
let deletePartsData = [] as any //记录规格属性子数据table删除数据
// deleteIndexData 记录被删除的数据， deleteIndex 记录被删除数据的索引
// 继续推si山吧 。。。
let productsData = (data: any, deleteIndex?: any, deleteIndexData?: any,
    deleteParamsIndex?: any, deleteParamsIndexData?: any, deleteMainIndex?: any,
    deleteMainIndexData?: any, deletePartsIndex?: any, deletePartsIndexData?: any) => {

    products.value = data
    if (deleteIndexData) {
        if (deleteIndexData.deleted !== undefined || deleteIndexData.deleted) {
            deleteData.push({ deleteIndexData, deleteIndex })
        }
    }
    if (deleteParamsIndexData) {
        if (deleteParamsIndexData.deleted !== undefined || deleteParamsIndexData.deleted) {
            deleteParamsData.push({ deleteParamsIndexData, deleteParamsIndex, deleteIndex })
            console.log('删除参数', deleteParamsData);
        }
    }

    if (deleteMainIndexData) {
        if (deleteMainIndexData.deleted !== undefined || deleteMainIndexData.deleted) {
            deleteMainData.push({ deleteMainIndexData, deleteMainIndex, deleteIndex })
            console.log('删除主要配置', deleteMainData);
        }
    }

    if (deletePartsIndexData) {
        if (deletePartsIndexData.deleted !== undefined || deletePartsIndexData.deleted) {
            deletePartsData.push({ deletePartsIndexData, deletePartsIndex, deleteIndex })
            console.log('删除配件', deletePartsData);
        }
    }
}

// 排序规格
let handleSort = (type: string, data: any) => {
    let sameIndex: any;
    // 取第一个规格名的索引
    let sameFlag = specifications.value.some((item: any, index: number) => {
        sameIndex = index
        return item.specification === data.specification
    })
    let preSpecSort = specifications.value[sameIndex].sort // 记录当前的排序sort
    let preSpecName = specifications.value[sameIndex].specification // 当前的规格名
    // ascending 升序
    if (sameFlag) {
        if (type == 'ascending') {
            let frontPreSpecName = specifications.value[sameIndex - 1].specification // 前一个的规格名
            let frontPreSpecSort = specifications.value[sameIndex - 1].sort // 记录前一个的规格属性的排序sort
            specifications.value.forEach((item: any) => {
                if (item.specification == frontPreSpecName) {
                    item.sort = preSpecSort
                    if (item.updateTime) item.updateTime = null
                }
                if (item.specification == preSpecName) {
                    item.sort = frontPreSpecSort
                    if (item.updateTime) item.updateTime = null
                }
            });
            // console.log(specifications.value, data);
            bubbleSort(specifications.value)
            selectSpecRef.value.setSpecifications(products.value)
        } else {
            let sum = 0
            specifications.value.map((item: any) => { if (item.specification == preSpecName) sum++ })
            // 防止相加索引值大于数组长度而导致取不到值
            if (sameIndex + sum > specifications.value.length - 1) {
                var afterPreSpecName = specifications.value[specifications.value.length - 1].specification // 后一个的规格名
                var afterPreSpecSort = specifications.value[specifications.value.length - 1].sort // 记录前一个的规格属性的排序sort
            } else {
                var afterPreSpecName = specifications.value[sameIndex + sum].specification // 后一个的规格名
                var afterPreSpecSort = specifications.value[sameIndex + sum].sort // 记录前一个的规格属性的排序sort
            }
            // console.log(typeof frontPreSpecName, frontPreSpecSort);
            specifications.value.forEach((item: any) => {
                if (item.specification == afterPreSpecName) {
                    item.sort = preSpecSort
                    if (item.updateTime) item.updateTime = null
                }
                if (item.specification == preSpecName) {
                    item.sort = afterPreSpecSort
                    if (item.updateTime) item.updateTime = null
                }
            });
            // console.log(specifications.value, data);
            bubbleSort(specifications.value)
        }
    }
}

// 冒泡排序
let bubbleSort = ((arr: any) => {
    for (var i = 0; i < arr.length - 1; i++) {
        for (var j = 0; j < arr.length - i - 1; j++) {
            if (arr[j].sort > arr[j + 1].sort) {
                var temp = arr[j]
                arr[j] = arr[j + 1]
                arr[j + 1] = temp
            }
        }
    }
    selectSpecRef.value.sort()
})

let handleCategoryChange = (value: any) => {
    // goods.value.categoryId = value[value.length - 1];
}
let handleCancel = () => {
    goods.value = {
        goodsSn: "",
        name: "",
        counterPrice: 0,
        gallery: [] as any,
        isHot: false,
        isNew: true,
        isOnSale: true,
        picUrl: "",
        // designUrl: '',
        unit: "",
        brandId: "",
        brief: "",
        detail: '',
        categoryId: undefined,
        keywords: undefined,
    }
    uploadRef.value.clearFiles()
    specifications.value = []
    products.value = []
    goodsParts.value = []
    fileList.value = []
    deleteData = []
    keywords.value = []
    editDrawer.value = false
    openEditor.value = false
}

let handleEdit = () => {
    goodsRef.value?.validate((valid: boolean) => {
        if (valid) {
            // 如果要删除数据，再提交时需要把删除记录加上
            if (deleteData.length !== 0)
                deleteData.map((item: any) => { products.value.push(item.deleteIndexData) })
            // 要子数据参数table删除数据
            if (deleteParamsData.length !== 0) {
                deleteParamsData.map((item: any) => {
                    console.log(products.value[item.deleteIndex].attributeList);
                    // table中只有一条数据的时候
                    if (products.value[item.deleteIndex].attributeList.length === 0) {
                        products.value[item.deleteIndex].updateTime = null
                        products.value[item.deleteIndex].attributeList.push(item.deleteParamsIndexData)
                    } else
                        products.value[item.deleteIndex].attributeList.map((res: any, r: number) => {
                            if (r === item.deleteIndex) {
                                products.value[item.deleteIndex].updateTime = null
                                products.value[r].attributeList.push(item.deleteParamsIndexData)
                            }
                        })
                })
            }
            // 要子数据主要配置table删除数据
            if (deleteMainData.length !== 0) {
                deleteMainData.map((item: any) => {
                    if (products.value[item.deleteIndex].mainConfigurationsList.length === 0) {
                        products.value[item.deleteIndex].updateTime = null
                        products.value[item.deleteIndex].mainConfigurationsList.push(item.deleteMainIndexData)
                    } else
                        products.value[item.deleteIndex].mainConfigurationsList.map((res: any, r: number) => {
                            if (r === item.deleteIndex) {
                                products.value[item.deleteIndex].updateTime = null
                                products.value[r].mainConfigurationsList.push(item.deleteMainIndexData)
                            }
                        })
                })
            }
            // 要子数据配件table删除数据
            if (deletePartsData.length !== 0) {
                deletePartsData.map((item: any) => {
                    if (products.value[item.deleteIndex].partList.length === 0) {
                        products.value[item.deleteIndex].updateTime = null
                        products.value[item.deleteIndex].partList.push(item.deletePartsIndexData)
                    } else
                        products.value[item.deleteIndex].partList.map((res: any, r: number) => {
                            if (r === item.deleteIndex) {
                                products.value[item.deleteIndex].updateTime = null
                                products.value[r].partList.push(item.deletePartsIndexData)
                            }
                        })
                })
            }
            // console.log(products.value, 'products.value');
            specifications.value = [...specificationsDeleteData.value, ...specifications.value]
            const finalGoods = {
                goods: goods.value,
                specifications: specifications.value,
                products: products.value,
                categoryIds: categoryIds.value,
                parts: partsData.value
            };
            editGoods(finalGoods).then((res: any) => {
                if (res.code === 200) {
                    ElNotification({
                        type: 'success',
                        title: "成功",
                        message: "编辑成功",
                    });
                    emits('initShelves')
                    handleCancel()
                } else if (res.code === 401) {
                    // 因为会有拦截所以的刷新数据
                    specificationsDeleteData.value = []
                    init(specQueryId.value)
                }
            }).catch((res: any) => {
                ElMessageBox.alert("业务错误：" + res.msg, "警告", {
                    confirmButtonText: "确定",
                    type: "error",
                });
            });
        } else return false
    })
}
let handleClose = (tag: any) => {
    keywords.value.splice(keywords.value.indexOf(tag), 1);
    goods.value.keywords = keywords.value.toString();
}
let showInput = () => {
    newKeywordVisible.value = true;
}
let handleInputConfirm = () => {
    const newKeywords: string = newKeyword.value;
    if (newKeywords) {
        keywords.value.push(newKeywords);
        goods.value.keywords = keywords.value.toString();
    }
    newKeywordVisible.value = false;
    newKeyword.value = "";
}

let uploadPicUrl = (res: any) => {
    goods.value.picUrl = res.data.url;
}

let uploadCdUrl = (res: any) => {
    // goods.value.designUrl = res.data.url;
}

let uploadOverrun = () => {
    ElMessage({
        type: "error",
        message: "上传文件个数超出限制!最多上传5张图片!",
    });
}
let handleGalleryUrl = (res: any, file: any, fileList: any) => {
    goods.value.gallery.push(res.data.url);
    fileList.value.push(fileList)
}
let handleRemove = (file: any, fileList: any) => {
    fileList.value = fileList
    for (let i = 0; i < goods.value.gallery.length; i++) {
        // 这里存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.res.data.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
        let url;
        if (file.res === undefined) {
            url = file.url;
        } else {
            url = file.res.data.url;
        }

        if (goods.value.gallery[i] === url) {
            goods.value.gallery.splice(i, 1);
        }
    }
}

let dictList = ref()
let handleSpecificationShow = () => {
    let dictQuery = {
        column: 'createTime',
        order: 'desc',
        pageNo: 1,
        pageSize: 999
    } // 字典查询参数
    getDictList(dictQuery).then((res: any) => {
        if (res.code === 200) {
            dictList.value = res.data.records
            specForm.value = { specification: "", value: "", picUrl: "", customSpec: false };
            disabledSpec.value = false
            titleSpec.value = '添加规格'
            specVisiable.value = true;
        }
    })
}
let dictItemList = ref()
let dictName = ref()
let dictValue = ref()
let dictSwitch = ref(false) // table swith
let dictTableIndex = ref() // 点击编辑table index
let dictTableIndexSwitch = ref(false) // 点击编辑table swith值
let dictChange = (id: any) => {
    getDictItemList({ dictId: id, pageNo: 1, pageSize: 999 }).then((res: any) => {
        if (res.code === 200) {
            dictItemList.value = res.data.records
            for (let s of dictList.value) {
                if (s.id === id) dictName.value = s.dictName
            }
        }
    })
}
let dictItemChange = (val: []) => {
    dictValue.value = val
}
let dictSwitchChange = (val: boolean) => {
    dictSwitch.value = val
}
let handleSpecificationClose = () => {
    specForm.value.value = specForm.value.value[0]
    specForm.value.customSpec = dictTableIndexSwitch.value
    specifications.value[dictTableIndex.value] = specForm.value
    dictName.value = null
    dictValue.value = null
    specVisiable.value = false;
}
let handleSpecificationAdd = () => {
    if (titleSpec.value === '添加规格') {
        if (!dictName.value) return ElMessage({
            type: 'warning',
            message: '请选择规格名'
        })
        if (dictValue.value) {
            for (let s of dictValue.value) {
                for (let i of specifications.value) {
                    if (s == i.value) {
                        return ElMessage({
                            type: 'warning',
                            message: '已存在 ' + s + ' 规格值'
                        })
                    }
                }
                // 判断是否添加过改规格名
                let sameSpecIndex;
                let sameSort;
                let sameFlag = specifications.value.some((item: any, index: number) => {
                    sameSpecIndex = index
                    sameSort = item.sort
                    return item.specification === dictName.value
                })
                // console.log(sameFlag, 'sameFlag', sameSpecIndex);
                if (sameFlag) {
                    // dictSwitch.value 变成true后需要把相同的规格名的customSpec值也变成true
                    if (dictSwitch.value) {
                        specifications.value.forEach((item: any) => {
                            if (item.specification === dictName.value) {
                                item.customSpec = dictSwitch.value
                                item.updateTime = null
                            }
                        })
                    }
                    specifications.value.splice(sameSpecIndex, 0, {
                        specification: dictName.value,
                        value: s,
                        customSpec: dictSwitch.value,
                        sort: sameSort
                    })
                } else {
                    let sort;
                    if (specifications.value.length === 0) sort = 0
                    else sort = specifications.value[specifications.value.length - 1].sort + 1
                    specifications.value.push({
                        specification: dictName.value,
                        value: s,
                        customSpec: dictSwitch.value,
                        sort
                    })
                }
                // console.log(specifications.value, 'specifications.value');
            }
            dictValue.value = null
            dictName.value = null
            specForm.value = { specification: "", value: "", picUrl: "", customSpec: false }
            specVisiable.value = false;
            dictSwitch.value = false
        } else {
            ElMessage({
                type: 'warning',
                message: '请选择规格值'
            })
        }
    } else {
        specForm.value.value = specForm.value.value[0]
        specifications.value[dictTableIndex.value] = specForm.value
        specifications.value?.forEach((item: any) => {
            if (specifications.value[dictTableIndex.value].specification === item.specification) {
                item.customSpec = specifications.value[dictTableIndex.value].customSpec
                item.updateTime = null
            }
        })
        specVisiable.value = false;
    }
}

// 编辑商品规格
let handleSpecificationEdit = (row: any, index: number) => {
    titleSpec.value = '设置规格'
    specVisiable.value = true
    disabledSpec.value = true
    let str = row.value
    dictTableIndexSwitch.value = row.customSpec
    row.value = []
    row.value.push(str)
    specForm.value = row
    dictTableIndex.value = index
}

let specificationsDeleteData = ref([] as any)

let handleSpecificationDelete = (row: any) => {
    const index = specifications.value.indexOf(row);
    let delRow = specifications.value[index]
    if (typeof delRow.deleted !== 'undefined') {
        delRow.deleted = true
        specificationsDeleteData.value.push(specifications.value[index])
    }
    specifications.value.splice(index, 1);
}

defineExpose({
    editDrawer,
    openEditor,
    init
})
</script>

<style>
.el-card {
    margin-bottom: 10px;
}

.el-tag+.el-tag {
    margin-left: 10px;
}

.input-new-keyword {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
}

.avatar-uploader .el-upload {
    width: 145px;
    height: 145px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
}

.avatar {
    width: 145px;
    height: 145px;
    display: block;
}

.op-container {
    display: flex;
    justify-content: center;
}
</style>