<template>
  <div class="installation-task-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">待安装任务</h1>
      <div class="header-actions">
        <a-button type="primary" @click="handleExportTasks">
          安装任务导出
        </a-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <a-form layout="inline" :model="searchForm" @finish="handleSearch">
        <a-form-item>
          <a-input 
            v-model:value="searchForm.policyNumber" 
            placeholder="保单编号"
            allowClear
            style="width: 150px;"
          />
        </a-form-item>
        <a-form-item>
          <a-input 
            v-model:value="searchForm.keyword" 
            placeholder="关键字搜索"
            allowClear
            style="width: 150px;"
          />
        </a-form-item>
        <a-form-item>
          <a-select 
            v-model:value="searchForm.installationStatus" 
            placeholder="安装状态"
            allowClear
            style="width: 120px;"
          >
            <a-select-option value="待安装">待安装</a-select-option>
            <a-select-option value="安装中">安装中</a-select-option>
            <a-select-option value="已安装">已安装</a-select-option>
            <a-select-option value="安装失败">安装失败</a-select-option>
            <a-select-option value="已取消">已取消</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit">
            <SearchOutlined />
            搜索
          </a-button>
        </a-form-item>
        <a-form-item>
          <a-button @click="handleReset">重置</a-button>
        </a-form-item>
      </a-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :pagination="pagination"
        :loading="loading"
        row-key="id"
        @change="handleTableChange"
        size="middle"
        :scroll="{ x: 1800 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'installationStatus'">
            <a-tag :color="getInstallationStatusColor(record.installationStatus)">
              {{ record.installationStatus }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'taskGeneratedTime'">
            <span>{{ formatDateTime(record.taskGeneratedTime) }}</span>
          </template>
          <template v-else-if="column.key === 'installationCompletedTime'">
            <span>{{ formatDateTime(record.installationCompletedTime) }}</span>
          </template>
          <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button type="link" size="small" @click="handleView(record)">
              查看
            </a-button>
            <a-button type="link" size="small" @click="handleEdit(record)">
              编辑
            </a-button>
            <a-popconfirm
              title="确定要删除这条安装任务吗？"
              @confirm="handleDelete(record.id)"
            >
              <a-button type="link" size="small" danger>
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 数据为空提示 -->
    <div v-if="!loading && tableData.length === 0" class="empty-data">
      <a-empty description="暂无数据" />
    </div>

    <!-- 分页信息 -->
    <div class="pagination-info">
      <span>共 {{ pagination.total }} 条记录</span>
    </div>

    <!-- 查看/编辑安装任务弹窗 -->
    <a-modal
      :title="modalTitle"
      :open="modalVisible"
      :width="900"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      :confirmLoading="modalLoading"
      :footer="isViewMode ? null : undefined"
    >
      <a-form
        ref="modalFormRef"
        :model="modalForm"
        :rules="modalRules"
        layout="vertical"
        :disabled="isViewMode"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="申请单号" name="applicationNumber">
              <a-input v-model:value="modalForm.applicationNumber" placeholder="请输入申请单号" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="保单编号" name="policyNumber">
              <a-input v-model:value="modalForm.policyNumber" 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="modalForm.productName" placeholder="请输入产品名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="客户姓名" name="customerName">
              <a-input v-model:value="modalForm.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="modalForm.idType" placeholder="请选择证件类型">
                <a-select-option value="身份证">身份证</a-select-option>
                <a-select-option value="护照">护照</a-select-option>
                <a-select-option value="军官证">军官证</a-select-option>
                <a-select-option value="其他">其他</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="modalForm.idNumber" placeholder="请输入证件号码" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="养殖生资种类" name="livestockSupplyType">
              <a-input v-model:value="modalForm.livestockSupplyType" placeholder="请输入养殖生资种类" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="待安装设备" name="pendingDevices">
              <a-input v-model:value="modalForm.pendingDevices" 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="modalForm.installationStatus" placeholder="请选择安装状态">
                <a-select-option value="待安装">待安装</a-select-option>
                <a-select-option value="安装中">安装中</a-select-option>
                <a-select-option value="已安装">已安装</a-select-option>
                <a-select-option value="安装失败">安装失败</a-select-option>
                <a-select-option value="已取消">已取消</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="生成安装任务时间" name="taskGeneratedTime">
              <a-date-picker 
                v-model:value="modalForm.taskGeneratedTime" 
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择生成任务时间"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="安装完成生效时间" name="installationCompletedTime">
              <a-date-picker 
                v-model:value="modalForm.installationCompletedTime" 
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择完成时间"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="安装人员" name="installer">
              <a-input v-model:value="modalForm.installer" placeholder="请输入安装人员" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="备注" name="remarks">
          <a-textarea 
            v-model:value="modalForm.remarks" 
            placeholder="请输入备注信息"
            :rows="3"
          />
        </a-form-item>

        <!-- 查看模式下显示操作按钮 -->
        <div v-if="isViewMode" style="text-align: right; margin-top: 16px;">
          <a-space>
            <a-button @click="handleModalCancel">关闭</a-button>
            <a-button type="primary" @click="switchToEditMode">编辑</a-button>
          </a-space>
        </div>
      </a-form>
    </a-modal>
  </div>
</template>

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

// 响应式数据
const loading = ref(false);
const tableData = ref([]);
const modalVisible = ref(false);
const modalLoading = ref(false);
const modalFormRef = ref();
const editingId = ref(null);
const isViewMode = ref(false);

// 搜索表单
const searchForm = reactive({
  policyNumber: '',
  keyword: '',
  installationStatus: undefined,
});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
});

