<template>
    <div class="app-container">
        <!-- 月计划填报管理列表 -->
        <ComTable
            ref="comTableRef"
            :form-columns="formColumns"
            :table-columns="tableColumns"
            :load-data="listMonthlyPlanAPI"
            :show-toolbar="true"
            :show-action="true"
            :action-columns="actionColumns"
        >
            <template #toolbar="{ formData }">
                <ComButton
                    type="primary"
                    icon="Plus"
                    @click="onHandleAdd"
                    v-hasPermi="['plan:monthlyPlan:add']"
                >
                    新增月计划
                </ComButton>
                <ComButton
                    type="info"
                    plain
                    icon="UploadFilled"
                    @click="onExportPersonArrange(formData)"
                    v-hasPermi="['plan:monthlyPlan:exportPersonArrange']"
                >
                    导出人员安排表
                </ComButton>
                <ComButton
                    type="info"
                    plain
                    icon="UploadFilled"
                    @click="onExportOverallSummary(formData)"
                    v-hasPermi="['plan:monthlyPlan:exportOverallSummary']"
                >
                    导出整体汇总表
                </ComButton>
                <ComButton
                    type="info"
                    plain
                    icon="UploadFilled"
                    @click="onExportWorkloadSummary(formData)"
                    v-hasPermi="['plan:monthlyPlan:exportWorkloadSummary']"
                >
                    导出工作量汇总表
                </ComButton>
            </template>

            <template #workAmount="{ row }">
                <template v-for="(item, index) in row.workloadList" :key="index">
                    <span>{{ item.workloadCategoryName || '类型' }} {{ item.workloadNum }}</span>
                    <span v-if="index !== row.workloadList.length - 1">，</span>
                </template>
            </template>
        </ComTable>

        <ComDialog :dialog-config="dialogConfig" @closeDialogOuter="onCloseDialogOuter">
            <template #outerContent>
                <AddForm ref="addFormRef" />
                <el-row class="common-btn-row fixed-bottom">
                    <ComButton plain type="info" @click="onHandleCancel">取消</ComButton>
                    <ComButton @click="onHandleSave">保存</ComButton>
                </el-row>
            </template>
        </ComDialog>
    </div>
</template>

