<template>
    <hc-dialog
        v-model="isShow"
        is-footer-center
        title=" 节点参数"
        @close="dialogClose"
        @save="saveElementHandle"
        widths="56rem"
        :loading="submitLoading"
    >
        <hc-card-item>
            <template #extra>
                <el-button size="small" type="primary" @click="addRowClick"
                    >新增</el-button
                >
                <el-button
                    size="small"
                    type="warning"
                    @click="refreshNode"
                    :loading="refreshLoad"
                    >刷新</el-button
                >
                <el-button
                    size="small"
                    type="success"
                    @click="setParamNameClick"
                    >设置参数名称</el-button
                >
            </template>

            <hc-table
                :column="tableColumn"
                :datas="tableData"
                :loading="tableLoading"
            >
                <template #name="{ row, index }">
                    <el-select
                        v-model="row.k"
                        placeholder="请选择"
                        filterable
                        block
                    >
                        <el-option
                            v-for="item in nameList"
                            :key="item.k"
                            :label="item.name"
                            :value="item.k"
                        />
                    </el-select>
                </template>
                <template #v="{ row, index }">
                    <hc-table-input v-model="row.v" />
                </template>
                <template #remark="{ row, index }">
                    <hc-table-input v-model="row.remark" />
                </template>
                <template #action="{ row, index }">
                    <el-link type="warning" @click="linkElement(row)"
                        >关联元素</el-link
                    >

                    <el-link type="danger" @click="delRowClick(index, row)"
                        >删除</el-link
                    >
                </template>
            </hc-table>
        </hc-card-item>
        <!-- 设置参数名称 -->
        <hc-dialog
            v-model="setNameShow"
            is-footer-center
            title=" 设置参数名称"
            @close="nameClosedialogClose"
            @save="saveNameHandle"
            widths="56rem"
            :loading="setNameLoading"
        >
            <hc-card-item>
                <template #extra>
                    <el-button
                        size="small"
                        type="primary"
                        @click="addNameRowClick"
                        >新增</el-button
                    >
                </template>

                <hc-table
                    :column="nameTableColumn"
                    :datas="nameTableData"
                    :loading="nameTableLoading"
                >
                    <template #name="{ row, index }">
                        <hc-table-input v-model="row.name" />
                    </template>
                    <template #k="{ row, index }">
                        <hc-table-input v-model="row.k" />
                    </template>
                    <template #remark="{ row, index }">
                        <hc-table-input v-model="row.remark" />
                    </template>
                    <template #action="{ row, index }">
                        <el-link type="danger" @click="delNameClick(row, index)"
                            >删除</el-link
                        >
                    </template>
                </hc-table>
            </hc-card-item>
        </hc-dialog>

        <!-- 关联元素 -->
        <hc-dialog
            v-model="linkParamShow"
            title=" 节点参数设置-关联元素"
            @close="linkParamdialogClose"
            widths="56rem"
            :footer="false"
        >
            <hc-card-item>
                <hc-table
                    :column="linkTableColumn"
                    :datas="linkTableData"
                    :loading="linkTableLoading"
                >
                    <template #action="{ row, index }">
                        <el-link
                            type="primary"
                            v-if="!row.mappingId"
                            @click="chooseClick(row, index)"
                            >选择元素</el-link
                        >
                        <el-link
                            type="danger"
                            v-else
                            @click="delLinkClick(row, index)"
                            :loading="delLinkLoading"
                            >删除关联</el-link
                        >
                    </template>
                </hc-table>
            </hc-card-item>
        </hc-dialog>
        <!-- 选择关联元素 -->
        <hc-dialog
            v-model="chooseLinkShow"
            title=" 选择关联元素"
            @close="linkShowClose"
            widths="56rem"
            @save="saveLink"
            :loading="saveLoading"
        >
            <hc-card-item>
                <hc-search-input
                    v-model="queryValue"
                    @search="searchClick"
                    @clear="searchClick"
                    class="mb-4"
                />
                <hc-table
                    :column="chooseLinkTableColumn"
                    :datas="chooseLinkTableData"
                    :loading="chooselinkTableLoading"
                >
                    <template #action="{ row, index }">
                        <el-checkbox
                            v-model="row.checked"
                            @change="(value) => linkEleCheck(value, index)"
                        ></el-checkbox>
                    </template>
                </hc-table>
            </hc-card-item>
        </hc-dialog>
    </hc-dialog>
