<template>
    <hc-card class="hc-debit-pay-material-adjustment">
        <template #header>
            <div class="w-40">
                <el-input
                    v-model="searchForm.materialNumber"
                    placeholder="材料编码"
                />
            </div>
            <div class="ml-3 w-60">
                <hc-search-input
                    v-model="searchForm.materialName"
                    placeholder="请输入材料名称"
                    @search="getTableData"
                />
            </div>
        </template>
        <hc-body :split="rowBindingShow" padding="0">
            <hc-card-item>
                <hc-table
                    :column="tableColumn"
                    :datas="tableData"
                    :is-index="false"
                    :loading="tableLoading"
                >
                    <template #action="{ row }">
                        <template v-if="row.rowBindingData">
                            <el-link
                                type="success"
                                :disabled="treeLoadNode.length <= 0"
                                @click="confirmBinding(row)"
                                >确认绑定</el-link
                            >
                            <el-link type="danger" @click="cancelBinding(row)"
                                >取消绑定</el-link
                            >
                        </template>
                        <template v-else>
                            <el-link type="warning" @click="rowBinding(row)"
                                >绑定清单</el-link
                            >
                            <el-link type="primary" @click="rowEditClick(row)"
                                >编辑</el-link
                            >
                        </template>
                    </template>
                </hc-table>
            </hc-card-item>
            <template #right>
                <hc-card-item scrollbar>
                    <el-tree
                        ref="treeRef"
                        :data="treeLoadNode"
                        node-key="id"
                        :props="treeProps"
                        :default-checked-keys="treeNodeCheckList"
                        show-checkbox
                        check-strictly
                    >
                        <template #default="{ data }">
                            <div class="data-custom-tree-node">
                                <div class="level">{{ data.formName }}</div>
                                <div
                                    v-if="data.isFormNode"
                                    class="submit-input"
                                >
                                    <el-input
                                        v-model="data.adjustFactor"
                                        size="small"
                                        placeholder="请输入调差参数"
                                        :disabled="data.isQuote === 1"
                                    />
                                </div>
                            </div>
                        </template>
                    </el-tree>
                </hc-card-item>
            </template>
        </hc-body>
        <!-- 调差系数编辑 -->
        <hc-new-dialog
            v-model="isFormModal"
            title="调差系数编辑"
            is-footer-center
            is-table
            widths="50rem"
            @close="modalClose"
        >
            <hc-table
                :column="tableColumn1"
                :datas="tableData2"
                :is-index="false"
            >
                <!-- <template #adjustFactor="{ row }">
                    <hc-table-input
                        v-model="row.adjustFactor"
                        :disabled="row.isQuote === 1"
                    />
                </template> -->
                <template #adjustFactor="{ row }">
                    <hc-table-input v-model="row.adjustFactor" />
                </template>
                <template #action="{ row }">
                    <el-link
                        type="danger"
                        :disabled="row.isQuote === 1"
                        @click="dischargeBinding(row)"
                        >解除绑定关系</el-link
                    >
                </template>
            </hc-table>
            <template #footer>
                <el-button hc-btn @click="modalClose">取消</el-button>
                <el-button
                    :loading="saveLoaing"
                    hc-btn
                    type="primary"
                    @click="modalSave"
                    >提交</el-button
                >
            </template>
        </hc-new-dialog>
    </hc-card>
</template>

<script setup>
import { onActivated, onDeactivated, ref } from "vue";
import { useAppStore } from "~src/store";
import { HcDelMsg } from "hc-vue3-ui";
import { getArrValue } from "js-fast-way";
import mainApi from "~api/debit-pay/material/adjustment";

//初始化
const store = useAppStore();
const projectId = ref(store.getProjectId);
const contractId = ref(store.getContractId);

//渲染完成
onActivated(() => {
    getTableData();
});

//搜索表单
const searchForm = ref({ materialNumber: "", materialName: "" });

//表格
const tableColumn = [
    { key: "materialNumber", name: "材料编码" },
    { key: "materialName", name: "材料名称" },
    { key: "unit", name: "材料单位" },
    { key: "action", name: "操作", width: 140, align: "center" },
];
const tableData = ref([]);

//获取表格数据
const tableLoading = ref(false);
const getTableData = async () => {
    tableLoading.value = true;
    const { error, code, data } = await mainApi.getAllMaterial({
        ...searchForm.value,
        projectId: projectId.value,
        contractId: contractId.value,
    });
    tableLoading.value = false;
    if (!error && code === 200) {
        tableData.value = getArrValue(data);
    } else {
        tableData.value = [];
    }
};

//调差树
const treeRef = ref(null);
const treeProps = {
    label: "formName",
    children: "children",
    disabled: (data) => {
        return data.isQuote === 1;
    },
    class: (data) => {
        return `${data.isFormNode === 1 ? "is-form-node" : "no-form-check"}`;
    },
};
const treeLoadNode = ref([]);

