<template>
  <div class="pending-installation-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1>待安装任务</h1>
      <div class="header-actions">
        <a-button type="primary" @click="handleExport">
          <download-outlined />
          安装任务导出
        </a-button>
      </div>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <a-row :gutter="16" align="middle">
        <a-col :span="6">
          <a-input
            v-model:value="searchForm.contractNumber"
            placeholder="请输入合同编号"
            allow-clear
          />
        </a-col>
        <a-col :span="8">
          <a-range-picker
            v-model:value="searchForm.dateRange"
            :placeholder="['开始日期', '结束日期']"
            style="width: 100%"
          />
        </a-col>
        <a-col :span="4">
          <a-select
            v-model:value="searchForm.installationStatus"
            placeholder="请选择安装状态"
            allow-clear
            style="width: 100%"
          >
            <a-select-option value="pending">待安装</a-select-option>
            <a-select-option value="in-progress">安装中</a-select-option>
            <a-select-option value="completed">已完成</a-select-option>
            <a-select-option value="failed">安装失败</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="6">
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <search-outlined />
              搜索
            </a-button>
            <a-button @click="handleReset">重置</a-button>
          </a-space>
        </a-col>
      </a-row>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <a-table
        :columns="columns"
        :data-source="filteredTasks"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
        :locale="{ emptyText: '暂无数据' }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'installationStatus'">
            <a-tag :color="getStatusColor(record.installationStatus)">
              {{ getStatusName(record.installationStatus) }}
            </a-tag>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="viewTask(record)">查看</a-button>
              <a-button type="link" size="small" @click="editTask(record)">编辑</a-button>
              <a-button type="link" size="small" @click="startInstallation(record)">开始安装</a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 编辑待安装任务对话框 -->
    <a-modal
      v-model:open="editModalVisible"
      title="编辑待安装任务"
      width="800px"
      @ok="handleEditTask"
      @cancel="handleCancelEdit"
      :confirmLoading="editLoading"
    >
      <a-form
        ref="editTaskFormRef"
        :model="editTaskForm"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="申请单号" name="applicationNumber">
              <a-input v-model:value="editTaskForm.applicationNumber" placeholder="请输入申请单号" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="放款合同编号" name="contractNumber">
              <a-input v-model:value="editTaskForm.contractNumber" placeholder="请输入放款合同编号" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="产品名称" name="productName">
              <a-input v-model:value="editTaskForm.productName" placeholder="请输入产品名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="客户姓名" name="customerName">
              <a-input v-model:value="editTaskForm.customerName" placeholder="请输入客户姓名" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="证件类型" name="idType">
              <a-select v-model:value="editTaskForm.idType" placeholder="请选择证件类型">
                <a-select-option value="ID_CARD">身份证</a-select-option>
                <a-select-option value="PASSPORT">护照</a-select-option>
                <a-select-option value="OTHER">其他</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="证件号码" name="idNumber">
              <a-input v-model:value="editTaskForm.idNumber" placeholder="请输入证件号码" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="养殖生资种类" name="assetType">
              <a-input v-model:value="editTaskForm.assetType" placeholder="请输入养殖生资种类" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="待安装设备" name="equipmentToInstall">
              <a-input v-model:value="editTaskForm.equipmentToInstall" placeholder="请输入待安装设备" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="安装状态" name="installationStatus">
              <a-select v-model:value="editTaskForm.installationStatus" placeholder="请选择安装状态">
                <a-select-option value="pending">待安装</a-select-option>
                <a-select-option value="in-progress">安装中</a-select-option>
                <a-select-option value="completed">已完成</a-select-option>
                <a-select-option value="failed">安装失败</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="生成安装任务时间" name="taskGenerationTime">
              <a-date-picker 
                v-model:value="editTaskForm.taskGenerationTime" 
                placeholder="请选择生成时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                show-time
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="安装完成生效时间" name="completionTime">
              <a-date-picker 
                v-model:value="editTaskForm.completionTime" 
                placeholder="请选择完成时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                show-time
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="安装员姓名" name="installerName">
              <a-input v-model:value="editTaskForm.installerName" placeholder="请输入安装员姓名" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="安装员电话" name="installerPhone">
              <a-input v-model:value="editTaskForm.installerPhone" placeholder="请输入安装员电话" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="安装地址" name="installationAddress">
          <a-input v-model:value="editTaskForm.installationAddress" placeholder="请输入安装地址" />
        </a-form-item>

        <a-form-item label="安装备注" name="installationNotes">
          <a-textarea 
            v-model:value="editTaskForm.installationNotes" 
            placeholder="请输入安装备注"
            :rows="3"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { DownloadOutlined, SearchOutlined } from '@ant-design/icons-vue'
