<template>
    <x-search-bar class="mb-4">
        <template #default="{ gutter, colSpan }">
            <a-form :label-col="{ style: { width: '130px' } }" :model="searchFormData">
                <!-- 基础查询字段 -->
                <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 label="身份证号" name="idCard">
                            <a-input v-model:value="searchFormData.idCard" placeholder="请输入身份证号" />
                        </a-form-item>
                    </a-col>

                    <a-col v-bind="colSpan">
                        <a-form-item label="异常类型" name="exceptionType">
                            <a-select v-model:value="searchFormData.exceptionType" placeholder="请选择异常类型">
                                <a-select-option value="type1">类型1</a-select-option>
                                <a-select-option value="type2">类型2</a-select-option>
                            </a-select>
                        </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="plannedDate">
                                    <a-range-picker v-model:value="searchFormData.plannedDate" />
                                </a-form-item>
                            </a-col>

                            <a-col v-bind="colSpan">
                                <a-form-item label="实际服务(小时)" name="serviceDuration" style="white-space: nowrap;">
                                    <a-input-number v-model:value="searchFormData.serviceDuration" :min="0"
                                        placeholder="请输入时长" style="width: 100%" />
                                </a-form-item>
                            </a-col>

                            <a-col v-bind="colSpan">
                                <a-form-item label="工单号" name="serviceOrderNo">
                                    <a-input v-model:value="searchFormData.serviceOrderNo" placeholder="请输入工单号" />
                                </a-form-item>
                            </a-col>

                            <a-col v-bind="colSpan">
                                <a-form-item label="所属服务组织" name="serviceOrg">
                                    <a-select v-model:value="searchFormData.serviceOrg" placeholder="请选择服务组织">
                                        <a-select-option value="org1">组织1</a-select-option>
                                        <a-select-option value="org2">组织2</a-select-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>

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

                            <a-col v-bind="colSpan">
                                <a-form-item label="服务满意度" name="satisfaction">
                                    <a-select v-model:value="searchFormData.satisfaction" placeholder="请选择满意度">
                                        <a-select-option value="5">非常满意</a-select-option>
                                        <a-select-option value="4">满意</a-select-option>
                                        <a-select-option value="3">一般</a-select-option>
                                        <a-select-option value="2">不满意</a-select-option>
                                        <a-select-option value="1">非常不满意</a-select-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>

                            <a-col v-bind="colSpan">
                                <a-form-item label="服务人员满意度" name="staffSatisfaction">
                                    <a-select v-model:value="searchFormData.staffSatisfaction" placeholder="请选择满意度">
                                        <a-select-option value="5">非常满意</a-select-option>
                                        <a-select-option value="4">满意</a-select-option>
                                        <a-select-option value="3">一般</a-select-option>
                                        <a-select-option value="2">不满意</a-select-option>
                                        <a-select-option value="1">非常不满意</a-select-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>

                            <a-col v-bind="colSpan">
                                <a-form-item label="是否回访" name="isVisited">
                                    <a-select v-model:value="searchFormData.isVisited" placeholder="请选择">
                                        <a-select-option :value="true">是</a-select-option>
                                        <a-select-option :value="false">否</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-row :gutter="8" :wrap="false" style="margin-top: 20px;">
        <a-col flex="auto">
            <a-card title="回访列表">
                <div style="margin-bottom: 20px;">
                    <a-space>
                        <a-button type="primary">导入</a-button>
                        <a-button type="primary">导入记录</a-button>
                        <a-button type="primary">导出</a-button>
                        <a-button type="primary">导出记录</a-button>
                    </a-space>
                </div>
                <a-table rowKey="id" :loading="loading" :pagination="true" :columns="columns" :data-source="listData"
                    :scroll="{ x: 'max-content' }">

                    <template #bodyCell="{ column, record, index }">
                        <template v-if="column.key === 'serialNumber'">
                            <span>{{ index + 1 }}</span>
                        </template>

                        <template v-else-if="column.dataIndex === 'otherPhone1'">
                            <span>{{ record.otherPhone1 || record.otherPhone2 || '—' }}</span>
                        </template>

                        <template v-else-if="column.dataIndex === 'plannedServiceStartDate'">
                            <span>{{ formatDate(record.plannedServiceStartDate) }}</span>
                        </template>

                        <template v-else-if="column.key === 'action'">
                            <x-action-button @click="$refs.editDialogRef.handleView(record)">
                                <span>详情</span>
                            </x-action-button>
                            <x-action-button @click="handleVisit(record)">
                                回访
                            </x-action-button>
                        </template>
                    </template>
                </a-table>
            </a-card>
        </a-col>
    </a-row>

    <edit-dialog @ok="onOk" ref="editDialogRef" />
    <!-- 新增回访弹框 -->
    <visit-dialog @ok="onVisitOk" ref="visitDialogRef" />
</template>