// 弹窗表单
const modalForm = reactive({
  applicationNumber: '',
  policyNumber: '',
  productName: '',
  customerName: '',
  idType: '',
  idNumber: '',
  livestockSupplyType: '',
  pendingDevices: '',
  installationStatus: '',
  taskGeneratedTime: null,
  installationCompletedTime: null,
  installer: '',
  remarks: ''
});

// 表单验证规则
const modalRules = {
  applicationNumber: [
    { required: true, message: '请输入申请单号', trigger: 'blur' }
  ],
  policyNumber: [
    { required: true, message: '请输入保单编号', trigger: 'blur' }
  ],
  productName: [
    { required: true, message: '请输入产品名称', trigger: 'blur' }
  ],
  customerName: [
    { required: true, message: '请输入客户姓名', trigger: 'blur' }
  ],
  installationStatus: [
    { required: true, message: '请选择安装状态', trigger: 'change' }
  ]
};

// 计算属性
const modalTitle = computed(() => {
  if (isViewMode.value) return '查看安装任务';
  return editingId.value ? '编辑安装任务' : '新增安装任务';
});

// 表格列定义
const columns = [
  {
    title: '申请单号',
    dataIndex: 'applicationNumber',
    key: 'applicationNumber',
    width: 120,
    ellipsis: true
  },
  {
    title: '保单编号',
    dataIndex: 'policyNumber',
    key: 'policyNumber',
    width: 120,
    ellipsis: true
  },
  {
    title: '产品名称',
    dataIndex: 'productName',
    key: 'productName',
    width: 150,
    ellipsis: true
  },
  {
    title: '客户姓名',
    dataIndex: 'customerName',
    key: 'customerName',
    width: 100
  },
  {
    title: '证件类型',
    dataIndex: 'idType',
    key: 'idType',
    width: 100
  },
  {
    title: '证件号码',
    dataIndex: 'idNumber',
    key: 'idNumber',
    width: 160,
    ellipsis: true
  },
  {
    title: '养殖生资种类',
    dataIndex: 'livestockSupplyType',
    key: 'livestockSupplyType',
    width: 150,
    ellipsis: true
  },
  {
    title: '待安装设备',
    dataIndex: 'pendingDevices',
    key: 'pendingDevices',
    width: 150,
    ellipsis: true
  },
  {
    title: '安装状态',
    dataIndex: 'installationStatus',
    key: 'installationStatus',
    width: 100
  },
  {
    title: '生成安装任务时间',
    dataIndex: 'taskGeneratedTime',
    key: 'taskGeneratedTime',
    width: 160
  },
  {
    title: '安装完成生效时间',
    dataIndex: 'installationCompletedTime',
    key: 'installationCompletedTime',
    width: 160
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right'
  }
];

// 生命周期钩子
onMounted(() => {
  fetchInstallationTasks();
});

// 方法定义
const fetchInstallationTasks = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...searchForm
    };
    
    const response = await installationTaskApi.getInstallationTasks(params);
    console.log('安装任务API响应:', response);
    
    if (response.data && response.data.status === 'success') {
      tableData.value = response.data.data.list || [];
      pagination.total = response.data.data.total || 0;
      console.log('安装任务数据设置成功:', tableData.value.length, '条');
    } else {
      console.log('安装任务响应格式错误:', response);
      message.error(response.data?.message || '获取安装任务列表失败');
    }
  } catch (error) {
    console.error('获取安装任务列表失败:', error);
    message.error('获取安装任务列表失败');
  } finally {
    loading.value = false;
  }
};

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

const handleReset = () => {
  Object.assign(searchForm, {
    policyNumber: '',
    keyword: '',
    installationStatus: undefined,
  });
  handleSearch();
};

const handleTableChange = (paginationInfo) => {
  pagination.current = paginationInfo.current;
  pagination.pageSize = paginationInfo.pageSize;
  fetchInstallationTasks();
};

const handleView = (record) => {
  console.log('查看记录:', record);
  isViewMode.value = true;
  editingId.value = record.id;
  fillModalForm(record);
  modalVisible.value = true;
};

const handleEdit = (record) => {
  console.log('编辑记录:', record);
  isViewMode.value = false;
  editingId.value = record.id;
  fillModalForm(record);
  modalVisible.value = true;
};

