<template>
    <div class="page-container list-container">
        <!-- 功能按钮区 -->
        <div class="list-btns-container">

        </div>
        <!-- 搜索区 -->
        <el-form class="list-search-container" size="small" :model="queryParams" ref="queryRef" :inline="true"
            label-width="68px">
            <el-form-item label="工作月：">
                <el-date-picker v-model="queryParams.date" format="YYYY-MM" value-format="YYYY-MM-DD" type="month"
                    placeholder="请选择工作月" :disabled-date="disabledDate"></el-date-picker>
            </el-form-item>
            <el-form-item label="客户名称：" prop="companyName">
                <el-input v-model="queryParams.companyName" style="width: 150px" placeholder="请输入客户名称" clearable
                    @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="来源：" prop="fromCompanyName">
                <el-input v-model="queryParams.fromCompanyName" placeholder="请输入来源" clearable
                    @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 列表区 -->
        <el-table v-loading="loading" :data="list" size="small" border height="100%"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <!-- <el-table-column label="工单号" align="center" prop="workOrderNo" width="200" /> -->
            <el-table-column label="客户名称" align="center" min-width="250" prop="companyName" />
            <el-table-column label="税号" align="center" prop="socialCreditCode" min-width="200" />
            <el-table-column label="来源" align="center" width="100" prop="fromCompanyName" />
            <el-table-column label="工单类型" align="center" prop="amount" min-width="80">
                <template #default="scope">
                    {{ scope.row.type === 1 ? "循环工单" : "代办工单" }}
                </template>
            </el-table-column>
            <el-table-column label="项目" align="center" prop="taskTypeName" min-width="140">
                <template #default="scope">
                    {{ scope.row.taskTypeName }}
                    {{
                    scope.row.taskTypeDetailName
                    ? `-${scope.row.taskTypeDetailName}`
                    : ""
                    }}
                </template>
            </el-table-column>
            <el-table-column label="起始月" align="center" width="90" min-prop="startMonth">
                <template #default="scope">
                    {{
                    scope.row.type === 1
                    ? scope.row.startMonth !="0000-00-00"
                    ? moment(scope.row.startMonth).format("YYYY年MM月")
                    : ""
                    : "-"
                    }}
                </template>
            </el-table-column>
            <el-table-column label="结束月" align="center" min-width="90" prop="endMonth">
                <template #default="scope">
                    {{
                    scope.row.type === 1
                    ? scope.row.endMonth !="0000-00-00"
                    ? moment(scope.row.endMonth).format("YYYY年MM月")
                    : ""
                    : "-"
                    }}
                </template>
            </el-table-column>
            <el-table-column label="工单月数" align="center" min-width="80" prop="monthNum">
                <template #default="scope">
                    {{ scope.row.type === 1 ? scope.row.monthNum : "-" }}
                </template>
            </el-table-column>
            <el-table-column label="工单执行人" align="center" min-width="100">
                <template #default="scope">
                    {{
                    scope.row.toAccountName
                    }}
                </template>
            </el-table-column>
        </el-table>
        <!-- <contract-form ref="contractRef" :get-list="getList" /> -->
        <!-- 分页 -->
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />
        <init-month-dialog ref="initMonthDialogRef" :get-list="checkCurrentMonthHandle"
            :setCurrentMonth="setCurrentMonth" />

        <set-entrust-dialog ref="setEntrustDialogRef" :get-list="getList" @submit="handleAddEntrust" />

    </div>
</template>

