<template>
    <!-- 用a-card包裹Tabs和搜索栏，形成统一白色区域 -->
    <a-card class="tab-search-container" :bordered="false">
        <a-tabs v-model:activeKey="activeTabKey" @change="handleTabChange" style="margin-bottom: 16px;">
            <a-tab-pane key="all" tab="全部" />
            <a-tab-pane key="initialization" tab="初始化" />
            <a-tab-pane key="pendingCheckin" tab="待签入" />
            <a-tab-pane key="completed" tab="已结单" />
            <a-tab-pane key="cancelled" tab="已作废" />
            <a-tab-pane key="expiredUncheckedIn" tab="过期未签入" />
            <a-tab-pane key="expiredUncheckedOut" tab="过期未签出" />
        </a-tabs>

        <x-search-bar class="mb-4">
            <template #default="{ gutter, colSpan }">
                <a-form  :model="searchFormData" layout="inline">
                    <!-- 基础查询字段 -->
                    <a-row :gutter="gutter">
                        <a-col v-bind="colSpan">
                            <a-form-item label="姓名" name="name">
                                <a-input v-model:value="searchFormData.name" placeholder="请输入姓名" />
                            </a-form-item>
                        </a-col>

                        <a-col v-bind="colSpan">
                            <a-form-item name="code">
                                <template #label>
                                    身份证号
                                    <a-tooltip title="身份证号">
                                        <question-circle-outlined class="ml-4-1 color-placeholder" />
                                    </a-tooltip>
                                </template>
                                <a-input v-model:value="searchFormData.code" placeholder="请输入身份证号" />
                            </a-form-item>
                        </a-col>

                        <a-col v-bind="colSpan">
                            <a-form-item label="实际服务日期" name="actualServiceTime">
                                <a-range-picker v-model:value="searchFormData.actualServiceTime" />
                            </a-form-item>
                        </a-col>
                    </a-row>

                    <!-- 高级查询折叠面板 -->
                    <a-collapse v-model:activeKey="advancedSearchVisible" ghost >
                        <a-collapse-panel key="1" :showArrow="false" style="padding: 0; border: none;">
                            <template #header></template>
                            <a-row :gutter="gutter" style="margin-top: -20px;">
                                <a-col v-bind="colSpan">
                                    <a-form-item label="工单号" name="workOrderNo">
                                        <a-input v-model:value="searchFormData.workOrderNo" placeholder="请输入工单号" />
                                    </a-form-item>
                                </a-col>

                                <a-col v-bind="colSpan">
                                    <a-form-item label="所在区域" name="area">
                                        <AreaCascader v-model:value="searchFormData.currentNode"
                                            @change="onAreaChange" />
                                    </a-form-item>
                                </a-col>

                                <a-col v-bind="colSpan">
                                    <a-form-item label="所在站点" name="stationId">
                                        <ServiceStation v-model:value="searchFormData.stationId" />
                                    </a-form-item>
                                </a-col>

                                <a-col v-bind="colSpan">
                                    <a-form-item label="服务项目" name="serviceProject">
                                        <a-input v-model:value="searchFormData.serviceProject" placeholder="请输入服务项目" />
                                    </a-form-item>
                                </a-col>

                                <a-col v-bind="colSpan">
                                    <a-form-item label="服务人员" name="staff">
                                        <a-select v-model:value="searchFormData.staff" placeholder="请选择服务人员">
                                            <a-select-option value="staff1">张三</a-select-option>
                                            <a-select-option value="staff2">李四</a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>

                                <a-col v-bind="colSpan">
                                    <a-form-item label="计划日期" name="plannedDate">
                                        <a-range-picker v-model:value="searchFormData.plannedDate" />
                                    </a-form-item>
                                </a-col>

                                <a-col v-bind="colSpan">
                                    <a-form-item label="服务项目编号" name="projectCode">
                                        <a-select v-model:value="searchFormData.projectCode" placeholder="请选择项目编号">
                                            <a-select-option value="P001">P001</a-select-option>
                                            <a-select-option value="P002">P002</a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>

                                <a-col v-bind="colSpan">
                                    <a-form-item label="服务对象分类" name="clientCategory">
                                        <a-select v-model:value="searchFormData.clientCategory" placeholder="请选择分类">
                                            <a-select-option value="elderly">老年人</a-select-option>
                                            <a-select-option value="disabled">残障人士</a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>
                            </a-row>
                        </a-collapse-panel>
                    </a-collapse>

                    <!-- 操作按钮 -->
                    <a-row :gutter="gutter">
                        <a-col :span="24" style="text-align: right;">
                            <a-space>
                                <a-button @click="handleResetSearch">{{ $t('button.reset') }}</a-button>

                                <a-button ghost type="primary" @click="handleSearch">
                                    {{ $t('button.search') }}
                                </a-button>
                                <a-button type="link" @click="toggleAdvancedSearch"
                                    style="color: #1890ff; border: none; padding: 0; font-size: 14px;">
                                    {{ advancedSearchVisible.length ? '收起' : '高级查询' }}
                                    <template #icon>
                                        <down-outlined v-if="advancedSearchVisible.length" />
                                        <up-outlined v-else />
                                    </template>
                                </a-button>
                            </a-space>
                        </a-col>
                    </a-row>
                </a-form>
            </template>
        </x-search-bar>
    </a-card>

    <!-- 表格区域 -->
    <a-card style="margin-top: 16px;">
        <x-action-bar class="mb-8-2">
            <a-button v-action="'add'" type="primary" @click="$refs.editDialogRef.handleCreate()"
                style="margin-right: 20px;">
                <template #icon>
                    <!-- <plus-outlined /> -->
                </template>
                {{ '导出' }}
            </a-button>

            <a-button v-action="'add'" type="primary" @click="$refs.editDialogRef.handleCreate()">
                <template #icon>
                    <!-- <plus-outlined /> -->
                </template>
                {{ '导出记录' }}
            </a-button>
        </x-action-bar>

        <a-table rowKey="id" :loading="loading" :pagination="true" :columns="currentColumns" :data-source="listData"
            :scroll="{ x: 'max-content' }">
            <!-- 表格列渲染逻辑保持不变 -->
            <template #bodyCell="{ column, record }">
                <template v-if="'menuType' === column.key">
                    <a-tag v-if="menuTypeEnum.is('page', record.type)" color="processing">
                        {{ menuTypeEnum.getDesc(record.type) }}
                    </a-tag>
                    <a-tag v-if="menuTypeEnum.is('button', record.type)" color="success">
                        {{ menuTypeEnum.getDesc(record.type) }}
                    </a-tag>
                </template>

                <template v-if="'createAt' === column.key">
                    {{ formatUtcDateTime(record.created_at) }}
                </template>

                <template v-if="'statusType' === column.key">
                    <a-tag v-if="statusTypeEnum.is('enabled', record.status)" color="processing">
                        {{ statusTypeEnum.getDesc(record.status) }}
                    </a-tag>
                    <a-tag v-if="statusTypeEnum.is('disabled', record.status)" color="default">
                        {{ statusTypeEnum.getDesc(record.status) }}
                    </a-tag>
                </template>

                <template v-if="'action' === column.key">
                    <template v-if="['all', 'initialization', 'pendingCheckin'].includes(activeTabKey)">
                        <x-action-button @click="$refs.cancelDialogRef.showCancelModal(record)">
                            <a-tooltip><template #title>
                                    {{ '作废' }}</template>作废
                            </a-tooltip>
                        </x-action-button>
                    </template>

                    <template v-if="['all', 'initialization'].includes(activeTabKey)">
                        <x-action-button @click="$refs.editDialogRef.showEditModal(record)">
                            <a-tooltip><template #title>编辑</template>编辑</a-tooltip>
                        </x-action-button>
                    </template>

                    <template v-if="['all', 'completed', 'cancelled'].includes(activeTabKey)">
                        <x-action-button @click="$refs.viewDialogRef.handleView(record)">
                            <a-tooltip><template #title>详情</template>详情</a-tooltip>
                        </x-action-button>
                    </template>

                    <template v-if="['all', 'expiredUncheckedIn', 'expiredUncheckedOut'].includes(activeTabKey)">
                        <x-action-button @click="$refs.checkDialogRef.showCheckModal(record)">
                            <a-tooltip><template #title>待签入</template>待签入</a-tooltip>
                        </x-action-button>
                    </template>
                </template>
            </template>
        </a-table>
    </a-card>

    <edit-dialog @ok="onOk" ref="editDialogRef" />
    <CancelWorkOrder @ok="onOk" ref="cancelDialogRef" />
    <view-dialog @ok="onOk" ref="viewDialogRef" />
    <check-dialog @ok="onOk" ref="checkDialogRef" />

    <!-- 作废确认模态   框 -->
    <!-- <a-modal 
      v-model:open="cancelModalVisible" 
      title="作废确认" 
      @ok="confirmCancel"
      @cancel="cancelModalVisible = false"
    >
      <p>确定要作废该工单吗？此操作不可撤销。</p>
      <a-textarea 
        v-model:value="cancelReason" 
        placeholder="请输入作废原因（可选）" 
        :rows="4"
      />
    </a-modal> -->
