<template>
    <div class="hc-project-list-adjust-excel-set-e-visa">
        <el-form
            ref="formRef"
            :model="formModel"
            :rules="formRules"
            label-position="left"
            label-width="auto"
        >
            <el-form-item label="元素坐标：" prop="colName">
                <el-input
                    v-model="formModel.colName"
                    placeholder="请点击左侧表单"
                    disabled
                />
            </el-form-item>
            <el-form-item label="证书类型：" prop="type">
                <el-select
                    v-model="formModel.type"
                    filterable
                    block
                    placeholder="请选择证书类型"
                    @change="signTypeChang"
                >
                    <el-option label="个人证书" :value="2" />
                    <el-option label="企业证书" :value="6" />
                </el-select>
            </el-form-item>
            <el-form-item
                v-if="formModel.type === 2"
                label="所属方："
                prop="roleType"
            >
                <el-select
                    v-model="formModel.roleType"
                    filterable
                    block
                    placeholder="请选择所属方"
                    @change="getRoleData"
                >
                    <el-option
                        v-for="item in roleType"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item
                v-if="formModel.type === 2"
                label="签字角色："
                prop="sigRoleId"
            >
                <el-select
                    v-model="formModel.sigRoleId"
                    :disabled="isNullES(formModel.roleType)"
                    filterable
                    block
                    placeholder="请选择签字角色"
                >
                    <el-option
                        v-for="item in roleData"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item v-if="formModel.type === 2" label="签字时间：">
                <el-checkbox
                    v-model="formModel.timeState"
                    :true-value="1"
                    :false-value="2"
                    >是否需要获取签字时间</el-checkbox
                >
            </el-form-item>
            <el-form-item
                v-if="formModel.timeState === 1"
                label="时间元素："
                prop="timeName"
                class="time-name-form-item"
            >
                <el-input
                    v-model="formModel.timeName"
                    placeholder="请点击后，再在左边选择元素"
                    @focus="timeElementFocus"
                >
                    <template #append>
                        <el-button
                            type="primary"
                            :disabled="!isTimeElement"
                            @click="timeElementFinish"
                            >完成</el-button
                        >
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item
                v-if="formModel.type === 6"
                label="签章类型："
                prop="sigRoleId"
            >
                <el-select
                    v-model="formModel.sigRoleId"
                    filterable
                    block
                    placeholder="请选择签章类型"
                >
                    <el-option
                        v-for="item in signData"
                        :key="item.dictKey"
                        :label="item.dictValue"
                        :value="item.dictKey"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="偏移位X：" prop="pyzbx">
                <el-input
                    v-model="formModel.pyzbx"
                    type="number"
                    placeholder="横坐标，负代表左移，正代表右移，偏移量50大概等于一厘米"
                />
            </el-form-item>
            <el-form-item label="偏移位Y：" prop="pyzby">
                <el-input
                    v-model="formModel.pyzby"
                    type="number"
                    placeholder="纵坐标，负代表下移，正代表上移，偏移量50大概等于一厘米"
                />
            </el-form-item>
        </el-form>
        <div class="action-btn-box mb-40px mt-10px text-center">
            <el-button v-if="isEditMode" type="success" @click="saveListClick"
                >保存数据</el-button
            >
            <el-button
                v-if="isEditMode"
                type="info"
                style="margin-left: 50px"
                @click="cancelListClick"
                >取消</el-button
            >
            <el-button v-else type="primary" @click="addToListClick"
                >添加到列表</el-button
            >
            <el-button
                type="warning"
                style="margin-left: 50px"
                @click="getPriwbsPdf"
                >预览表</el-button
            >
        </div>
        <hc-card-item title="已配数据：">
            <template #extra>
                <el-button
                    type="primary"
                    size="small"
                    :loading="submitLoading"
                    @click="dialogSubmit"
                    >保存入库</el-button
                >
            </template>
            <hc-table
                :column="tableColumn"
                :datas="tableData"
                :is-current-row="false"
                :is-index="false"
            >
                <template #action="{ row, index }">
                    <el-link
                        v-if="row.isEditMode"
                        type="success"
                        @click="saveListClick"
                        >保存</el-link
                    >
                    <el-link
                        v-else
                        type="primary"
                        @click="rowEditClick(row, index)"
                        >编辑</el-link
                    >
                    <el-link type="danger" @click="rowDelClick(row, index)"
                        >删除</el-link
                    >
                </template>
            </hc-table>
        </hc-card-item>
    </div>
</template>

<script setup>
import { onMounted, ref, watch } from "vue";
import { HcDelMsg } from "hc-vue3-ui";
import {
    deepClone,
    formValidate,
    getArrValue,
    getObjValue,
    isNullES,
    newWindow,
} from "js-fast-way";
import mainApi from "~api/project/tree";

const props = defineProps({
    info: {
        type: Object,
        default: () => ({}),
    },
    type: {
        type: [String, Number],
        default: "", //默认没有，独立表单库类型为2
    },
});