</template>
<script setup>
import { ref, watch } from "vue";
import mainWbsApi from "~api/wbs/wbsforelement";
import mainApi from "~api/wbs/tree";
import { getArrValue } from "js-fast-way";
import { HcDelMsg } from "hc-vue3-ui";
const props = defineProps({
    nodeId: {
        type: String,
        default: "",
    },
    porjectId: {
        type: String,
        default: "",
    },
    scopeType: {
        type: [String, Number],
        default: "",
    },
    nodeInfo: {
        type: Object,
        default: () => {},
    },
});
//事件
const emit = defineEmits(["close"]);
//双向绑定
// eslint-disable-next-line no-undef
const isShow = defineModel("modelValue", {
    default: false,
});
//监听显示
watch(isShow, (val) => {
    if (val) {
        getTableData();
        getNameList();
    } else {
        emit("close");
    }
});
const nodeId = ref(props.nodeId);
const porjectId = ref(props.porjectId);
const scopeType = ref(props.scopeType);
const nodeInfo = ref(props.nodeInfo);
const delIds = ref([]);
//监听数据
watch(
    () => [props.nodeId, props.porjectId, props.scopeType, props.nodeInfo],
    ([tid, pid, stype, ninfo]) => {
        nodeId.value = tid;
        porjectId.value = pid;
        scopeType.value = stype;
        nodeInfo.value = ninfo;
    },
    { deep: true }
);
//关闭弹窗
const dialogClose = () => {
    isShow.value = false;
    emit("close");
};
const submitLoading = ref(false);
const saveElementHandle = async () => {
    let tag = true;
    tableData.value.forEach((val) => {
        if (!val.k | !val.v) {
            return (tag = false);
        }
        for (let i = 0; i < nameList.value.length; i++) {
            if (nameList.value[i].k == val.k) {
                val.name = nameList.value[i].name;
                return;
            }
        }
    });
    if (tag) {
        submitLoading.value = true;
        const { error, code, data } = await mainApi.saveOrUpdateBatch({
            scopeType: scopeType.value,
            porjectId: porjectId.value,
            nodeId: nodeId.value,
            wps: tableData.value,
            type: 1,
            delIds: delIds.value,
        });
        submitLoading.value = false;
        //判断状态
        if (!error && code === 200) {
            window.$message.success("设置参数节点成功");
            delIds.value = [];
            getTableData();
        }
    } else {
        window.$message.warning("请填写所有的参数名称和参数值KEY");
    }
};
const tableColumn = [
    { key: "name", name: "参数名称", align: "center" },
    { key: "v", name: "参数值KEY", align: "center" },
    { key: "remark", name: "描述", align: "center" },
    { key: "action", name: "操作", align: "center" },
];
const tableLoading = ref(false);
const tableData = ref([]);

const getTableData = async () => {
    let pid = nodeInfo.value.primaryKeyId
        ? nodeInfo.value.primaryKeyId
        : nodeInfo.value.pKeyId;
    tableLoading.value = true;
    const { data } = await mainApi.parameters({
        wbsId: porjectId.value ? pid : nodeId.value,
    });

    tableData.value = getArrValue(data);
    tableLoading.value = false;
};
const nameList = ref([]);
const getNameList = async () => {
    const { data } = await mainApi.keymap({});

    nameList.value = getArrValue(data);
};
const addRowClick = () => {
    tableData.value.unshift({
        k: "",
        v: "",
        remark: "",
        nodeId: nodeId.value,
        type: 1,
    });
};
const delRowClick = (index, row) => {
    delIds.value.push(row.id);
    tableData.value.splice(index, 1);
};
//设置节点参数名称
const setNameShow = ref(false);
const nameTableData = ref([]);
const setParamNameClick = async () => {
    setNameShow.value = true;
    await getNameList();
    nameTableData.value = [...nameList.value];
};
const nameClosedialogClose = () => {};
const setNameLoading = ref(false);
const saveNameHandle = async () => {
    //设置参数名称中的保存按钮
    if (nameTableData.value.length) {
        let tag = true;
        nameTableData.value.forEach((val) => {
            if (!val.name || !val.k) {
                return (tag = false);
            }
        });
        if (tag) {
            setNameLoading.value = true;
            const { error, code, data } = await mainApi.saveOrUpdateBatch({
                scopeType: scopeType.value,
                nodeId: nodeId.value,
                porjectId: porjectId.value,
                wps: nameTableData.value,
                type: 0,
                delIds: delIds.value,
            });
            setNameLoading.value = false;
            //判断状态
            if (!error && code === 200) {
                window.$message.success("操作成功");
                setNameShow.value = false;
                delIds.value = [];
                getNameList();
                getTableData();
            }
        } else {
            window.$message.warning("请填写所有的参数名称和参数值KEY");
        }
    } else {
        window.$message.warning("请先添加参数");
    }
};
const nameTableColumn = [
    { key: "name", name: "参数名称", align: "center" },
    { key: "k", name: "参数值KEY", align: "center" },
    { key: "remark", name: "描述", align: "center" },
    { key: "action", name: "操作", align: "center" },
];

