<template>
    <div class="app-container">
        <el-card class="top-radio">
            <el-radio-group v-model="tableType">
                <el-radio-button label="运行" value="0" />
                <el-radio-button label="检修" value="1" />
                <el-radio-button label="项目部" value="2" />
            </el-radio-group>

            <ComButton
                type="info"
                plain
                icon="Download"
                @click="onDownloadStatistic"
                v-hasPermi="['plan:dailyPlan:downloadStatistic']"
            >
                下载统计表
            </ComButton>
        </el-card>
        <!-- 日计划填报管理列表 -->
        <ComTable
            ref="comTableRef"
            :key="tableType"
            :show-toolbar="true"
            :show-action="true"
            :form-columns="formColumns"
            :load-data="listDailyPlanAPI"
            :table-columns="initTableColumns"
            :action-columns="actionColumns"
            :defaultQueryParams="{ dayPlanType: tableType }"
        >
            <template #proposedLongTimeCar="{ row }">
                <span v-if="row.proposedLongTimeCar && row.proposedTemporaryCar">
                    长租车{{ row.proposedLongTimeCar }}辆
                    <br />
                    临租车{{ row.proposedTemporaryCar }}辆
                </span>
            </template>
            <template #actualLongTimeCar="{ row }">
                <span v-if="row.actualLongTimeCar && row.actualTemporaryCar">
                    长租车{{ row.actualLongTimeCar }}辆
                    <br />
                    临租车{{ row.actualTemporaryCar }}辆
                </span>
            </template>
            <template #toolbar>
                <ComButton
                    type="primary"
                    icon="Plus"
                    @click="onHandleAdd"
                    v-hasPermi="['plan:dailyPlan:add']"
                >
                    新增日计划
                </ComButton>
                <ComButton
                    plain
                    type="info"
                    icon="Download"
                    @click="onDownloadWorkloadSummary"
                    v-if="['0'].includes(tableType)"
                    v-hasPermi="['plan:dailyPlan:downloadWorkloadSummary']"
                >
                    下载工作量统计表
                </ComButton>
            </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, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { listDailyPlanAPI, delDailyPlanAPI, addDailyPlanAPI } from '@/api/planMange/dailyPlan.js'
import useDictStore from '@/store/modules/dict'
import { selectDictLabel } from '@/utils/ruoyi'
import dayjs from 'dayjs'
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'

const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()
const dictStore = useDictStore()

const {
    tableColumns: baseTableColumns,
    tableColumns_1,
    tableColumns_2,
    dialogConfig,
    buildFormColumns,
} = config

const comTableRef = ref(null)
const addFormRef = ref(null)
const tableType = ref(route.query.dayPlanType || '0')

onMounted(() => {
    if (route.query.dayPlanType) {
        tableType.value = route.query.dayPlanType
    }
})

// 加载字典数据，确保字典数据在表格渲染前已经加载
const { plan_risk_level } = proxy.useDict('plan_risk_level')

// 搜索表单配置（当前月计划场景暂不依赖下拉接口，直接使用静态配置）
const formColumns = computed(() => buildFormColumns())

// 创建动态 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) || value
    }
}

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

// 处理 tableColumns_2，根据 tableType 区分实际完成工作内容的显示方式
const processedTableColumns_2 = computed(() => {
    return tableColumns_2.map((column) => {
        // 实际完成工作内容字段需要根据类型区分
        if (column.label === '实际完成工作内容') {
            return {
                ...column,
                formatter: (row) => {
                    // 检修类型（type === '1'）：使用 actualWorkloadList 遍历
                    if (tableType.value === '1') {
                        return (
                            row.workloadList?.map((item) => item.workloadCategoryName).join(',') ||
                            ''
                        )
                    }
                    // 项目部类型（type === '2'）：使用 actualWorkContent 直接显示
                    if (tableType.value === '2') {
                        return row.actualWorkContent || ''
                    }
                    return ''
                },
            }
        }
        return column
    })
})

const initTableColumns = computed(() => {
    if (tableType.value === '0') return [...tableColumns.value, ...tableColumns_1]
    if (tableType.value !== '0') return [...tableColumns.value, ...processedTableColumns_2.value]
})

// 判断日期是否为今天之前
const isBeforeToday = (dayPlan) => {
    if (!dayPlan) return false
    const planDate = dayjs(dayPlan)
    const today = dayjs().startOf('day')
    return planDate.isBefore(today)
}

// 操作列
const actionColumns = computed(() => [
    {
        label: '详情',
        type: 'primary',
        link: true,
        permission: ['plan:dailyPlan:detail'], // 权限控制：使用 v-hasPermi 指令控制按钮显示
        handler: (row) => {
            router.push({
                path: '/plan/dailyPlanEdit/index',
                query: {
                    id: row.planId || row.dayPlanId,
                    mode: 'detail',
                    dayPlanType: tableType.value,
                    inspectionStationName: row.inspectionStationName,
                    projectName: row.projectName,
                    planMajorName: row.planMajorName,
                    dayPlan: row.dayPlan,
                },
            })
        },
    },
    {
        label: '编辑',
        type: 'primary',
        link: true,
        permission: ['plan:dailyPlan:edit'], // 权限控制：使用 v-hasPermi 指令控制按钮显示
        disabled: (row) => isBeforeToday(row.dayPlan), // 当日期为今天之前时禁用
        handler: (row) => {
            router.push({
                path: '/plan/dailyPlanEdit/index',
                query: {
                    id: row.planId || row.dayPlanId,
                    mode: 'edit',
                    dayPlanType: tableType.value,
                    inspectionStationName: row.inspectionStationName,
                    projectName: row.projectName,
                    planMajorName: row.planMajorName,
                    dayPlan: row.dayPlan,
                },
            })
        },
    },
    {
        label: '删除',
        type: 'danger',
        link: true,
        permission: ['plan:dailyPlan:remove'], // 权限控制：使用 v-hasPermi 指令控制按钮显示
        disabled: (row) => isBeforeToday(row.dayPlan), // 当日期为今天之前时禁用
        handler: (row) => {
            proxy.$modal.confirm('是否确认删除该日计划？').then(async () => {
                const result = await delDailyPlanAPI({ dayPlanId: row.dayPlanId })
                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) => ({
        dayPlan: addFormRef.value.getCurrentDate(),
        monthlyPlanId: item.monthlyPlanId,
        dayPlanType: tableType.value,
        riskLevel: item.riskLevel,
    }))

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

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

// 编辑调试
const onHandleEdit = () => {
    router.push({
        path: '/plan/dailyPlanEdit/index',
        query: {
            mode: 'edit',
            dayPlanType: tableType.value,
        },
    })
}

// 下载统计表
const onDownloadStatistic = () => {
    proxy.download(
        '/download/dayPlanStatistics',
        {
            dayPlanType: tableType.value,
            startDate: dayjs().startOf('month').format('YYYY-MM-DD'),
            endDate: dayjs().endOf('month').format('YYYY-MM-DD'),
        },
        `日计划统计表.xlsx`,
    )
}

// 下载工作量统计表
const onDownloadWorkloadSummary = () => {
    proxy.download(
        '/monthlyPlan/exportWorkloadSummary',
        {
            dayPlanType: tableType.value,
        },
        `${tableType.value === '1' ? '检修' : '项目部'}统计表.xlsx`,
    )
}
</script>

<style scoped lang="scss">
.top-radio {
    margin-bottom: 10px;
    :deep(.el-card__body) {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 10px 20px !important;
    }
}
</style>