//事件
const emit = defineEmits(["finish"]);

//监听数据
const dataInfo = ref(props.info);
const type = ref(props.type);
watch(
    () => [props.info, props.type],
    ([data, tpe]) => {
        dataInfo.value = getObjValue(data);

        type.value = tpe;
    },
    { immediate: true, deep: true }
);
//渲染完成
onMounted(() => {
    getSigList();
    getRoleTypeData();
    formModel.value = { type: 2, pyzbx: 0, pyzby: 0, timeState: 2 };
});

//获取数据
const getSigList = async () => {
    const { pkeyId, excelId, primaryKeyId, excelIds } = dataInfo.value;
    const { data } = await mainApi.getSigList({
        current: 0,
        size: 99999,
        type: 2,
        tabId: type.value == 2 ? primaryKeyId : pkeyId,
        excelId: type.value == 2 ? excelIds : excelId,
    });
    tableData.value = getArrValue(data?.records);
};

//获取所属方
const roleType = ref([]);
const getRoleTypeData = async () => {
    const { data } = await mainApi.getRoleType();
    roleType.value = getArrValue(data);
};

//获取签字角色
const roleData = ref([]);
const getRoleData = async () => {
    formModel.value.sigRoleId = "";
    const { roleType } = formModel.value;
    if (isNullES(roleType)) {
        roleData.value = [];
        return;
    }
    const { data } = await mainApi.getRoleInfoByParentId({
        ParentId: roleType,
    });
    roleData.value = getArrValue(data);
};

//获取签章类型
const signData = ref([]);
const getSignData = async () => {
    const { data } = await mainApi.findPfxType({ typeOrStatus: "pfx_type" });
    signData.value = getArrValue(data);
};

//证书类型
const signTypeChang = () => {
    const { type } = formModel.value;
    if (type === 6) {
        getSignData();
    }
    formModel.value.sigRoleId = "";
};

//时间元素
const isTimeElement = ref(false);
const timeElementFocus = () => {
    isTimeElement.value = true;
};
const timeElementFinish = () => {
    isTimeElement.value = false;
};

//基础表单
const formRef = ref(null);
const formModel = ref({});
const formRules = {
    colName: {
        validator: (rule, value, callback) => {
            if (isNullES(value)) {
                callback(new Error("请先获取元素坐标"));
            } else if (value === "警告") {
                callback(new Error("警告框不能配置电签"));
            } else {
                callback();
            }
        },
        required: true,
        trigger: "change",
    },
    type: { required: true, trigger: "change", message: "请选择证书类型" },
    roleType: { required: true, trigger: "change", message: "请选择所属方" },
    sigRoleId: {
        validator: (rule, value, callback) => {
            const { type } = formModel.value;
            if (type === 2 && isNullES(value)) {
                callback(new Error("请选择签字角色"));
            } else if (type === 6 && isNullES(value)) {
                callback(new Error("请选择签章类型"));
            } else {
                callback();
            }
        },
        required: true,
        trigger: "change",
    },
    timeName: {
        validator: (rule, value, callback) => {
            const { timeState } = formModel.value;
            if (timeState === 1 && isNullES(value)) {
                callback(new Error("请选择时间元素"));
            } else {
                callback();
            }
        },
        required: true,
        trigger: "change",
    },
};

//数据表格
const tableColumn = [
    { key: "colName", name: "元素位置" },
    { key: "sigRoleName", name: "签字岗位" },
    { key: "timeName", name: "签字时间" },
    { key: "pyzbx", name: "偏移X" },
    { key: "pyzby", name: "偏移Y" },
    {
        key: "action",
        name: "操作",
        align: "center",
        width: 100,
        fixed: "right",
    },
];
const tableData = ref([]);

//编辑数据
const isEditMode = ref(false);
const rowEditClick = async (row, index) => {
    if (isEditMode.value) {
        window.$message.warning("当前已有数据在编辑，请先完成或取消");
        return;
    }
    let sigRoleId = "",
        rowType = 2;
    if (isNullES(row.id)) {
        const obj = deepClone(row);
        rowType = obj.type;
        sigRoleId = obj.sigRoleId;
        formModel.value = deepClone(row);
        formModel.value.isIndex = index;
    } else {
        const { pkeyId, primaryKeyId } = dataInfo.value;
        const { data } = await mainApi.getSignDetail({
            id: row.id,
            tabId: type.value == 2 ? primaryKeyId : pkeyId,
        });
        const res = getObjValue(data);
        const obj = deepClone(res);
        obj.roleType = obj.parentRoleId;
        rowType = res.type;
        sigRoleId = res.sigRoleId;
        formModel.value = obj;
        formModel.value.isIndex = index;
    }
    if (rowType === 2) {
        await getRoleTypeData();
        await getRoleData();
    } else {
        await getSignData();
    }
    formModel.value.sigRoleId = sigRoleId;
    row.isEditMode = true;
    isEditMode.value = true;
};

