<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">
                            <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" style="margin-top: 16px;">
                    <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="paginationState" :columns="columns"
                    :data-source="listData" :scroll="{ x: totalWidth }" @change="onTableChange">
                    <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'">
                            <!-- 只保留派单按钮 -->
                            <a-button type="link" @click="openDispatchDrawer(record)">派单</a-button>
                        </template>
                    </template>
                </a-table>
            </a-card>
        </a-col>
    </a-row>

    <!-- 派单抽屉（右侧弹出） -->
    <DispatchDrawer 
        :open="showDrawer" 
        :assignees="staffList" 
        :initial-values="drawerInitialValues"
        @close="handleDrawerClose" 
        @submit="handleDispatchSubmit" />
</template>

<script setup>
import { DownOutlined, UpOutlined } from '@ant-design/icons-vue'
import AreaCascader from '@/components/AreaCascader/index.vue'
import { message } from 'ant-design-vue'
import { ref, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import DispatchDrawer from './components/DispatchDrawer.vue';
import apis from '@/apis'
import { usePagination } from '@/hooks'
import storage from '@/utils/storage'

defineOptions({
    name: 'allocation',
})

const { t } = useI18n()
const { listData, loading, showLoading, hideLoading, paginationState, resetPagination, searchFormData } = usePagination()

// 表格列
const columns = [
    { title: '序号', key: 'serialNumber', align: 'center', width: 60 },
    { title: '工单号', dataIndex: 'orderNum', key: 'orderNum', align: 'center', width: 120 },
    { title: '姓名', dataIndex: 'customerName', key: 'customerName', align: 'center', width: 100 },
    { title: '身份证号', dataIndex: 'idCard', key: 'idCard', align: 'center', width: 150 },
    { title: '联系方式1', dataIndex: 'otherPhone1', key: 'otherPhone1', align: 'center', width: 120 },
    { title: '联系方式2', dataIndex: 'otherPhone2', key: 'otherPhone2', align: 'center', width: 120 },
    { title: '计划服务时间', dataIndex: 'plannedServiceStartDate', key: 'plannedServiceStartDate', align: 'center', width: 180 },
    { title: '计划服务时长（分钟）', dataIndex: 'serviceDurationMinutes', key: 'serviceDurationMinutes', align: 'center', width: 150 },
    { title: '服务项目', dataIndex: 'serviceName', key: 'serviceName', align: 'center', width: 120 },
    { title: '所属区域', dataIndex: 'area', key: 'area', align: 'center', width: 120 },
    { title: '服务地址', dataIndex: 'serviceAddress', key: 'serviceAddress', align: 'center', width: 200 },
    { title: '下单员', dataIndex: 'creator', key: 'creator', align: 'center', width: 100 },
    { title: '下单时间', dataIndex: 'createTime', key: 'createTime', align: 'center', width: 180 },
    { title: '操作', key: 'action', width: 100, fixed: 'right' }
]

// 高级搜索
const advancedSearchVisible = ref([])

// 计算总宽度
const totalWidth = computed(() => {
    return columns.reduce((sum, col) => sum + (col.width || 100), 0)
})

// ====== 响应式变量 ======
const showDrawer = ref(false)
const currentRecord = ref(null)
const staffList = ref([
    { id: '1', name: '张三' },
    { id: '2', name: '李四' },
    { id: '3', name: '王五' },
])

// 传递给抽屉的初始值
const drawerInitialValues = computed(() => {
  if (!currentRecord.value) return {}
  console.log('当前记录传递给抽屉:', currentRecord.value)

  return {
    id: currentRecord.value.id
  }
})

// 获取列表
async function getPageList() {
    loading.value = true
    try {
        showLoading()
        const { pageSize, current } = paginationState
        const params = {
            status:'Initialize',
            stationId: storage.local.getItem('stationId'),
            companyId: storage.local.getItem('companyId'),
            pageSize,
            current,
            ...searchFormData.value
        }
        const { success, data, total } = await apis.workOrder.getWorkOrderList(params)
        listData.value = data
        paginationState.total = total

    } catch (error) {
        console.error('获取工单列表失败:', error)
        message.error('获取数据失败')
    } finally {
        hideLoading()
    }
}

// 搜索 & 重置
function handleSearch() {
    paginationState.value.current = 1
    getPageList()
}

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

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

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

function onAreaChange(value) {
    console.log('区域变更:', value)
}

// 格式化日期（简单处理）
function formatDate(dateStr) {
    return dateStr || '—'
}

// ====== 派单抽屉操作函数 ======
function openDispatchDrawer(record) {
    currentRecord.value = record
    showDrawer.value = true
    console.log('打开派单抽屉，记录ID:', record.id)
}

function handleDrawerClose() {
    showDrawer.value = false
    currentRecord.value = null
}

function handleDispatchSubmit(values) {
    console.log('派单数据:', values)
    console.log('派给工单:', currentRecord.value)

    // 这里可以调用派单提交接口
    // await apis.workOrder.dispatchWorkOrder({
    //   workOrderId: currentRecord.value.id,
    //   ...values
    // })

    message.success('派单成功')
    handleDrawerClose()
    
    // 刷新列表
    getPageList()
}

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

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