<template>
    <hc-dialog
        v-model="isShow"
        is-footer-center
        title="元素编辑"
        @close="dialogClose"
        @save="saveFormAndElementHandle"
        widths="56rem"
        :loading="submitLoading"
        isTable
    >
        <hc-card-item>
            <template #header>
                <el-tooltip
                    :visible="editVisible"
                    effect="light"
                    placement="bottom-start"
                >
                    <template #content>
                        <div class="text-sm text-red">
                            1.元素名称不能为空<br />
                            2.数据类型不能为空<br />
                            3.元素长度不能为空<br />
                            4.编辑元素信息请谨慎操作<br />
                        </div>
                    </template>
                    <el-button
                        type="danger"
                        @mouseenter="editVisible = true"
                        @mouseleave="editVisible = false"
                    >
                        <HcIcon name="question" />
                        <span>编辑说明</span>
                    </el-button>
                </el-tooltip>
            </template>

            <template #extra>
                <el-button size="small" type="success" @click="addRowClick"
                    >新增</el-button
                >
            </template>
            <hc-search-input
                v-model="queryValue"
                @search="getEditEleList"
                class="w-100 mb-4"
            />
            <hc-table :column="tableColumn" :datas="editEleList">
                <template #eName="{ row }">
                    <hc-table-input v-model="row.eName" />
                </template>
                <template #eType="{ row }">
                    <el-select
                        v-model="row.eType"
                        @change="setDefaultLength(row)"
                        placeholder="请选择"
                    >
                        <el-option
                            v-for="item in dataTypeList"
                            :key="item.id"
                            :label="item.label"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                </template>
                <template #eLength="{ row }">
                    <hc-table-input v-model="row.eLength" />
                </template>
                <template #eAllowDeviation="{ row }">
                    <div class="flex">
                        <el-select
                            v-model="row.allow"
                            :popper-append-to-body="false"
                            placeholder="请选择"
                        >
                            <el-option :key="1" label="-" value="-"></el-option>
                            <el-option :key="2" label=">" value=">"></el-option>
                            <el-option :key="3" label="<" value="<"></el-option>
                            <el-option :key="4" label="≥" value="≥"></el-option>
                            <el-option :key="5" label="≤" value="≤"></el-option>
                            <el-option :key="6" label="±" value="±"></el-option>
                            <el-option
                                :key="7"
                                label="【】"
                                value="【】"
                            ></el-option>
                        </el-select>
                        <hc-table-input v-model="row.deviation" />
                    </div>
                </template>
                <template #eInspectionMethod="{ row }">
                    <hc-table-input v-model="row.eInspectionMethod" />
                </template>

                <template #action="{ row, index }">
                    <el-link
                        type="danger"
                        @click="rowDelClick(row, index)"
                        v-if="row.id"
                        >删除</el-link
                    >
                    <div v-else>
                        <el-link
                            type="primary"
                            @click="addSaveClick(row, index)"
                            :loading="addSaveLoading"
                            >保存</el-link
                        >
                        <el-link
                            type="danger"
                            @click="rowDelClick(row, index)"
                            :loading="rowDelLoading"
                            >删除</el-link
                        >
                    </div>
                </template>
            </hc-table>
        </hc-card-item>
    </hc-dialog>
</template>
<script setup>
import { ref, watch } from "vue";
import { getDictionaryData } from "~src/utils/tools";
import mainApi from "~api/wbs/wbsforelement";
import treeApi from "~api/wbs/tree";

import { getArrValue } from "js-fast-way";

const props = defineProps({
    info: {
        type: Object,
        default: () => {},
    },
});
//事件
const emit = defineEmits(["close"]);
//双向绑定
// eslint-disable-next-line no-undef
const isShow = defineModel("modelValue", {
    default: false,
});
//监听显示
watch(isShow, (val) => {
    if (val) {
        getDataTypelist();
        getEditEleList();
    } else {
        emit("close");
    }
});

const info = ref(props.info);

//监听数据
watch(
    () => [props.info],
    ([infoData]) => {
        info.value = infoData;
    },
    { deep: true }
);