import { api } from '@/utils/api'
import dayjs from 'dayjs'

const loading = ref(false)
const tasks = ref([])

// 编辑相关
const editModalVisible = ref(false)
const editTaskFormRef = ref()
const editTaskForm = ref({})
const editLoading = ref(false)
const currentEditTask = ref(null)

const searchForm = reactive({
  contractNumber: '',
  dateRange: [],
  installationStatus: undefined,
})

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条`,
})

const columns = [
  { title: '申请单号', dataIndex: 'applicationNumber', key: 'applicationNumber', sorter: true },
  { title: '放款合同编号', dataIndex: 'contractNumber', key: 'contractNumber', sorter: true },
  { title: '产品名称', dataIndex: 'productName', key: 'productName' },
  { title: '客户姓名', dataIndex: 'customerName', key: 'customerName' },
  { title: '证件类型', dataIndex: 'idType', key: 'idType' },
  { title: '证件号码', dataIndex: 'idNumber', key: 'idNumber' },
  { title: '养殖生资种类', dataIndex: 'assetType', key: 'assetType' },
  { title: '待安装设备', dataIndex: 'equipmentToInstall', key: 'equipmentToInstall' },
  { title: '安装状态', dataIndex: 'installationStatus', key: 'installationStatus', filters: [
    { text: '待安装', value: 'pending' },
    { text: '安装中', value: 'in-progress' },
    { text: '已完成', value: 'completed' },
    { text: '安装失败', value: 'failed' },
  ]},
  { title: '生成安装任务时间', dataIndex: 'taskGenerationTime', key: 'taskGenerationTime', sorter: true },
  { title: '安装完成生效时间', dataIndex: 'completionTime', key: 'completionTime', sorter: true },
  { title: '操作', key: 'action', fixed: 'right', width: 180 },
]

// 模拟数据
const mockTasks = [
  {
    id: 'I001',
    applicationNumber: 'APP2024001',
    contractNumber: 'LOAN2024001',
    productName: '生猪养殖贷',
    customerName: '张三',
    idType: 'ID_CARD',
    idNumber: '4401XXXXXXXXXXXXXX',
    assetType: '生猪',
    equipmentToInstall: '耳标设备',
    installationStatus: 'pending',
    taskGenerationTime: '2024-01-15 10:30:00',
    completionTime: null,
  },
  {
    id: 'I002',
    applicationNumber: 'APP2024002',
    contractNumber: 'LOAN2024002',
    productName: '肉牛养殖贷',
    customerName: '李四',
    idType: 'ID_CARD',
    idNumber: '4402XXXXXXXXXXXXXX',
    assetType: '肉牛',
    equipmentToInstall: '项圈设备',
    installationStatus: 'in-progress',
    taskGenerationTime: '2024-01-16 14:20:00',
    completionTime: null,
  },
  {
    id: 'I003',
    applicationNumber: 'APP2024003',
    contractNumber: 'LOAN2024003',
    productName: '蛋鸡养殖贷',
    customerName: '王五',
    idType: 'ID_CARD',
    idNumber: '4403XXXXXXXXXXXXXX',
    assetType: '蛋鸡',
    equipmentToInstall: '监控设备',
    installationStatus: 'completed',
    taskGenerationTime: '2024-01-10 09:15:00',
    completionTime: '2024-01-20 16:30:00',
  },
]

const fetchTasks = async () => {
  loading.value = true
  try {
    // 构建日期范围参数
    let dateRangeParam = ''
    if (searchForm.dateRange && Array.isArray(searchForm.dateRange) && searchForm.dateRange.length === 2) {
      dateRangeParam = `${searchForm.dateRange[0].format('YYYY-MM-DD')},${searchForm.dateRange[1].format('YYYY-MM-DD')}`
    }
    
    console.log('开始获取待安装任务列表...', {
      page: pagination.current,
      pageSize: pagination.pageSize,
      search: searchForm.contractNumber,
      installationStatus: searchForm.installationStatus,
      dateRange: dateRangeParam
    })
    
    const response = await api.installationTasks.getList({
      page: pagination.current,
      limit: pagination.pageSize,
      search: searchForm.contractNumber,
      installationStatus: searchForm.installationStatus,
      dateRange: dateRangeParam
    })
    
    console.log('待安装任务列表响应:', response)
    
    if (response.success) {
      tasks.value = response.data.tasks || []
      pagination.total = response.data.pagination.total
    } else {
      message.error(response.message || '获取待安装任务列表失败')
    }
  } catch (error) {
    console.error('获取待安装任务失败:', error)
    message.error('获取待安装任务失败')
  } finally {
    loading.value = false
  }
}

const filteredTasks = computed(() => {
  // 后端已经处理了过滤，直接返回任务列表
  return tasks.value
})

const handleSearch = () => {
  pagination.current = 1
  fetchTasks()
}

const handleReset = () => {
  searchForm.contractNumber = ''
  searchForm.dateRange = []
  searchForm.installationStatus = undefined
  pagination.current = 1
  fetchTasks()
}

const handleExport = () => {
  message.info('安装任务导出功能开发中...')
}

const handleTableChange = (pag, filters, sorter) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchTasks()
}

const getStatusColor = (status) => {
  const colors = {
    'pending': 'blue',
    'in-progress': 'orange',
    'completed': 'green',
    'failed': 'red',
  }
  return colors[status] || 'default'
}

const getStatusName = (status) => {
  const names = {
    'pending': '待安装',
    'in-progress': '安装中',
    'completed': '已完成',
    'failed': '安装失败',
  }
  return names[status] || status
}

const viewTask = async (record) => {
  try {
    const response = await api.installationTasks.getById(record.id)
    if (response.success) {
      message.info(`查看任务: ${record.applicationNumber}`)
      // 这里可以打开详情对话框显示任务信息
      console.log('任务详情:', response.data)
    } else {
      message.error('获取任务详情失败')
    }
  } catch (error) {
    console.error('获取任务详情失败:', error)
    message.error('获取任务详情失败')
  }
}

const editTask = async (record) => {
  try {
    // 保存当前编辑的任务
    currentEditTask.value = record
    
    // 填充编辑表单数据
    editTaskForm.value = {
      applicationNumber: record.applicationNumber || '',
      contractNumber: record.contractNumber || '',
      productName: record.productName || '',
      customerName: record.customerName || '',
      idType: record.idType || 'ID_CARD',
      idNumber: record.idNumber || '',
      assetType: record.assetType || '',
      equipmentToInstall: record.equipmentToInstall || '',
      installationStatus: record.installationStatus || 'pending',
      taskGenerationTime: record.taskGenerationTime ? dayjs(record.taskGenerationTime) : null,
      completionTime: record.completionTime ? dayjs(record.completionTime) : null,
      installerName: record.installerName || '',
      installerPhone: record.installerPhone || '',
      installationAddress: record.installationAddress || '',
      installationNotes: record.installationNotes || ''
    }
    
    // 打开编辑对话框
    editModalVisible.value = true
  } catch (error) {
    console.error('打开编辑对话框失败:', error)
    message.error('打开编辑对话框失败')
  }
}

const startInstallation = async (record) => {
  try {
    const response = await api.installationTasks.update(record.id, {
      installationStatus: 'in-progress'
    })
    
    if (response.success) {
      message.success(`开始安装任务: ${record.applicationNumber}`)
      fetchTasks() // 刷新列表
    } else {
      message.error('开始安装任务失败')
    }
  } catch (error) {
    console.error('开始安装任务失败:', error)
    message.error('开始安装任务失败')
  }
}

// 编辑任务处理函数
const handleEditTask = async () => {
  try {
    editLoading.value = true
    
    const response = await api.installationTasks.update(currentEditTask.value.id, editTaskForm.value)
    
    if (response.success) {
      message.success('编辑待安装任务成功')
      editModalVisible.value = false
      editTaskFormRef.value.resetFields()
      currentEditTask.value = null
      fetchTasks() // 刷新列表
    } else {
      message.error(response.message || '编辑待安装任务失败')
    }
  } catch (error) {
    console.error('编辑待安装任务失败:', error)
    message.error('编辑待安装任务失败')
  } finally {
    editLoading.value = false
  }
}

const handleCancelEdit = () => {
  editModalVisible.value = false
  editTaskFormRef.value.resetFields()
  currentEditTask.value = null
}

onMounted(() => {
  fetchTasks()
})
</script>

<style scoped>
.pending-installation-page {
  padding: 0;
  background: #f0f2f5;
  min-height: calc(100vh - 134px);
  margin: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-section {
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 24px;
}

.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  overflow: hidden;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: center;
  }
  
  .search-section .ant-col {
    margin-bottom: 16px;
  }
  
  .search-section .ant-col:last-child {
    margin-bottom: 0;
  }
}
</style>