</template>

<script setup>
import { DownOutlined, UpOutlined, QuestionCircleOutlined } from '@ant-design/icons-vue'
import { Modal, message } from 'ant-design-vue'
import { ref, computed } from 'vue'
import apis from '@/apis'
import { config } from '@/config'
import { menuTypeEnum, statusTypeEnum } from '@/enums/system'
import { usePagination, useForm } from '@/hooks'
import { formatUtcDateTime } from '@/utils/util'
import EditDialog from './components/EditDialog.vue'
import CancelWorkOrder from './components/InvalidatedDialog.vue'
import ViewDialog from './components/ViewDialog.vue'
import CheckDialog from './components/CheckDialog.vue'
import { useI18n } from 'vue-i18n'
import storage from '@/utils/storage'
import AreaCascader from '@/components/AreaCascader/index.vue'
import dayjs from 'dayjs'
import ServiceStation from '@/components/ServiceStation/index.vue'
defineOptions({
    name: 'menu',
})

const { t } = useI18n()
const activeTabKey = ref('all') // 默认选中"全部"标签页

// 作废相关状态
const cancelModalVisible = ref(false)
const cancelRecord = ref(null)
const cancelReason = ref('')

// 不同标签页对应的表格列配置
const columnConfigs = ref({
    all: [

        // { title: '工单号', dataIndex: 'orderNum', key: 'orderNum', fixed: true, width: 280 },
        { title: '服务对象', dataIndex: 'customerName', key: 'customerName', width: 140 },
        { title: '服务对象身份证', dataIndex: 'customerIdCard', key: 'customerIdCard', width: 240 },
        {
            title: '服务对象分类', dataIndex: 'labels', key: 'labels', width: 140,
            render: (labels) => Array.isArray(labels) ? labels.join(', ') : ''
        },
        { title: '服务人员', dataIndex: 'serviceName', key: 'serviceName', width: 140 },
        {
            title: '计划日期',
            dataIndex: 'plannedStartDate',
            key: 'plannedStartDate',
            width: 240,
            customRender: ({ text, record }) => {
                if (!text) return '';
                try {
                    // 确保 dayjs 已导入
                    const formatted = dayjs(text).format('YYYY-MM-DD HH:mm:ss');
                    return formatted;
                } catch (e) {
                    console.error('日期格式化失败:', text, e);
                    return text; // 或 return '无效日期'
                }
            }
        },
        {
            title: '服务项目分类',
            // 假设取 projects[0].categoryType，可根据实际字段调整
            render: (_, record) => record.projects?.[0]?.categoryType || record.projects?.[0]?.categoryMethod || '',
            key: 'serviceCategory',
            width: 240
        },
        {
            title: '服务项目',
            render: (_, record) => record.projects?.[0]?.name || '',
            key: 'serviceNameProject',
            width: 240
        },
        {
            title: '服务费用',
            render: (_, record) => record.projects?.[0]?.price ?? 0,
            key: 'servicePrice',
            width: 140
        },
        {
            title: '实际支付费用',
            // 若无单独字段，可先与服务费用一致；后续可替换为 actualPaid 等字段
            render: (_, record) => record.projects?.[0]?.price ?? 0,
            key: 'actualPaid',
            width: 140
        },
        {
            title: '计划服务时间（分钟）',

            dataIndex: 'workDuration',
            key: 'workDuration',
            width: 240
        },
        { title: '服务状态', dataIndex: 'status', key: 'status', width: 180 },
        { title: '操作', key: 'action', width: 440, fixed: 'right' }

    ],
    initialization: [
        { title: '工单号', dataIndex: 'name', key: 'name', fixed: true, width: 280 },
        { title: '服务对象', dataIndex: 'code', key: 'code', width: 240 },
        { title: '服务项目', dataIndex: 'project', key: 'project', width: 240 },
        { title: '计划服务时间', dataIndex: 'scheduledTime', key: 'scheduledTime', width: 240 },
        { title: '服务组织', dataIndex: 'organization', key: 'organization', width: 240 },
        { title: '操作', key: 'action', width: 240, fixed: 'right' }
    ],
    pendingCheckin: [
        { title: '工单号', dataIndex: 'name', key: 'name', fixed: true, width: 280 },
        { title: '服务对象', dataIndex: 'code', key: 'code', width: 240 },
        { title: '服务地址', dataIndex: 'address', key: 'address', width: 300 },
        { title: '计划服务时间', dataIndex: 'scheduledTime', key: 'scheduledTime', width: 240 },
        { title: '服务人员', dataIndex: 'staff', key: 'staff', width: 240 },
        { title: '操作', key: 'action', width: 240, fixed: 'right' }
    ],
    completed: [
        { title: '工单号', dataIndex: 'name', key: 'name', fixed: true, width: 280 },
        { title: '服务对象', dataIndex: 'code', key: 'code', width: 240 },
        { title: '服务项目', dataIndex: 'project', key: 'project', width: 240 },
        { title: '实际服务时间', dataIndex: 'actualTime', key: 'actualTime', width: 240 },
        { title: '服务人员', dataIndex: 'staff', key: 'staff', width: 240 },
        { title: '操作', key: 'action', width: 240, fixed: 'right' }
    ],
    cancelled: [
        { title: '工单号', dataIndex: 'name', key: 'name', fixed: true, width: 280 },
        { title: '服务对象', dataIndex: 'code', key: 'code', width: 240 },
        { title: '作废原因', dataIndex: 'cancelReason', key: 'cancelReason', width: 300 },
        { title: '作废时间', dataIndex: 'cancelTime', key: 'cancelTime', width: 240 },
        { title: '操作人', dataIndex: 'operator', key: 'operator', width: 240 },
        { title: '操作', key: 'action', width: 240, fixed: 'right' }
    ],
    expiredUncheckedIn: [
        { title: '工单号', dataIndex: 'name', key: 'name', fixed: true, width: 280 },
        { title: '服务对象', dataIndex: 'code', key: 'code', width: 240 },
        { title: '计划服务时间', dataIndex: 'scheduledTime', key: 'scheduledTime', width: 240 },
        { title: '逾期天数', dataIndex: 'overdueDays', key: 'overdueDays', width: 180 },
        { title: '服务人员', dataIndex: 'staff', key: 'staff', width: 240 },
        { title: '操作', key: 'action', width: 240, fixed: 'right' }
    ],
    expiredUncheckedOut: [
        { title: '工单号', dataIndex: 'name', key: 'name', fixed: true, width: 280 },
        { title: '服务对象', dataIndex: 'code', key: 'code', width: 240 },
        { title: '签入时间', dataIndex: 'checkinTime', key: 'checkinTime', width: 240 },
        { title: '逾期天数', dataIndex: 'overdueDays', key: 'overdueDays', width: 180 },
        { title: '服务人员', dataIndex: 'staff', key: 'staff', width: 240 },
        { title: '操作', key: 'action', width: 240, fixed: 'right' }
    ]
})