<script setup>
import { DownOutlined, UpOutlined } from '@ant-design/icons-vue'
import AreaCascader from '@/components/AreaCascader/index.vue'
import { message, Modal } from 'ant-design-vue'
import { ref } from 'vue'
import apis from '@/apis'
import { config } from '@/config'
import { usePagination } from '@/hooks'
import { useI18n } from 'vue-i18n'
import { useDicsStore } from '@/store'
import EditDialog from './components/EditDialog.vue'
// 引入回访弹框组件
import VisitDialog from './components/VisitDialog.vue'
import dayjs from 'dayjs'

defineOptions({
    name: 'allocation',
})

const dicsStore = useDicsStore()
const { t } = useI18n()

// 表格列
const columns = [
    { title: '订单号', dataIndex: 'orderNum', key: 'orderNum', align: 'center', width: 80 },
    { title: '服务对象姓名', dataIndex: 'customerName', key: 'customerName', align: 'center', width: 100 },
    { title: '电话', dataIndex: 'contact1', key: 'contact1', align: 'center', width: 120 },
    { title: '电话1', dataIndex: 'otherPhone1', key: 'otherPhone1', align: 'center', width: 120 },
    { title: '电话2', dataIndex: 'otherPhone2', key: 'otherPhone2', align: 'center', width: 120 },
    { title: '身份证号', dataIndex: 'customerIdCard', key: 'customerIdCard', align: 'center', width: 240 },
    { title: '地址', dataIndex: 'detailAddress', key: 'detailAddress', align: 'center', width: 240 },
    { title: '服务人员姓名', dataIndex: 'serviceName', key: 'serviceName', align: 'center', width: 120 },
    { title: '服务项目名称', dataIndex: 'workType', key: 'workType', align: 'center', width: 120 },
    { title: '计划服务开始时间', dataIndex: 'plannedServiceStartDate', key: 'plannedServiceStartDate', align: 'center', width: 100 },
    { title: '状态', dataIndex: 'status', key: 'status', align: 'center', width: 150 },
    { title: '操作', key: 'action', width: 140, fixed: 'right' }
]
// 分页与搜索数据
const {
    listData,
    loading,
    paginationState,
    resetPagination,
    searchFormData,
} = usePagination()

// 初始化 searchFormData 结构（重要！）
searchFormData.value = {
    name: '',
    idCard: '',
    exceptionType: undefined,
    serviceOrderNo: '',
    serviceOrg: undefined,
    satisfaction: undefined,
    staffSatisfaction: undefined,
    isVisited: undefined,
    plannedDate: [],
    serviceDuration: undefined,
    currentNode: [],
}

const editDialogRef = ref()
const detailRef = ref()
const advancedSearchVisible = ref([]) // 高级查询默认收起
// 回访弹框引用
const visitDialogRef = ref()
// 计算所有列宽度总和
const totalWidth = columns.reduce((sum, col) => sum + (col.width || 100), 0);

// 获取列表（mock 数据）
async function getPageList() {
    loading.value = true
    try {
        const { pageSize, current } = paginationState
        const params = {
            pageSize,
            current,
            ...searchFormData.value,
        }
        if (Array.isArray(params.plannedDate) && params.plannedDate.length === 0) {
            delete params.plannedDate
        }
        const { success, data, total } = await apis.workOrder.getBackWorkOrderList(params)
        listData.value = data
        paginationState.total = total
    } catch (error) {
        console.error('获取列表失败:', error)
        message.error('加载数据失败')
    } finally {
        loading.value = false
    }
}

// 搜索
function handleSearch() {
    resetPagination()
    getPageList()
}

// 重置
function handleResetSearch() {
    searchFormData.value = {
        name: '',
        idCard: '',
        exceptionType: undefined,
        serviceOrderNo: '',
        serviceOrg: undefined,
        satisfaction: undefined,
        staffSatisfaction: undefined,
        isVisited: undefined,
        plannedDate: [],
        serviceDuration: undefined,
        currentNode: [],
    }
    resetPagination()
    getPageList()
}

// 分页变化
function onTableChange(pagination) {
    paginationState.current = pagination.current
    paginationState.pageSize = pagination.pageSize
    getPageList()
}

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

// 区域选择回调
function onAreaChange(value) {
    console.log('区域变更:', value)
}

// 操作：详情
function handleDetail(record) {
    console.log('查看详情:', record)
    message.info(`查看【${record.name}】的详情`)
    // 示例：打开详情弹窗
    // detailRef.value?.open(record)
}


// 操作：回访（点击行内“回访”按钮时触发）
function handleVisit(record) {
    visitDialogRef.value.handleOpen(record) // 打开回访弹框
}

// 回访提交成功后的回调
function onVisitOk(formData) {
    console.log('回访表单数据:', formData)
    message.success('回访提交成功')
    getPageList() // 重新获取列表，更新状态
}

// 页面初始化
getPageList()
</script>

<style lang="less" scoped></style>