const fillModalForm = (record) => {
  Object.assign(modalForm, {
    applicationNumber: record.applicationNumber || '',
    policyNumber: record.policyNumber || '',
    productName: record.productName || '',
    customerName: record.customerName || '',
    idType: record.idType || '',
    idNumber: record.idNumber || '',
    livestockSupplyType: record.livestockSupplyType || '',
    pendingDevices: record.pendingDevices || '',
    installationStatus: record.installationStatus || '',
    taskGeneratedTime: record.taskGeneratedTime ? dayjs(record.taskGeneratedTime) : null,
    installationCompletedTime: record.installationCompletedTime ? dayjs(record.installationCompletedTime) : null,
    installer: record.installer || '',
    remarks: record.remarks || ''
  });
};

const resetModalForm = () => {
  Object.assign(modalForm, {
    applicationNumber: '',
    policyNumber: '',
    productName: '',
    customerName: '',
    idType: '',
    idNumber: '',
    livestockSupplyType: '',
    pendingDevices: '',
    installationStatus: '',
    taskGeneratedTime: null,
    installationCompletedTime: null,
    installer: '',
    remarks: ''
  });
};

const switchToEditMode = () => {
  isViewMode.value = false;
};

const handleModalOk = async () => {
  if (isViewMode.value) {
    modalVisible.value = false;
    return;
  }

  try {
    await modalFormRef.value.validate();
    modalLoading.value = true;

    const submitData = {
      ...modalForm,
      taskGeneratedTime: modalForm.taskGeneratedTime ? 
        dayjs(modalForm.taskGeneratedTime).format('YYYY-MM-DD HH:mm:ss') : null,
      installationCompletedTime: modalForm.installationCompletedTime ? 
        dayjs(modalForm.installationCompletedTime).format('YYYY-MM-DD HH:mm:ss') : null
    };

    const response = editingId.value
      ? await installationTaskApi.updateInstallationTask(editingId.value, submitData)
      : await installationTaskApi.createInstallationTask(submitData);

    if (response.code === 200 || response.code === 201) {
      message.success(editingId.value ? '更新成功' : '创建成功');
      modalVisible.value = false;
      fetchInstallationTasks();
    } else {
      message.error(response.message || '操作失败');
    }
  } catch (error) {
    console.error('提交失败:', error);
    if (error.errorFields) {
      message.error('请完善表单信息');
    } else {
      message.error('操作失败');
    }
  } finally {
    modalLoading.value = false;
  }
};

const handleModalCancel = () => {
  modalVisible.value = false;
  isViewMode.value = false;
  editingId.value = null;
  resetModalForm();
};

const handleDelete = async (id) => {
  try {
    const response = await installationTaskApi.deleteInstallationTask(id);
    if (response.code === 200) {
      message.success('删除成功');
      fetchInstallationTasks();
    } else {
      message.error(response.message || '删除失败');
    }
  } catch (error) {
    console.error('删除失败:', error);
    message.error('删除失败');
  }
};

const handleExportTasks = async () => {
  try {
    const response = await installationTaskApi.exportInstallationTasks(searchForm);
    
    if (response && response.data) {
      // 处理文件下载 - response.data是Blob对象
      const url = window.URL.createObjectURL(response.data);
      const link = document.createElement('a');
      link.href = url;
      link.download = `安装任务导出_${dayjs().format('YYYY-MM-DD_HH-mm-ss')}.xlsx`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      message.success('导出成功');
    } else {
      message.error('导出失败');
    }
  } catch (error) {
    console.error('导出失败:', error);
    message.error('导出失败，请稍后重试');
  }
};

// 工具方法
const formatDateTime = (dateTime) => {
  return dateTime ? dayjs(dateTime).format('YYYY-MM-DD HH:mm:ss') : '-';
};

const getInstallationStatusColor = (status) => {
  const colorMap = {
    '待安装': 'orange',
    '安装中': 'blue',
    '已安装': 'green',
    '安装失败': 'red',
    '已取消': 'default'
  };
  return colorMap[status] || 'default';
};
</script>

<style scoped>
.installation-task-container {
  padding: 20px;
  background: #fff;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.page-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #262626;
}

.search-section {
  margin-bottom: 20px;
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
}

.search-row {
  align-items: center;
}

.text-right {
  text-align: right;
}

.table-section {
  background: #fff;
  border-radius: 6px;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
}

:deep(.ant-pagination) {
  margin-top: 16px;
  text-align: right;
}
</style>

<style scoped>
.installation-task-page {
  padding: 24px;
  background: #fff;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 16px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #262626;
  margin: 0;
}

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

.search-area {
  margin-bottom: 16px;
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
}

.table-container {
  margin-bottom: 16px;
}

.empty-data {
  text-align: center;
  padding: 40px 0;
}

.pagination-info {
  text-align: right;
  padding: 16px 0;
  color: #666;
  font-size: 14px;
}

/* 查看模式下表单样式优化 */
:deep(.ant-form-item-control-input-content) {
  .ant-input[disabled],
  .ant-select-disabled .ant-select-selector,
  .ant-picker-disabled,
  .ant-input-number-disabled {
    color: rgba(0, 0, 0, 0.85);
    background-color: #fafafa;
    border-color: #d9d9d9;
    cursor: default;
  }
  
  .ant-input-disabled,
  .ant-select-disabled .ant-select-selection-item {
    color: rgba(0, 0, 0, 0.85);
  }
}
</style>