<script setup name="MonthlyPlan">
import { ref, computed, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
import { useOptions } from '@/hooks/useOptions'
import {
    listMonthlyPlanAPI,
    addMonthlyPlanAPI,
    delMonthlyPlanAPI,
} from '@/api/planMange/monthlyPlan.js'
import { getInspectionStationSelectAPI, getMajorTypeCategorySelectAPI } from '@/api/common.js'
import useDictStore from '@/store/modules/dict'
import { selectDictLabel } from '@/utils/ruoyi'
import config from './config'
import ComTable from '@/components/ComTable/index.vue'
import ComButton from '@/components/ComButton/index.vue'
import ComDialog from '@/components/ComDialog/index.vue'
import AddForm from './addForm.vue'
import dayjs from 'dayjs'

const { proxy } = getCurrentInstance()
const dictStore = useDictStore()
const { plan_risk_level } = proxy.useDict('plan_risk_level')
const router = useRouter()
const { tableColumns: baseTableColumns, dialogConfig, buildFormColumns } = config

const comTableRef = ref(null)
const addFormRef = ref(null)

// 运检站
const { options: inspectionStationOptions } = useOptions(
    'inspectionStationOptions',
    getInspectionStationSelectAPI,
    { category: 0 },
)

// 专业
const { options: majorTypeCategoryOptions } = useOptions(
    'majorTypeCategoryOptions',
    getMajorTypeCategorySelectAPI,
    {
        category: 0,
    },
)

// 业务类型
const { options: planBusinessTypeOptions } = useOptions(
    'planBusinessTypeOptions',
    getMajorTypeCategorySelectAPI,
    {
        category: 1,
    },
)
// 搜索表单配置（当前月计划场景暂不依赖下拉接口，直接使用静态配置）
const formColumns = computed(() =>
    buildFormColumns(
        inspectionStationOptions.value,
        majorTypeCategoryOptions.value,
        planBusinessTypeOptions.value,
        plan_risk_level.value,
    ),
)

// 创建动态 formatter 函数，每次执行时从 store 获取最新的字典数据
const createDynamicDictFormatter = (dictType, fieldName = null) => {
    return (row, column, cellValue) => {
        const value = fieldName ? row[fieldName] : cellValue
        // 每次执行时都从 store 获取最新的字典数据
        const dictData = dictStore.getDict(dictType) || []
        return selectDictLabel(dictData, value)
    }
}

// 构建表格列配置，添加字典映射的 formatter
const tableColumns = computed(() => {
    return baseTableColumns.map((column) => {
        if (column.prop === 'riskLevel') {
            return {
                ...column,
                // 使用动态 formatter，每次执行时都会获取最新的字典数据
                formatter: createDynamicDictFormatter('plan_risk_level', 'riskLevel'),
            }
        }
        return column
    })
})

// 操作列
const actionColumns = [
    {
        label: '详情',
        type: 'primary',
        link: true,
        permission: ['plan:monthlyPlan:detail'], // 权限控制：使用 v-hasPermi 指令控制按钮显示
        handler: (row) => {
            const {
                monthlyPlanId,
                inspectionStationName,
                projectName,
                workContent,
                plannedStartTime,
                plannedEndTime,
            } = row
            router.push({
                path: '/plan/monthlyPlanEdit/index',
                query: {
                    projectName,
                    workContent,
                    monthlyPlanId,
                    mode: 'detail',
                    plannedEndTime,
                    plannedStartTime,
                    inspectionStationName,
                },
            })
        },
    },
    {
        label: '编辑',
        type: 'primary',
        link: true,
        permission: ['plan:monthlyPlan:edit'], // 权限控制：使用 v-hasPermi 指令控制按钮显示
        handler: (row) => {
            const {
                monthlyPlanId,
                inspectionStationName,
                projectName,
                workContent,
                plannedStartTime,
                plannedEndTime,
            } = row
            router.push({
                path: '/plan/monthlyPlanEdit/index',
                query: {
                    projectName,
                    workContent,
                    monthlyPlanId,
                    plannedEndTime,
                    plannedStartTime,
                    inspectionStationName,
                },
            })
        },
    },
    {
        label: '删除',
        type: 'danger',
        link: true,
        permission: ['plan:monthlyPlan:remove'], // 权限控制：使用 v-hasPermi 指令控制按钮显示
        handler: (row) => {
            proxy.$modal.confirm('是否确认删除该月计划？').then(async () => {
                const result = await delMonthlyPlanAPI({ monthlyPlanId: row.monthlyPlanId })
                if (result.code === 200) {
                    proxy.$modal.msgSuccess('删除成功')
                    comTableRef.value?.refresh()
                }
            })
        },
    },
]

// 新增
const onHandleAdd = () => {
    dialogConfig.outerVisible = true
}

// 取消
const onHandleCancel = () => {
    dialogConfig.outerVisible = false
}

// 保存
const onHandleSave = async () => {
    await addFormRef.value.validate()

    const paramsList = addFormRef.value.getSelectedTasks().map((item) => ({
        planManagementId: item.planManagementId,
        monthlyPlan: item.planManagementMonth,
        inspectionStationId: item.inspectionStationId,
        inspectionStationName: item.inspectionStationName,
        projectName: item.projectName,
        workContent: item.workContent,
        plannedStartTime: item.stareDate,
        plannedEndTime: item.endDate,
        riskLevel: item.riskLevel,
    }))

    const result = await addMonthlyPlanAPI(paramsList)
    if (result.code === 200) {
        proxy.$modal.msgSuccess('保存成功')
        dialogConfig.outerVisible = false
        comTableRef.value?.refresh()
    }
}

// 关闭弹框统一处理
const onCloseDialogOuter = (visible) => {
    dialogConfig.outerVisible = visible
}

// 导出人员安排表
const onExportPersonArrange = (queryParams) => {
    console.log('queryParams', queryParams)
    proxy.download(
        '/monthlyPlan/export',
        {
            ...queryParams,
        },
        `人员安排表.xlsx`,
    )
}

// 导出整体汇总表
const onExportOverallSummary = (queryParams) => {
    proxy.download(
        '/monthlyPlan/exportResourceSummary',
        {
            ...queryParams,
        },
        `整体汇总表.xlsx`,
    )
}

// 导出工作量汇总表
const onExportWorkloadSummary = (queryParams) => {
    proxy.download(
        '/monthlyPlan/exportWorkloadSummary',
        {
            ...queryParams,
        },
        `工作量汇总表.xlsx`,
    )
}
</script>

<style scoped></style>
