<!-- 属性列表 -->
<template>
    <div class="table-box">
        <div style="padding-bottom: 16px">
            <el-button type="primary" @click="handleAdd"> 添加 </el-button>
        </div>
        <ProTable
            ref="proTableRef"
            :formData="dataStore.formData"
            :columns="dataStore.columns"
            :request-api="getProductAttrListApi"
            :init-param="dataStore.initParam"
        >
            <template #operation="scope">
                <el-button size="small" type="primary" @click="handleBtnClick(scope.row)" v-if="scope.row.id !== 1"
                    >编辑</el-button
                >
            </template>
        </ProTable>
        <!-- :show-close="false" -->
        <el-drawer
            v-model="dataStore.visible"
            :show-close="true"
            :size="600"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            :before-close="handleBeforeClone"
            destroy-on-close
        >
            <template #header="{ titleId, titleClass }">
                <h4 :id="titleId" :class="titleClass">{{ dataStore.title }}</h4>
            </template>
            <div>
                <rulesForm
                    :ruleForm="dataStore.editRuleForm"
                    :formData="dataStore.editFormData"
                    :rules="dataStore.rules"
                    ref="formRef"
                />
            </div>
            <template #footer>
                <div style="flex: auto">
                    <el-button @click="handleResetClick">重置</el-button>
                    <el-button type="primary" @click="handleConfirmClick">确认</el-button>
                </div>
            </template>
        </el-drawer>
    </div>
</template>

<script setup lang="ts" name="productAttributeListIndex">
import ProTable from "@/components/ProTable/index.vue";
import rulesForm from "@/components/rulesForm/index.vue";
import qs from "qs";
//接口
import {
    getProductAttrListApi,
    getProductAttrDetailsApi,
    getProductAttrUpApi,
    getProductAttrAddApi
} from "@/api/modules/productAttributeList";
//深拷贝方法
import { cloneDeep } from "lodash-es";
//表格和搜索條件
import { RULE_FORM, COLUMNS, RULES, SEARCH_DATA, EDIT_FORM_DATA, EDIT_RULE_FORM, ADD_FORM_DATA } from "./constant/index";
import { useMsg } from "@/hooks/useMsg";
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTableRef = ref<any>(null);
// 数据源
const dataStore = reactive<any>({
    title: "编辑产品属性",
    rules: cloneDeep(RULES), //抽屉表单验证
    row: {},
    editRuleForm: cloneDeep(EDIT_RULE_FORM),
    editFormData: cloneDeep(EDIT_FORM_DATA), //抽屉表单配置项
    visible: false, //抽屉控制
    columns: COLUMNS, //列表配置项
    initParam: cloneDeep(RULE_FORM), // 初始化搜索条件|重置搜索条件
    ruleForm: cloneDeep(RULE_FORM), // 搜索參數
    formData: SEARCH_DATA //搜索配置项
});
const formRef: any = ref(null);
//设置表单
const handleSetRuleForm = () => {
    dataStore.editRuleForm.attributeKey = dataStore.row.productName;
    dataStore.editRuleForm.attributeValue = dataStore.row.model;
};

//编辑
const handleBtnClick = (row: any) => {
    dataStore.visible = true;
    dataStore.title = "编辑产品属性";
    dataStore.editFormData = cloneDeep(EDIT_FORM_DATA);
    dataStore.row = cloneDeep(row);
    dataStore.editFormData[0].disabled = true;
    handleSetRuleForm();
    getProductAttrDetails(row.id);
};
//更新
const getProductAttrUp = async () => {
    let obj = {
        prop_name: dataStore.editRuleForm.addAttribute,
        prop_value: dataStore.editRuleForm.addAttribute
    };
    if (obj.prop_name) {
        dataStore.editRuleForm.props.push(obj);
    }

    let dataClone = cloneDeep(dataStore.editRuleForm.props);
    let props = JSON.stringify([...dataClone]);
    dataStore.editRuleForm.props = props;
    const result = await getProductAttrUpApi(dataStore.editRuleForm);
    if (result?.code === 0) {
        useMsg("success", result?.msg);
        proTableRef?.value?.getTableList();
        dataStore.visible = false;
        handleClear();
        // getProductAttrDetails(dataStore.editRuleForm.id);
    }
};
//添加
const getProductAttrAdd = async () => {
    let params = {
        attr_name: dataStore.editRuleForm.attr_name,
        props: JSON.stringify([
            {
                prop_name: dataStore.editRuleForm.propsStr,
                prop_value: dataStore.editRuleForm.propsStr
            }
        ])
    };
    const result = await getProductAttrAddApi(qs.stringify(params));
    if (result?.code === 0) {
        useMsg("success", result?.msg);
        proTableRef?.value?.getTableList();
        dataStore.visible = false;
        handleClear();
    }
};
//详情
const getProductAttrDetails = async (id: any) => {
    const result = await getProductAttrDetailsApi(id);
    if (result?.code === 0) {
        dataStore.editRuleForm = cloneDeep(result?.data);

        if (dataStore.editRuleForm.props.length) {
            let arr: any = [];

            dataStore.editRuleForm.props.forEach((item: any) => {
                arr.push(item.prop_name);
            });

            dataStore.editRuleForm.propsStr = arr.length ? arr.join(",") : [];
        }
    }
};
//清空表单数据
const handleClear = () => {
    for (let key in dataStore.editRuleForm) {
        dataStore.editRuleForm[key] = "";
    }
};
//添加
const handleAdd = () => {
    dataStore.visible = true;
    dataStore.title = "添加产品属性";
    dataStore.editFormData = cloneDeep(ADD_FORM_DATA);
    handleClear();
};
//重置验证
const resetFields = () => {
    if (!formRef.value!.ruleFormRef) return;
    formRef!.value!.ruleFormRef.resetFields();
};
//抽屉关闭前的钩子
const handleBeforeClone = () => {
    dataStore.visible = false;
    dataStore.editRuleForm.addAttribute = "";
    resetFields();
    handleClear();
};
//重置按钮
const handleResetClick = () => {
    if (dataStore.title === "添加产品属性") {
        dataStore.editRuleForm.addAttribute = "";
        handleSetRuleForm();
        resetFields();
    } else {
        getProductAttrDetails(dataStore.row.id);
    }
};
//确认
const handleConfirmClick = async () => {
    if (!formRef.value!.ruleFormRef) return;
    formRef!.value!.ruleFormRef!.validate((valid: any) => {
        if (valid) {
            dataStore.title === "添加产品属性" ? getProductAttrAdd() : getProductAttrUp();
        } else {
            console.log("error submit!");
            return false;
        }
    });
};
</script>

<style scoped></style>