const formModel = ref({});
const editVisible = ref(false);
const tableColumn = ref([
    { key: "eName", name: "元素名称", width: 150 },
    { key: "eType", name: "数据类型", width: 120 },
    { key: "eLength", name: "长度" },
    { key: "eAllowDeviation", name: "允许偏差值", width: 180 },
    { key: "eInspectionMethod", name: "检查方法和频率" },
    { key: "action", name: "操作", width: 80, align: "center" },
]);
const editEleList = ref([]);
const queryValue = ref("");

const getEditEleList = async () => {
    const { data } = await treeApi.selectPrivateFormElements({
        id: info.value?.id,
        eName: queryValue.value || "",
    });
    editEleList.value = getArrValue(data);
    const eleReg = /(-|>|<|≥|≤|±|【】)?([^≥≤±【】]*)/;
    editEleList.value.forEach((element) => {
        eleReg.exec(element.eAllowDeviation);
        element.allow = RegExp.$1 ? RegExp.$1 : "";
        element.deviation = RegExp.$2 ? RegExp.$2 : "";
    });
};
const dataTypeList = ref([]);
const getDataTypelist = async () => {
    if (dataTypeList.value.length > 1) {
        return;
    }
    dataTypeList.value = await getDictionaryData("data_type", false);
};

const setDefaultLength = (row) => {
    const dataTypeDefaultMap = {
        1: 250, //字符串
        2: 50, //整数
        3: 50, //小数
        4: 50, //日期
        5: 50, //数值
        6: 50, //签名
        7: 100, //文件
    };
    row.eLength = dataTypeDefaultMap[row.eType];
};
const rowDelLoading = ref(false);
const rowDelClick = async (row, index) => {
    if (!row.id) {
        editEleList.value.splice(index, 1);
    } else {
        HcDelMsg(async (resolve) => {
            //发起请求
            rowDelLoading.value = true;
            const { isRes } = await mainApi.removeElement({
                ids: row.id,
                initTableName: info.value?.initTableName,
                eKey: row.ekey,
            });
            resolve(); //关闭弹窗
            if (!isRes) return;
            window?.$message?.success("操作成功");
            getEditEleList();
        });
    }
};
const addRowClick = () => {
    editEleList.value.push({});
};

const addSaveLoading = ref(false);
const addSaveClick = async (row) => {
    if (!row.eName) {
        window.$message.warning("请填写元素名称");
        return;
    }
    if (!row.eType) {
        window.$message.warning("请选择数据类型");
        return;
    }

    row.eAllowDeviation =
        (row.allow ? row.allow : "") + (row.deviation ? row.deviation : "");
    row.fId = info.value.initTableId;
    row.initTableName = info.value.initTableName;
    if (!row.eLength) {
        window.$message.warning("请填写长度");
        return;
    }
    addSaveLoading.value = true;
    const { error, code, data } = await mainApi.saveElement(row);
    addSaveLoading.value = false;
    if (!error && code === 200) {
        window?.$message?.success("操作成功");
        row.id = data.id;
        row.ekey = data.ekey;
    }
};
const submitLoading = ref(false);

const saveFormAndElementHandle = async () => {
    for (let i = 0; i < editEleList.value.length; i++) {
        if (!editEleList.value[i].id) {
            window.$message.warning("请先将新增的元素点击保存");
            return;
        }

        if (!editEleList.value[i].eName) {
            window.$message.warning("请填写第" + (i + 1) + "条元素名称");
            return;
        }
        if (!editEleList.value[i].eType) {
            window.$message.warning("请选择第" + (i + 1) + "条数据类型");
            return;
        }
        if (!editEleList.value[i].eLength) {
            window.$message.warning("请填写第" + (i + 1) + "条数据长度");
            return;
        }
    }
    if (editEleList.value.length > 0) {
        editEleList.value.forEach((element) => {
            element.eAllowDeviation =
                (element.allow ? element.allow : "") +
                (element.deviation ? element.deviation : "");
        });
        submitLoading.value = true;
        const { error, code } = await mainApi.updateBatchElements(
            editEleList.value,
            info.value.initTableName
        );
        submitLoading.value = false;
        if (!error && code === 200) {
            window?.$message?.success("操作成功");
            dialogClose();
        }
    } else {
        window.$message.warning("请填写完整元素表信息");
    }
};
//关闭弹窗
const dialogClose = () => {
    isShow.value = false;
    emit("close");
};
</script>