//取消修改
const cancelListClick = () => {
    const { isIndex } = formModel.value;
    tableData.value[isIndex].isEditMode = false;
    formModel.value = { type: 2, pyzbx: 0, pyzby: 0, timeState: 2 };
    isEditMode.value = false;
};

//统一验证
const formValidatorData = async () => {
    const isForm = await formValidate(formRef.value);
    if (!isForm) return false;
    const form = deepClone(formModel.value);
    const table = tableData.value;
    //已配数据
    let isValidator = true;
    for (let i = 0; i < table.length; i++) {
        // 位置只能添加一个
        if (table[i].colName === form.colName) {
            window.$message.warning("位置只能配置一个电签");
            isValidator = form;
            break;
        }
    }
    if (!isValidator) return false;
    //获取签字角色
    let sigRoleName = "";
    if (form.type === 2) {
        const info = roleData.value.find(
            (item) => item.value === form.sigRoleId
        );
        sigRoleName = isNullES(info) ? "" : info.label || "";
    } else if (form.type === 6) {
        const info = signData.value.find(
            (item) => item.dictKey === form.sigRoleId
        );
        sigRoleName = isNullES(info) ? "" : info.dictValue || "";
    }
    formModel.value.sigRoleName = sigRoleName;
    formModel.value.timeState = form.timeState || 2;
    return true;
};

//添加到列表
const addToListClick = async () => {
    const isForm = await formValidatorData();
    if (!isForm) return false;
    const form = deepClone(formModel.value);
    tableData.value.push(form);
    formModel.value = { type: 2, pyzbx: 0, pyzby: 0, timeState: 2 };
};

//保存数据
const saveListClick = async () => {
    const isForm = await formValidatorData();
    if (!isForm) return false;
    const form = deepClone(formModel.value);
    form.isEditMode = false;
    tableData.value[form.isIndex] = form;
    formModel.value = { type: 2, pyzbx: 0, pyzby: 0, timeState: 2 };
    isEditMode.value = false;
};

//删除数据
const rowDelClick = (row, index) => {
    HcDelMsg(async (resolve) => {
        if (isNullES(row.id)) {
            tableData.value.splice(index, 1);
            resolve(); //关闭弹窗的回调
            return;
        }
        const { pkeyId } = dataInfo.value;
        const { isRes } = await mainApi.remove(row.id, pkeyId);
        if (!isRes) {
            resolve(); //关闭弹窗的回调
            return;
        }
        tableData.value.splice(index, 1);
        resolve(); //关闭弹窗的回调
    });
};

//预览pdf
const getPriwbsPdf = async () => {
    const { pkeyId } = dataInfo.value;
    const { data } = await mainApi.getPriwbsPdf(pkeyId);
    if (isNullES(data)) {
        window.$message.warning("暂无预览数据");
        return;
    }
    newWindow(data);
};

//提交
const submitLoading = ref(false);
const dialogSubmit = async () => {
    const table = tableData.value;
    if (table.length <= 0) {
        window.$message.warning("请先添加数据");
        return;
    }
    submitLoading.value = true;
    const { pkeyId, primaryKeyId } = dataInfo.value;
    const { isRes } = await mainApi.saveSig({
        dataInfo: table,
        tabId: type.value == 2 ? primaryKeyId : pkeyId,
    });
    submitLoading.value = false;
    if (!isRes) return;
    window.$message.success("操作成功");
    emit("finish");
};

//设置dom数据
const setDomData = (item) => {
    if (isTimeElement.value) {
        formModel.value.timeName = item.text;
        formModel.value.timeColKey = item.key;
    } else {
        const { pkeyId, primaryKeyId } = dataInfo.value;
        formModel.value.colName = item.text;
        formModel.value.colKey = item.key;
        formModel.value.tabId = type.value == 2 ? primaryKeyId : pkeyId;
    }
};

//导出函数
defineExpose({
    setDomData,
});
</script>

<style scoped lang="scss">
.hc-project-list-adjust-excel-set-e-visa :deep(.hc-card-item-box) {
    padding: 6px 14px 14px;
    .hc-card-item-header {
        color: #101010;
        font-size: 14px;
        font-weight: unset;
    }
}
.hc-project-list-adjust-excel-set-e-visa
    :deep(.time-name-form-item)
    .el-form-item__content
    .el-input
    .el-input-group__append {
    .el-button {
        background-color: var(--el-button-bg-color);
        border-color: var(--el-button-border-color);
        color: var(--el-button-text-color);
        border-radius: 0 var(--el-border-radius-base)
            var(--el-border-radius-base) 0;
    }
    .el-button.is-disabled {
        background-color: var(--el-button-disabled-bg-color);
        border-color: var(--el-button-disabled-border-color);
        color: var(--el-button-disabled-text-color);
    }
}
</style>
