<template>
    <el-card>
        <h3>选择规格</h3>
        <div>{{ data }}</div>
        <div v-if="JSON.stringify(specData) != '[]'">
            <div v-for="(item, i) in specData" :key="i">
                <div style="margin-bottom: 20px;">
                    <el-tag class="ml-2" effect="dark" size="large">{{ item.specification }}</el-tag>
                </div>
                <el-radio-group v-model="item.specRadio" size="small" @change="radioChange($event, item)">
                    <el-radio-button v-for="(res, r) in item.values" :key="r" :label="res.value" />
                </el-radio-group>
                <el-divider />
            </div>
        </div>
        <el-button v-if="JSON.stringify(specData) != '[]'" type="primary"
            style="float: right; margin-right: 5%; margin-bottom: 20px;" @click="showAddSpec">添加</el-button>
    </el-card>

    <el-card>
        <h3>规格属性</h3>
        <el-table :data="specificationData">
            <el-table-column type="expand">
                <template #default="scope">
                    <el-row style="padding: 30px;">
                        <el-col :span="8" style="margin-right: 30px;">
                            <params-attr
                                :attributeData="{ attributeList: scope.row.attributeList, index: scope.$index }"
                                @paramsChange="paramsChange" style="width: 50%;" />
                        </el-col>
                        <el-col :span="8">
                            <main-config
                                :mainConfigurationsData="{ mainConfigurationsList: scope.row.mainConfigurationsList, index: scope.$index }"
                                @mainConfigChange="mainConfigChange" style="width: 50%;" />
                        </el-col>
                        <el-col :span="7" style="margin-left: 2%">
                            <parts :partsData="{ partList: scope.row.partList, index: scope.$index }"
                                @partsChange="partsChange" style="width: 50%;" />
                        </el-col>
                    </el-row>
                </template>
            </el-table-column>
            <el-table-column label="规格属性">
                <template #default="scope">
                    <el-tag v-for="(item, i) in scope.row.specifications.length" :key="i">{{
                            scope.row.specifications[i]
                    }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="155" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button type="primary" size="small" @click="handleAttributeEdit(scope.$index, scope.row)">编辑
                    </el-button>
                    <el-button type="danger" size="small" @click="handleAttributeDelete(scope.row)">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
    </el-card>

    <add-specifications ref="specificationsRef" @clickAdd="clickAdd" @clickEdit="clickEdit" />
</template>

<script setup lang='ts'>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import paramsAttr from './paramsAttr.vue'
import mainConfig from './mainConfig.vue'
import addSpecifications from './addSpecifications.vue'
import parts from './parts.vue'

let props = defineProps({
    specData: {
        type: Object,
        default: []
    },
    products: {
        type: Object,
        default: []
    }
})

let emits = defineEmits(['productsData'])

let data = computed(() => {
    if (JSON.stringify(props.specData) != '[]') {
        specData.value = []
        group(props.specData)
    } else {
        specData.value = []
        specificationData.value = []
    }
})

let specificationsRef = ref()
let specList = ref([] as any)
let specificationData = ref([] as any)

var specData = ref([] as any) //符合条件的数据

watch(specData.value, (newVlaue: any) => {
    if (JSON.stringify(newVlaue) === '[]') {
        specData.value = []
        specificationData.value = []
    }
})

let setSpecifications = (data: any) => {
    if (data) specificationData.value = data
}

// 参数值操作
let paramsChange = (type: string, data: any, index: any) => {
    if (type === 'add') {
        if (specificationData.value[index].id !== 'undefined') {
            specificationData.value[index].updateTime = null
        }
        specificationData.value[index].attributeList.unshift(data)
        emits('productsData', specificationData.value)
    }
    else {
        let i = specificationData.value[index].attributeList.indexOf(data);
        let deleteIndexParamsData: any = {} // 记录要被删除的数据
        if (typeof specificationData.value[index].attributeList[i].deleted !== 'undefined') { // deleted标为ture即为删除
            deleteIndexParamsData = specificationData.value[index].attributeList[i] // 记录要被删除的数据
            deleteIndexParamsData.deleted = true
            deleteIndexParamsData.updateTime = null
        }
        specificationData.value[index].attributeList.splice(i, 1)
        emits('productsData', specificationData.value, index, undefined, i, deleteIndexParamsData)
    }
}

// 参数值操作
let mainConfigChange = (type: string, data: any, index: any) => {
    if (type === 'add') {
        if (specificationData.value[index].id !== 'undefined') {
            specificationData.value[index].updateTime = null
        }
        specificationData.value[index].mainConfigurationsList.unshift(data)
        emits('productsData', specificationData.value)
    }
    else {
        const i = specificationData.value[index].mainConfigurationsList.indexOf(data);
        let deleteIndexMainData: any = {} // 记录要被删除的数据
        if (typeof specificationData.value[index].mainConfigurationsList[i].deleted !== 'undefined') { // deleted标为ture即为删除
            deleteIndexMainData = specificationData.value[index].mainConfigurationsList[i] // 记录要被删除的数据
            deleteIndexMainData.deleted = true
            deleteIndexMainData.updateTime = null
        }
        specificationData.value[index].mainConfigurationsList.splice(i, 1)
        emits('productsData', specificationData.value, index, undefined, undefined, undefined, i, deleteIndexMainData)
    }
}

// 配件操作
let partsChange = (type: string, data: any, index: any) => {
    if (type === 'add') {
        if (specificationData.value[index].id !== 'undefined') {
            specificationData.value[index].updateTime = null
        }
        specificationData.value[index].partList.unshift(data)
        emits('productsData', specificationData.value)
    }
    else {
        const i = specificationData.value[index].partList.indexOf(data);
        let deleteIndexPartsData: any = {} // 记录要被删除的数据
        if (typeof specificationData.value[index].partList[i].deleted !== 'undefined') { // deleted标为ture即为删除
            deleteIndexPartsData = specificationData.value[index].partList[i] // 记录要被删除的数据
            deleteIndexPartsData.deleted = true
            deleteIndexPartsData.updateTime = null
        }
        specificationData.value[index].partList.splice(i, 1)
        emits('productsData', specificationData.value, index, undefined, undefined, undefined, undefined, undefined, i, deleteIndexPartsData)
    }
}

// 每组只可以取一个
let radioChange = (e: any, item: any) => {
    item.values.forEach((res: any) => {
        if (specList.value.indexOf(res.value) != -1) {
            let s = specList.value.indexOf(res.value)
            if (specList.value[s] != e) {
                specList.value.splice(s, 1)
            }
        }
    })
    if (specList.value.indexOf(e) == -1) specList.value.push(e)
}

// 把配件数据整合，让数据选择规格时顺序从上到下
let handleSpecData = () => {
    let data = [] as any // specification, value
    // 深拷贝，避免影响原数组
    let newarr = JSON.parse((JSON.stringify(props.specData)))
    newarr.map((item: any) => {
        let flag = true
        // 如果已经存储了相同的specification，则下面就不在循环
        data.map((res: any) => {
            if (item.specification === res.specification) flag = false
        })
        newarr.map((item1: any) => {
            if (flag) {
                if (item.specification === item1.specification) {
                    let flag1 = true
                    // 如果已经存储了相同的specification，就只添加value
                    data.map((res: any) => {
                        if (item.specification === res.specification) flag1 = false
                    })
                    if (flag1) {
                        data.push({
                            specification: item.specification,
                            value: [item1.value]
                        })
                    } else {
                        data.forEach((res: any) => {
                            if (item1.specification === res.specification) {
                                res.value.push(item1.value)
                            }
                        })
                    }
                }
            }
        })
    })
    return data
}

// 判断规格属性的顺序是否正确，错误需要排序
let handleSequence = (data: any) => {
    let specListCopy = [...specList.value] // 浅拷贝
    // 双重循环判断对应索引值是否对应
    specList.value.map((arrVal: any, arr: number) => {
        data.map((item: any, i: number) => {
            if (arr === i) {
                let index = item.value.indexOf(arrVal)
                // 如果对应索引中没有对应关系，则取当前索引在拷贝数组找到对应值，直接赋值
                if (index === -1) {
                    data[arr].value.map((element: any) => {
                        let index1 = specListCopy.indexOf(element)
                        if (index1 !== -1) {
                            specList.value[arr] = specListCopy[index1]
                        }
                    })
                }
            }
        })
    })
}

// 打开添加规格属性框
let showAddSpec = () => {
    if (specList.value.length === 0) return ElMessage({ type: 'warning', message: '请先选择规格属性' })
    let resultSpecData = handleSpecData()
    if (specList.value.length !== resultSpecData.length) return ElMessage({ type: 'warning', message: '请选择所有规格属性' })
    handleSequence(resultSpecData)
    specificationsRef.value.formData = {
        bomCode: '',
        model: '',
        productName: ''
    }
    specificationsRef.value.title = '添加规格属性'
    specificationsRef.value.showVisiable = true
}

// 添加规格属性
let clickAdd = (formData: any) => {
    let data = {
        specifications: specList.value,
        price: 0.0,
        number: 0,
        url: "",
        attributeList: [],
        mainConfigurationsList: [],
        partList: []
    }
    data = { ...data, ...formData }
    specificationData.value.push(data)
    specList.value = []
    specData.value = poty.value
    emits('productsData', specificationData.value)
    // console.log(attributes.value, '规格属性数据');
}

let clickEdit = (formData: any) => {
    if (typeof formData.updateTime !== 'undefined') formData.updateTime = null
    specificationData.value[editIndex.value] = formData

}

let editIndex = ref() //编辑规格的下标
// 修改规格属性数据
let handleAttributeEdit = (index: number, row: any) => {
    specificationsRef.value.formData = row
    editIndex.value = index
    specificationsRef.value.title = '编辑规格属性'
    specificationsRef.value.showVisiable = true
}

// 删除规格属性数据
let handleAttributeDelete = (row: any) => {
    let index = specificationData.value.indexOf(row);
    let deleteIndexData: any = {} // 记录要被删除的数据
    // console.log(specificationData.value[index].deleted, 'specificationData.value[index].deleted');
    if (typeof specificationData.value[index].deleted !== 'undefined') { // deleted标为ture即为删除
        deleteIndexData = specificationData.value[index] // 记录要被删除的数据
        deleteIndexData.deleted = true
        deleteIndexData.updateTime = null
    }
    specificationData.value.splice(index, 1);
    emits('productsData', specificationData.value, index, deleteIndexData)
}

let poty = ref()

// 把相同数据分组
let group = (data: any) => {
    let arr = [] as any //记录相同索引
    let copyArr = [...data] // 拷贝
    let list = [] as any // 记录相同value
    let spec = copyArr[0].specification // 记录specification
    copyArr.forEach((item: any, i: number) => {
        if (item.specification == copyArr[0].specification) {
            arr.push(i)
            list.push({
                value: item.value,
                type: 'info'
            })
        }
    });
    let sum = -1
    arr.forEach((index: any) => {
        sum++
        if (arr.length > 1) {
            if (index < 0) {
                index = 0
                copyArr.splice(index, 1)
            } else {
                index -= sum
                copyArr.splice(index, 1)
            }
        } else {
            copyArr.splice(index, 1)
        }
    });
    specData.value.push({
        specification: spec,
        values: list,
        specRadio: ''
    })
    if (copyArr.length === 0) return poty.value = [...specData.value]
    else group(copyArr)
}

defineExpose({
    setSpecifications
})
</script>
 
<style lang="scss" scoped>
.el-divider--horizontal {
    margin: 12px 0 !important;
}
</style>