// 根据当前选中的标签页获取对应的表格列
const currentColumns = computed(() => {
    return columnConfigs.value[activeTabKey.value] || columnConfigs.value.all
})

const { listData, loading, showLoading, hideLoading, searchFormData, paginationState, resetPagination } =
    usePagination()
const { resetForm } = useForm()
const editDialogRef = ref()
const viewDialogRef = ref()
const checkDialogRef = ref()
// 控制高级查询面板是否展开
const advancedSearchVisible = ref([]) // 默认收起
const tabKeyToStatusMap = {
    all: undefined, // 全部不传 status
    initialization: 'Initialize',
    pendingCheckin: 'Pending_Check-in',
    completed: 'Closed',
    cancelled: 'Cancelled',
    expiredUncheckedIn: 'Overdue_Unchecked-in',
    expiredUncheckedOut: 'Overdue_Unchecked-out'
}

// 初始加载数据
getMenuList()

/**
 * 获取菜单列表
 * @return {Promise<void>}
 */
async function getMenuList() {
    try {
        showLoading()
        const { pageSize, current } = paginationState

        // 获取当前 tab 对应的 status
        const status = tabKeyToStatusMap[activeTabKey.value]

        const params = {
            pageSize,
            current,
            ...searchFormData.value
        }

        // 只有 status 不为 undefined 时才加入参数
        if (status !== undefined) {
            params.status = status
        }

        console.log("=====search params", params)

        const { success, data, total } = await apis.workOrder.getWorkOrderList(params)

        if (config('http.code.success') === success) {
            listData.value = data
            paginationState.total = total
        }
    } catch (error) {
        console.error('获取工单列表失败:', error)
        message.error('获取数据失败')
    } finally {
        hideLoading()
    }
}

