<template>
    <hc-dialog
        v-model="isShow"
        is-footer-center
        :title="modelTitle"
        @close="dialogClose"
        @save="saveFormAndElementHandle"
        widths="56rem"
        :loading="submitLoading"
    >
        <el-form
            ref="formRef"
            :model="formModel"
            :rules="formRules"
            label-position="top"
            label-width="auto"
            v-if="!tableId"
        >
            <el-row :gutter="60">
                <el-col :span="12">
                    <el-form-item label="表名" prop="tableName">
                        <el-input v-model="formModel.tableName" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="填报率">
                        <el-input v-model="formModel.fillRate" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="60">
                <el-col :span="12">
                    <el-form-item label="表类型：" prop="tableType">
                        <el-select
                            v-model="formModel.tableType"
                            placeholder="选择表类型"
                            filterable
                            block
                        >
                            <el-option
                                v-for="item in tableTypelist"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="所属方：" prop="tableOwner">
                        <el-select
                            v-model="formModel.tableOwner"
                            placeholder="选择所属方"
                            filterable
                            block
                        >
                            <el-option
                                v-for="item in ownerTypeList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <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
                >
                <el-button
                    size="small"
                    type="primary"
                    @click="uploadClick"
                    v-if="!tableId"
                    >快捷导入</el-button
                >
                <el-button
                    size="small"
                    type="warning"
                    v-if="!tableId"
                    @click="downLoadFile"
                    :loading="downloadLoading"
                    >下载导入模板</el-button
                >
            </template>
            <hc-search-input
                v-model="queryValue"
                @search="getEditEleList"
                class="w-100 mb-4"
                v-if="tableId"
            />
            <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 #dynamicDict="{ row }" v-if="tableId">
                    <el-select v-model="row.dynamicDict" placeholder="请选择">
                        <el-option
                            v-for="item in dynamicDictList"
                            :key="item.id"
                            :label="item.label"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                </template>
                <template #action="{ row, index }">
                    <el-link
                        type="danger"
                        @click="rowDelClick(row, index)"
                        v-if="row.id"
                        >删除</el-link
                    >
                    <div v-else>
                        <el-link
                            v-if="tableId"
                            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>
    <!-- 模板导入 -->
    <hc-dialog v-model="fileModal" title="模板导入" @save="saveFileImport">
        <hc-card-item>
            <template #header>
                <div class="text-sm text-red">
                    提示：必须按照系统要求的模版格式上传，否则系统识别无效
                </div>
            </template>

            <template #extra>
                <el-button
                    size="small"
                    type="primary"
                    @click="downLoadFile"
                    :loading="downloadLoading"
                    >下载导入模板</el-button
                >
                <el-button
                    size="small"
                    type="primary"
                    @click="importModalClick"
                    :loading="uploadsLoading"
                    >本地上传</el-button
                >
            </template>
            <hc-table :column="fileTableColumn" :datas="fileTableData">
                <template #elementAllowDeviation="{ 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.elementAllowDeviation" />
                    </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 { useAppStore } from "~src/store";