const nameTableLoading = ref(false);
const addNameRowClick = () => {
    nameTableData.value.unshift({
        name: "",
        remark: "",
        k: "",
        type: 0,
        nodeId: nodeId.value,
    });
};
const delNameClick = (row, index) => {
    delIds.value.push(row.id);
    nameTableData.value.splice(index, 1);
};

//关联元素
const linkTableColumn = [
    { key: "tableName", name: "元素表名", align: "center" },
    { key: "elementName", name: "关联元素字段", align: "center" },

    { key: "action", name: "操作", align: "center" },
];
const linkTableData = ref([]);
const linkTableLoading = ref(false);
const curParam = ref({});
const linkParamShow = ref(false);
const getLinkTableData = async () => {
    const { error, code, data } = await mainApi.getParamElements({
        nodeId: nodeId.value,
        porjectId: porjectId.value,
        paramId: curParam.value.id,
        scopeType: scopeType.value,
    });

    //判断状态
    if (!error && code === 200) {
        linkTableData.value = getArrValue(data);
    }
};
const linkElement = async (row) => {
    if (!row.id) {
        window.$message.warning("请先保存数据，再点击关联元素");
    } else {
        curParam.value = row;
        linkParamShow.value = true;
        getLinkTableData(row);
    }
};
const linkParamdialogClose = () => {
    linkParamShow.value = false;
};
//选择元素
const chooseLinkShow = ref(false);
const chooseLinkTableData = ref([]);
const chooselinkTableLoading = ref(false);
const getChooseData = async (id) => {
    let pid = nodeInfo.value.primaryKeyId
        ? nodeInfo.value.primaryKeyId
        : nodeInfo.value.pKeyId;
    chooselinkTableLoading.value = true;
    const { error, code, data } = await mainApi.selectFormElements({
        nodeId: porjectId.value ? pid : nodeId.value,
        id: id,
        type: porjectId.value ? 3 : 5,
    });
    chooselinkTableLoading.value = false;
    //判断状态
    if (!error && code === 200) {
        chooseLinkTableData.value = getArrValue(data);
    }
};

const chooseId = ref("");
const chooseClick = (row) => {
    chooseLinkShow.value = true;
    chooseId.value = row.id;
    getChooseData(row.id);
};

const linkShowClose = () => {};
const chooseLinkTableColumn = [
    { key: "eName", name: "元素名", align: "center" },
    { key: "action", name: "操作", align: "center" },
];
const queryValue = ref("");
const searchClick = () => {
    if (queryValue.value.length > 0) {
        chooseLinkTableData.value = chooseLinkTableData.value.filter((ele) => {
            return ele.eName.indexOf(queryValue.value) > -1;
        });
    } else {
        getChooseData(chooseId.value);
    }
};
const linkEleCheck = (value, index) => {
    if (value) {
        chooseLinkTableData.value.forEach((ele, i) => {
            if (i != index) {
                ele.checked = false;
            }
        });
    }
};
const saveLoading = ref(false);
const saveLink = async () => {
    let target = {};
    chooseLinkTableData.value.forEach((ele) => {
        if (ele.checked === true) {
            target = { elementId: ele.id, paramId: curParam.value.id };
        }
    });
    saveLoading.value = true;
    const { error, code, data, msg } = await mainApi.specifiedParamElements(
        target
    );
    saveLoading.value = false;
    //判断状态
    if (!error && code === 200) {
        window.$message.success(msg);
        chooseLinkShow.value = false;
        getLinkTableData();
    }
};
const delLinkLoading = ref(false);
const delLinkClick = (row) => {
    HcDelMsg(async (resolve) => {
        //发起请求
        delLinkLoading.value = true;
        const { isRes } = await mainApi.delParamElements(row);
        resolve(); //关闭弹窗
        if (!isRes) return;
        window.$message.success("删除成功");
        getLinkTableData();
    });
};
//刷新
const refreshLoad = ref(false);
const refreshNode = async () => {
    refreshLoad.value = true;
    const { error, code, data, msg } = await mainApi.refrehPram({
        type: porjectId.value ? 1 : 0,
        nodeId: nodeId.value,
        porjectId: porjectId.value,
    });
    refreshLoad.value = false;
    //判断状态
    if (!error && code === 200) {
        window.$message.success(msg);
    }
};
</script>