/**
 * 标签页切换事件
 */


function handleTabChange(key) {
    // 全部不用传 
    // 初始化  Initialize
    // 待签入 Pending_Check-in
    // 待签出 Pending_Check-out
    // 已结单 Closed
    // 已作废 Cancelled
    // 过期未签入 Overdue_Unchecked-in
    // 过期未签出  Overdue_Unchecked-out
    console.log('active tab key:', key)
    activeTabKey.value = key
    resetPagination()
    getMenuList() // 切换标签页时重新加载数据
}

/**
 * 搜索
 */
function handleSearch() {
    resetPagination()
    getMenuList()
}

/**
 * 重置
 */
function handleResetSearch() {
    searchFormData.value = {}
    resetPagination()
    getMenuList()
}

/**
 * 显示作废确认模态框
 */
function showCancelModal(record) {
    cancelRecord.value = record
    cancelReason.value = ''
    cancelModalVisible.value = true
}

/**
 * 确认作废操作
 */
async function confirmCancel() {
    if (!cancelRecord.value) return

    try {
        const { success } = await apis.menu.cancelMenu({
            id: cancelRecord.value.id,
            reason: cancelReason.value
        }).catch(() => {
            throw new Error()
        })

        if (config('http.code.success') === success) {
            message.success('工单已作废')
            cancelModalVisible.value = false
            await getMenuList()
        }
    } catch (error) {
        message.error('作废失败')
    }
}

