import { h, ref, onMounted, reactive, watch, toRaw, nextTick } from "vue";
import { request } from "@/utils/request";
import { useRoute, useRouter } from 'vue-router'
import ExamineDialog from "./examineDialog.vue";
import RejectDialog from './rejectDialog.vue';

const tableData = ref([]); // 表格数据
const modelVisible = ref(false); // 弹窗状态
const drawerVisible = ref(false); // 抽屉状态
// 弹窗内容
const model = reactive({
    title: '',
    content: null,
    props: {},
    onCancel: null,
    onConfirm: null,
    width: '',
    footerPosition: null,
    onCancelType: null,
    onConfirmName: null,
    onCancelName: null,
    tagContent: null,
    tagType: null,
});
const form = reactive({
});
// 抽屉内容
const drawer = reactive({
    title: '',
    content: null,
    props: {},
    onCancel: null,
    onConfirm: null,
    direction: 'rtl',
    size: '50%'
});
const dialogRef = ref(null); // 弹窗实例
const drawerRef = ref(null); // 抽屉实例

// 第二个弹窗
const model2 = reactive({
    title: '',
    content: null,
    props: {},
    onCancel: null,
    onConfirm: null,
    width: '',
    footerPosition: null,
    onCancelType: null,
    onConfirmName: null,
    onCancelName: null,
    tagContent: null,
    tagType: null,
});
const modelVisible2 = ref(false);
const dialogRef2 = ref(null);



// 过滤条件
const filterData = reactive({
})
// 分页
const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
    pageSizes: [10, 20, 50],
    layout: "prev, pager, next, jumper",
    onChange: (page, pageSize) => {
        pagination.current = page;
        pagination.pageSize = pageSize;
        getTableData(filterData);
    },
});

// 获取项目列表
const getTableData = async (filterData = {}) => {
    try {
        // 过滤空字符串属性
        const filteredParams = {};
        Object.keys(filterData).forEach(key => {
            if (filterData[key] !== '' && filterData[key] != null) {
                filteredParams[key] = filterData[key];
            }
        });

        const res = await request({
            url: '/snow-ops-platform/recovery/list',
            method: "GET",
            params: {
                ...filteredParams,
                submitTimeStart: filteredParams?.submitTimeStart ? filteredParams.submitTimeStart + `-01-01 00:00:00` : null,
                pageNum: pagination.current,
                pageSize: pagination.pageSize,
            }
        })
        if (res.code === '00000') {
            tableData.value = res.data.records
            pagination.total = res.data.total
        } else {
            throw new Error(res.message)
        }
    } catch (error) {
        ElMessage.error('获取项目列表失败');
        console.error('获取项目列表失败:', error);
    }
}




// 驳回项目
const rejectProject = async () => {
    try {
        const loading = ElLoading.service({
            lock: true,
            text: '操作中',
            background: 'rgba(0, 0, 0, 0.7)',
        })
        const res = await request({
            url: '/snow-ops-platform/recovery/approve',
            method: 'POST',
            data: {
                id: form.id,
                approveLevel: 2,
                isPass: false,
                rejectReason: form.rejectReason,
            }
        })
        loading.close();
        if (res.code === '00000') {
            ElMessage.success('操作成功');
            modelVisible.value = false;
            modelVisible2.value = false;
            getTableData(filterData);
        }
    } catch (error) {
        ElMessage.error('操作失败');
        console.error('驳回项目失败:', error);
    }
}

// 审批通过项目
const approveProject = async () => {
    try {
        const loading = ElLoading.service({
            lock: true,
            text: '操作中',
            background: 'rgba(0, 0, 0, 0.7)',
        })
        const res = await request({
            url: '/snow-ops-platform/recovery/approve',
            method: 'POST',
            data: {
                id: form.id,
                approveLevel: 2,
                isPass: true,
            }
        })
        loading.close();
        if (res.code === '00000') {
            ElMessage.success('操作成功');
            modelVisible.value = false;
            modelVisible2.value = false;
            getTableData(filterData);
        }
    } catch (error) {
        ElMessage.error('操作失败');
        console.error('审批项目失败:', error);
    }
}

// 获取项目详情
const getDetailData = async (id) => {
    try {
        const res = await request({
            url: `/snow-ops-platform/recovery/getById`,
            method: 'GET',
            params: {
                id: id,
            }
        });
        if (res.code === '00000') {
            return res.data;
        } else {
            throw new Error(res.message);
        }
    } catch (error) {
        ElMessage.error('获取项目详情失败');
        console.error('获取项目详情失败:', error);
    }
}