//绑定清单
const rowBindingShow = ref(false);
const treeNodeCheckList = ref([]);
const rowBinding = async (row) => {
    if (rowBindingShow.value) {
        window.$message.error("请先操作完上一个清单");
        return;
    }
    rowBindingShow.value = true;
    row.rowBindingData = true;
    //获取树的数据
    const { data } = await mainApi.getAdjustFormTree({
        projectId: projectId.value,
        contractId: contractId.value,
        materialId: row.id,
    });
    treeLoadNode.value = getArrValue(data["vo2s"]);
    treeNodeCheckList.value = getArrValue(data["ids"]);
};

//确认绑定
const confirmBinding = async (row) => {
    const nodes = treeRef.value?.getCheckedNodes();
    if (nodes.length <= 0) {
        window.$message.error("请先勾选要绑定的节点");
        return false;
    }
    //处理数据
    let newArr = [];
    for (let i = 0; i < nodes.length; i++) {
        newArr.push({
            id: nodes[i].id,
            adjustFactor: nodes[i].adjustFactor ?? "",
        });
    }
    //发起请求
    const { error, code, msg } = await mainApi.linkFormMaterial({
        projectId: projectId.value,
        contractId: contractId.value,
        materialId: row.id,
        forms: newArr,
    });
    if (!error && code === 200) {
        window.$message.success(msg);
        cancelBinding(row);
        getTableData().then();
    } else {
        window.$message.error(msg ?? "操作失败");
    }
};

//取消绑定
const cancelBinding = (row) => {
    rowBindingShow.value = false;
    row.rowBindingData = false;
};

//编辑表格
const tableColumn1 = [
    { key: "formName", name: "清单名称" },
    { key: "formNumber", name: "清单编号" },
    { key: "materialName", name: "绑定材料名称" },
    { key: "adjustFactor", name: "调差系数" },
    { key: "action", name: "操作", width: 110, align: "center" },
];
const tableData2 = ref([]);
const getLinkAllForm = async () => {
    const { data } = await mainApi.linkAllForm({
        projectId: projectId.value,
        contractId: contractId.value,
        materialId: tableRowID.value,
    });
    tableData2.value = getArrValue(data);
};

//编辑
const isFormModal = ref(false);
const tableRowID = ref("");
const rowEditClick = (row) => {
    isFormModal.value = true;
    tableRowID.value = row.id;
    getLinkAllForm();
};

//解除绑定关系
const dischargeBinding = (row) => {
    HcDelMsg(
        {
            title: "确认操作提醒",
            text: "确认要解除绑定关系？",
        },
        async (resolve) => {
            const { error, code, msg } = await mainApi.removeLinkForm(row.id);
            if (!error && code === 200) {
                window.$message.success(msg);
                getLinkAllForm();
                resolve();
            } else {
                window.$message.error(msg ?? "操作失败");
            }
        }
    );
};

//保存
const saveLoaing = ref(false);
const modalSave = async () => {
    const list = tableData2.value;
    if (list.length <= 0) {
        window.$message.error("无数据可提交");
        return;
    }
    //处理数据
    let newArr = [];
    for (let i = 0; i < list.length; i++) {
        newArr.push({
            id: list[i].id,
            adjustFactor: list[i].adjustFactor,
        });
    }
    //发起请求
    const { error, code, msg } = await mainApi.submitLinkForm(newArr);
    if (!error && code === 200) {
        window.$message.success(msg);
        modalClose();
    } else {
        window.$message.error(msg ?? "操作失败");
    }
};

//取消关闭
const modalClose = () => {
    isFormModal.value = false;
    tableData2.value = [];
    tableRowID.value = "";
};

//页面卸载
onDeactivated(() => {
    rowBindingShow.value = false;
});
</script>

<style lang="scss">
.hc-debit-pay-material-adjustment .el-tree {
    --el-fill-color-blank: transparent;
    --el-tree-node-hover-bg-color: white;
    .el-tree-node.no-form-check .el-tree-node__content .el-checkbox {
        display: none;
    }
    .el-tree-node.is-form-node .el-tree-node__content .el-checkbox {
        display: inline-flex;
    }
    .data-custom-tree-node {
        position: relative;
        display: flex;
        align-items: center;
        width: 100%;
        flex: 1;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        color: #101010;
        .level {
            position: relative;
            flex: 1;
            height: 100%;
            display: flex;
            align-items: center;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .submit-input {
            position: unset;
            margin-left: 10px;
            margin-right: 2px;
            width: 100px;
        }
        .el-input .el-input__wrapper {
            background-color: white;
        }
    }
}
</style>