/**
 * 查看详情
 * @param record
 */
function handleDetail(record) {
    console.log('查看详情:', record)
    // 实现详情查看逻辑
}

/**
 * 续期操作（针对过期工单）
 * @param record
 */
function handleRenew(record) {
    Modal.confirm({
        title: t('pages.system.renewConfirm'),
        content: t('pages.system.renewTip'),
        okText: t('button.confirm'),
        cancelText: t('button.cancel'),
        onOk: async () => {
            try {
                const { success } = await apis.menu.renewMenu(record.id)
                if (config('http.code.success') === success) {
                    message.success(t('component.message.success.renew'))
                    await getMenuList()
                }
            } catch (error) {
                message.error(t('component.message.error.renew'))
            }
        }
    })
}

/**
 * 编辑完成
 */
async function onOk() {
    await getMenuList()
}

// 选择器变更事件
function handleChange(value) {
    console.log('Selected value:', value)
}

// 区域变更事件
function onAreaChange(value) {
    console.log('Area changed:', value)
}

// 切换高级查询
function toggleAdvancedSearch() {
    advancedSearchVisible.value = advancedSearchVisible.value.length ? [] : ['1']
}
</script>

<style lang="less" scoped>
.tab-search-container {
    background: #fff; // 白色背景
    padding: 16px; // 内边距
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); // 可选：添加轻微阴影增强层次
    margin-bottom: 16px; // 与下方表格区域保持间距
}

// 在 style 中添加
.ant-btn-link:hover {
    color: #0050b3;
    text-decoration: underline;
}
</style>