import { HcUploadFileApi, HcDelMsg } from "hc-vue3-ui";
import { formValidate, getArrValue, downloadBlob } from "js-fast-way";
const store = useAppStore();
const userInfo = ref(store.getUserInfo);
const props = defineProps({
    ownerTypeList: {
        type: Array,
        default: () => [],
    },
    tableTypelist: {
        type: Array,
        default: () => [],
    },
    wid: {
        type: [String, Number],
        default: "",
    },
    node: {
        type: Object,
        default: () => {},
    },
    title: {
        type: String,
        default: "",
    },
    tableId: {
        type: String,
        default: "",
    },
    initTableName: {
        type: String,
        default: "",
    },

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

const ownerTypeList = ref(props.ownerTypeList);
const tableTypelist = ref(props.tableTypelist);
const wbsId = ref(props.wid);
const node = ref(props.node);
const modelTitle = ref(props.title);
const tableId = ref(props.tableId);
const initTableName = ref(props.initTableName);
const initTableId = ref(props.initTableId);
const eKey = ref(props.eKey);
//监听数据
watch(
    () => [
        props.ownerTypeList,
        props.tableTypelist,
        props.wid,
        props.node,
        props.title,
        props.tableId,
        props.initTableName,
        props.initTableId,
        props.eKey,
    ],
    ([own, table, wbsid, nodeInfo, til, tid, tname, itid, ekey]) => {
        ownerTypeList.value = own;
        tableTypelist.value = table;
        wbsId.value = wbsid;
        node.value = nodeInfo;
        modelTitle.value = til;
        tableId.value = tid;
        initTableName.value = tname;
        initTableId.value = itid;
        eKey.value = ekey;
    },
    { deep: true }
);
watch(
    tableId,
    (val) => {
        console.log(val, "val11111111");

        if (val) {
            getEditEleList();
            tableColumn.value = [
                { key: "eName", name: "元素名称", width: 150 },
                { key: "eType", name: "数据类型", width: 120 },
                { key: "eLength", name: "长度" },
                { key: "eAllowDeviation", name: "允许偏差值", width: 180 },
                { key: "eInspectionMethod", name: "检查方法和频率" },
                { key: "dynamicDict", name: "动态字典" },
                { key: "action", name: "操作", width: 80, align: "center" },
            ];
        } else {
            editEleList.value = [];
            tableColumn.value = [
                { 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" },
            ];
        }
    },
    { deep: true }
);
//表单
const formRef = ref(null);
const formRules = {
    tableName: {
        required: true,
        trigger: "blur",
        message: "请输入表单名称",
    },
    tableType: {
        required: true,
        trigger: "blur",
        message: "请选择表单类型",
    },
    tableOwner: {
        required: true,
        trigger: "blur",
        message: "请选择所属方",
    },
    wid: {
        type: [String, Number],
        default: "",
    },
};

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 mainApi.getTableElements({
        id: tableId.value,
        search: "",
        type: 1,
    });
    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 dynamicDictList = ref([]); //动态字典列表
const getDynamicDictList = async () => {
    if (dynamicDictList.value.length > 1) {
        return;
    }
    dynamicDictList.value = await getDictionaryData("land_field_dict", 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: initTableName.value,
                eKey: row.ekey,
            });
            resolve(); //关闭弹窗
            if (!isRes) return;
            window?.$message?.success("操作成功");
        });
    }
};
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 = initTableId.value;
    row.initTableName = initTableName.value;
    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 () => {
    if (!tableId.value) {
        const formRes = await formValidate(formRef.value);
        if (!formRes) return false;
    }

    formModel.value.wbsId = wbsId.value;
    formModel.value.tenantId = userInfo.value.tenant_id;
    formModel.value.nodeType = -1;
    formModel.value.type = 2; //	'1'节点 '2'表
    formModel.value.parentId = node.value.id;
    formModel.value.nodeName = node.value.nodeName;
    for (let i = 0; i < editEleList.value.length; i++) {
        if (tableId.value) {
            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;
        formModel.value.elementList = editEleList;

        if (!tableId.value) {
            const { error, code } = await mainApi.saveFormAndElement({
                ...formModel.value,
            });
            submitLoading.value = false;
            if (!error && code === 200) {
                window?.$message?.success("操作成功");
                dialogClose();
            }
        } else {
            const { error, code } = await mainApi.updateBatchElements(
                editEleList.value,
                initTableName.value
            );
            submitLoading.value = false;
            if (!error && code === 200) {
                window?.$message?.success("操作成功");
                dialogClose();
            }
        }
    } else {
        window.$message.warning("请填写完整元素表信息");
    }
};
//关闭弹窗
const dialogClose = () => {
    isShow.value = false;
    emit("close");
};
const fileModal = ref(false);
const uploadClick = () => {
    fileModal.value = true;
    fileTableData.value = [];
};
const fileTableColumn = [
    { key: "elementName", name: "元素名称" },
    { key: "elementType", name: "数据类型" },
    { key: "elementLength", name: "长度" },
    { key: "elementAllowDeviation", name: "允许偏差值" },
    { key: "elementInspectionMethod", name: "检查方法和频率" },
];
const fileTableData = ref([]);
const downloadLoading = ref(false);
const downLoadFile = async () => {
    downloadLoading.value = true;
    const { error, disposition, res } = await mainApi.getExportTem();
    //处理数据
    downloadLoading.value = false;
    if (!error) {
        if (disposition) {
            downloadBlob(res, disposition);
        } else {
            window.$message?.error("数据异常");
        }
    }
};
const uploadsLoading = ref(false);
const importModalClick = () => {
    HcUploadFileApi({
        multiple: false,
        url: "/api/blade-manager/wbsFormElement/import-wbsElement",
        target: "/api/blade-manager/wbsFormElement/import-wbsElement",
        progress: () => {
            uploadsLoading.value = true;
        },
        success: (file, res) => {
            fileTableData.value = getArrValue(res.data);
        },
        error: (file) => {
            uploadsLoading.value = false;
            window.$message.error(`${file.name} 上传失败`);
        },
        finish: () => {
            uploadsLoading.value = false;
            window.$message.success("上传完成");
        },
    });
};
const saveFileImport = () => {
    fileModal.value = false;
    fileTableData.value.forEach((ele) => {
        editEleList.value.push({
            eName: ele.elementName,
            eAllowDeviation: ele.elementAllowDeviation,
            eName: ele.elementInspectionMethod,
            eLength: ele.elementLength,
            eType: ele.elementType,
        });
    });
};
</script>