<script setup name="HistoryWorkOrderForFactory">
    import InitMonthDialog from "../initMonthDialog";
    import { getToken, getTenant } from "@/utils/auth";
    import {
        listCurrentWorkOrder,
        checkCurrent,
        exportCurrentWorkOrder,
        delEntrust,
        transNext,
        addEntrust, listHistory
    } from "@/api/business/entrust/currentWorkOrder";
    import SetEntrustDialog from "../setEntrustDialog";
    import useUserStore from "@/store/modules/user";
    // import { ca } from "element-plus/es/locale";
    const { proxy } = getCurrentInstance();
    const currentMonth = ref(null);
    /** 字典数组区 */
    /** 查询 对象 */

    const list = ref([]);
    const loading = ref(true);
    const cancel = ref(true);
    const multiple = ref(true);
    const ids = ref([]);
    const selections = ref([]);
    const single = ref(false);
    const total = ref(0);
    const prev = ref([]);
    const tenantId = ref(getTenant());
    const permissions = useUserStore().permissions;
    const all_permission = "*:*:*";

    const initMonthDialogRef = ref(null);
    const setEntrustDialogRef = ref(null);

    const showInitMonth = ref(false);

    const { contract_verify_status } = proxy.useDict("contract_verify_status");
    const { contract_status } = proxy.useDict("contract_status");
    onActivated(() => {
        // 你的逻辑
        getList();
    });
    /** 查询对象 */
    const queryParams = ref({
        pageNum: 1,
        pageSize: 20,

    });

    const editStatus = {
        startMonth: false,
    };
    function disabledDate(time) {
        const currentMonth = new Date().getMonth();
        const selectedMonth = time.getMonth();
        const currentYear = new Date().getFullYear();
        const selectedYear = time.getFullYear();

        // 禁用当前年份之后的所有月份
        if (selectedYear > currentYear) {
            return true;
        }

        // 如果选择的是当前年份，只能选择当前月份之前的月份
        return selectedYear === currentYear && selectedMonth >= currentMonth;
    }

    function checkCurrentMonthHandle() {
        checkCurrent().then((res) => {
            if (res.data.checkResult === true) {
                setCurrentMonth(res.data.currentMonth);
                getList();
            } else {
                showInitMonthDialog();
            }
        });
    }

    function showInitMonthDialog() {
        initMonthDialogRef.value.open();
    }

    /***********************  方法区  ****************************/
    // 禁用当前月及之后的月份
    const beforeCurrentMonth = (time) => {
        const currentMonth = new Date().getMonth();
        const selectedMonth = time.getMonth();
        return selectedMonth >= currentMonth;
    };
    /** 查询company列表 */
    function getList() {
        loading.value = true;
        console.log(queryParams.value);

        queryParams.value.currentMonth = currentMonth.value;
        listHistory(queryParams.value).then((response) => {
            list.value = response.rows;
            console.log(response);
            total.value = response.total;
        }).finally(() => {
            loading.value = false;
        });
    }

    /** 取消委托按钮操作 */
    function cancelEntrust() {
        if (selections.value.length === 0) {
            proxy.$modal.msgError("请选择要取消委托的数据");
            return;
        }
        proxy.$modal
            .confirm("是否确认取消委托?")
            .then(function () {

            });
    }

    //判断是否有权限
    function viewAdviser(quer) {
        return permissions.includes(all_permission) || permissions.includes(quer);
    }

    /** 搜索按钮操作 */
    function handleQuery() {
        queryParams.value.pageNum = 1;
        getList();
    }

    /** 重置按钮操作 */
    function resetQuery() {
        proxy.resetForm("queryRef");
        handleQuery();
    }
    /** 新增导入操作 */
    function exportZero() {
        proxy.$refs.exportRef.open();
    }
    // 多选框选中数据
    function handleSelectionChange(selection) {
        ids.value = selection.map((item) => item.id);
        selections.value = selection;

        //取消委托计数
        let cancelNum = 0;
        //设置委托计数
        let multipleNum = 0;
        //判断是否有执行人
        selections.value.forEach((item) => {
            if (item.entrust) {
                //有执行人
                if (item.entrust.toAccountName) {
                    cancelNum++;
                }
            }
            //没有执行人
            if (!item.entrust) {
                multipleNum++;
            }
        });

        //判断是否有选中数据
        if (!selections.value.length > 0) {
            multiple.value = true;
            cancel.value = true;
        } //判断是否设置执行人和设置委托选中
        else if (cancelNum > 0 && multipleNum > 0) {
            cancel.value = cancelNum > 0;
            multiple.value = multipleNum > 0;
        } else {
            cancel.value = !cancelNum > 0;
            multiple.value = !multipleNum > 0;
        }
    }

    /** 导出按钮操作 */
    function handleExport() {
        exportCurrentWorkOrder(queryParams.value);
    }

    function setCurrentMonth(month) {
        currentMonth.value = month;
    }

    function setEntrustHandle() {
        setEntrustDialogRef.value.open({
            selections: selections.value,
            optionCurrentMonth: currentMonth.value,
        });
    }

    function delEntrustHandle() {
        const entrust = {
            workMonth: currentMonth.value,
            workOrderIds: ids.value,
        };
        proxy.$modal.confirm("是否确认取消委托？").then(() => {
            delEntrust(entrust).then((res) => {
                proxy.$modal.msgSuccess("取消成功");
                getList();
            });
        });
    }

    function transEntrustHandler() {
        // proxy.$modal.confirm("确定流转到下一月？").then(() => {
        //     transNext().then((res) => {
        //       proxy.$modal.msgSuccess("流转成功");
        //       checkCurrentMonthHandle();
        //     });
        //   });
        let currentDate = new Date().getMonth() + 1;
        let formattedMonth = currentDate.toString().padStart(2, '0');
        let month = currentMonth.value.split('-')[1];
        console.log(formattedMonth);
        if (month < formattedMonth) {
            proxy.$modal.confirm("确定流转到下一月？").then(() => {
                transNext().then((res) => {
                    proxy.$modal.msgSuccess("流转成功");
                    checkCurrentMonthHandle();
                });
            });
        } else {
            // //真实月 ！= 当前月 
            if (month != formattedMonth) {
                proxy.$modal.msgError("每月只可流转一次");
            } else {
                let currentDay = new Date().getDate()
                let cutoffDay = 20;
                //如果当前月时间小于20号
                if (currentDay < cutoffDay) {
                    proxy.$modal.msgError("每月20号后才能流转");
                } else {
                    proxy.$modal.confirm("确定流转到下一月？").then(() => {
                        transNext().then((res) => {
                            proxy.$modal.msgSuccess("流转成功");
                            checkCurrentMonthHandle();
                        });
                    });
                }

            }
        }

    }

    function handleAddEntrust(data) {
        addEntrust(data).then((response) => {
            proxy.$modal.msgSuccess("设置完成!");
            setEntrustDialogRef.value.cancel();
            getList();
        });
    }

    checkCurrentMonthHandle();
</script>