export default () => {

    const router = useRouter();

    // 记录访问的项目管理模块
    onMounted(() => {
        sessionStorage.setItem('lastVisitedProjectManagement', 'projectManagement2')
    })

    const columns = [
        {
            prop: "districtName",
            label: "区县",
        },
        {
            prop: "routeNo",
            label: "路线编码",
        },
        // {
        //     prop: "disasterType",
        //     label: "灾害类型",
        // },
        {
            prop: "startStakeNo",
            label: "起点桩号",
        },
        {
            prop: "endStakeNo",
            label: "止点桩号",
        },
        {
            prop: "implementMileage",
            label: "实施里程（公里）",
        },
        // {
        //     prop: "technicalGrade",
        //     label: "技术等级",
        // },
        {
            prop: "totalInvestment",
            label: "总投资金额(万元)",
        },
        {
            prop: "estimatedCost",
            label: "投资估算(万元)",
        },
        {
            prop: "subsidyAmount",
            label: "补助金额(万元)",
        },
        {
            prop: "fundingSource",
            label: "资金来源",
        },
        {
            prop: "startTime",
            label: "开工或预计开工时间",
        },
        {
            prop: "endTime",
            label: "完工或预计完工时间",
        },
        {
            prop: "projectProgress",
            label: "项目进度情况",
        },
        // {
        //     prop: "reportStatus",
        //     label: "申报状态",
        //     formatter: (row) => {
        //         const colorMap = {
        //             0: '#409EFF', // 蓝色 - 未申报
        //             1: '#67C23A', // 绿色 - 已申报
        //         };
        //         const textMap = {
        //             0: '未申报',
        //             1: '已申报',
        //         };
        //         const status = row.reportStatus;
        //         const color = colorMap[status] || '#909399';
        //         const text = textMap[status] || '未知状态';
        //         return h(ElText, { style: { color } }, text);
        //     }
        // },
        {
            prop: "approvalStatus",
            width: 150,
            label: "审批状态",
            formatter: (row) => {
                const colorMap = {
                    0: '#409EFF', // 蓝色 - 待区县审批
                    1: '#67C23A', // 绿色 - 区县审批通过
                    2: '#F56C6C', // 红色 - 区县审批驳回
                    3: '#67C23A', // 绿色 - 业务部门审批通过
                    4: '#F56C6C', // 红色 - 业务部门审批驳回
                };
                const textMap = {
                    0: '待区县审批',
                    1: '区县审批通过(待业务部门审批)',
                    2: '区县审批驳回',
                    3: '业务部门审批通过',
                    4: '业务部门审批驳回',
                };
                const status = row.approvalStatus;
                const color = colorMap[status] || '#909399';
                const text = textMap[status] || '未知状态';
                return h(ElText, { style: { color } }, text);
            }
        },
        {
            prop: "updateTime",
            label: "更新日期",
        },
        {
            label: "操作",
            fixed: "right",
            width: 150,
            render: (row) => () =>
                h("div", { class: "action-btns" }, [
                    row.approvalStatus === 1 ? h(
                        ElButton,
                        {
                            type: "primary",
                            link: true,
                            onClick: async () => {
                                openExamineDialog(row);
                            },
                        },
                        () => "审批"
                    ) : null,
                    h(
                        ElButton,
                        {
                            type: "primary",
                            link: true,
                            style: row.approvalStatus === 1 ? "margin-left: 10px;" : "",
                            onClick: async () => {
                                gotoDetaillPage(row);
                            },
                        },
                        () => "详情"
                    ),
                ]),
        },
    ]

    // 打开审批弹窗
    const openExamineDialog = async (row) => {
        const data = await getDetailData(row.id)
        model.title = '项目审批';
        Object.assign(form, data);
        model.props = {
            form: form,
        };
        model.content = ExamineDialog;
        model.onCancel = () => {
            model2.title = '驳回原因';
            model2.props = {
                form: form,
            }
            model2.content = RejectDialog;
            model2.onCancel = () => {
                modelVisible2.value = false;
            }
            model2.onConfirm = async () => {
                await dialogRef2?.value?.dynamicComponentRef?.formRef.validate().then(async () => {
                    await rejectProject()
                })
                    .catch((err) => {
                        ElMessage.error('请处理表单中的错误项');
                    });

            }
            model2.width = '30%'
            model2.footerPosition = 'center'
            model2.onConfirmName = '确定'
            model2.onCancelName = '取消'
            modelVisible2.value = true;
        };
        model.onConfirm = async () => {
            await dialogRef?.value?.dynamicComponentRef?.formRef.validate().then(async () => {
                try {
                    await ElMessageBox.confirm(
                        '确定该项目申请通过恢复重建？',
                        '审批确认',
                        {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning',
                        }
                    );
                    await approveProject();
                } catch {
                    ElMessage.info('已取消审批');
                }
            })
                .catch((err) => {
                    ElMessage.error('请处理表单中的错误项');
                });
        };
        model.width = "50%"
        model.footerPosition = 'flex-end'
        model.onCancelType = 'danger'
        model.onConfirmName = '审批通过'
        model.onCancelName = '审批驳回'
        // model.tagType = 'warning'
        // model.tagContent = '测试'
        modelVisible.value = true;
    }

    // 跳转至详情页面
    const gotoDetaillPage = (row) => {
        router.push({
            name: 'projectDetail2',
            params: {
                data: encodeURIComponent(JSON.stringify(row.id))
            }
        })
    }

    onMounted(() => {
        getTableData();
    })


    watch(filterData, (val) => {
        getTableData(filterData);
    }, { deep: true })


    return {
        tableData,
        filterData,
        pagination,
        columns,

        modelVisible,
        model,
        drawerVisible,
        drawer,
        dialogRef,
        drawerRef,
        openExamineDialog,

        model2,
        modelVisible2,
        dialogRef2,
    }
}