<template>
  <div class="allocation-list">
    <!-- 操作栏 -->
    <el-card class="toolbar">
      <div class="toolbar-actions">
        <el-button type="primary" :icon="Plus" @click="handleCreate">
          新建分配单
        </el-button>
        <el-button :icon="Download" @click="handleExport">
          导出
        </el-button>
      </div>

      <div class="filter-section">
        <el-select
          v-model="filters.orderType"
          placeholder="单据类型"
          clearable
          style="width: 150px"
        >
          <el-option
            v-for="(item, key) in ALLOCATION_ORDER_TYPE"
            :key="key"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <el-select
          v-model="filters.approvalStatus"
          placeholder="审批状态"
          clearable
          style="width: 150px"
        >
          <el-option
            v-for="(item, key) in APPROVAL_STATUS"
            :key="key"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <el-select
          v-model="filters.executeStatus"
          placeholder="执行状态"
          clearable
          style="width: 150px"
        >
          <el-option label="待执行" value="pending" />
          <el-option label="执行中" value="executing" />
          <el-option label="已完成" value="completed" />
        </el-select>

        <el-input
          v-model="filters.keyword"
          placeholder="搜索单号/申请人"
          clearable
          style="width: 250px"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <el-button type="primary" @click="handleSearch">
          搜索
        </el-button>
        <el-button @click="handleReset">
          重置
        </el-button>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderCode" label="分配单号" width="180" fixed />
        <el-table-column prop="orderTypeName" label="单据类型" width="120">
          <template #default="{ row }">
            <el-tag>{{ row.orderTypeName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" min-width="200" />
        <el-table-column prop="targetOrganization.orgName" label="目标机构" width="150" />
        <el-table-column prop="applicant.realName" label="申请人" width="120" />
        <el-table-column prop="assetCount" label="资产数量" width="100" align="center" />
        <el-table-column prop="approvalStatus" label="审批状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getApprovalStatusType(row.approvalStatus)">
              {{ getApprovalStatusName(row.approvalStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="executeStatus" label="执行状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getExecuteStatusType(row.executeStatus)">
              {{ getExecuteStatusName(row.executeStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleView(row)">
              查看
            </el-button>
            <el-button
              v-if="row.approvalStatus === 'draft'"
              link
              type="primary"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="row.approvalStatus === 'draft'"
              link
              type="primary"
              @click="handleSubmit(row)"
            >
              提交
            </el-button>
            <el-button
              v-if="row.approvalStatus === 'pending'"
              link
              type="warning"
              @click="handleApprove(row)"
            >
              审批
            </el-button>
            <el-button
              v-if="row.approvalStatus === 'draft'"
              link
              type="danger"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
            <el-button
              v-if="row.approvalStatus === 'approved' && row.executeStatus === 'pending'"
              link
              type="success"
              @click="handleExecute(row)"
            >
              执行
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePageChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑分配单对话框 -->
    <CreateAllocationDialog
      v-model="createDialogVisible"
      :order-id="selectedOrderId"
      @success="handleSaveSuccess"
    />

    <!-- 分配单详情对话框 -->
    <AllocationDetailDialog
      v-model="detailDialogVisible"
      :order-id="selectedOrderId"
      @success="handleActionSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Plus, Download, Search } from '@element-plus/icons-vue'
import { getAllocationOrders, deleteAllocationOrder } from '@/api'
import { usePagination } from '@/composables/usePagination'
import { ALLOCATION_ORDER_TYPE, APPROVAL_STATUS } from '@/utils/constants'
import CreateAllocationDialog from './components/CreateAllocationDialog.vue'
import AllocationDetailDialog from './components/AllocationDetailDialog.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const { pagination, resetPage, setTotal } = usePagination()

const filters = reactive({
  orderType: undefined,
  approvalStatus: undefined,
  executeStatus: undefined,
  keyword: ''
})

const loading = ref(false)
const tableData = ref<any[]>([])
const selectedRows = ref<any[]>([])

const createDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const selectedOrderId = ref<number | null>(null)

// 获取分配单列表
const fetchAllocationList = async () => {
  loading.value = true
  try {
    const data = await getAllocationOrders({
      page: pagination.page,
      page_size: pagination.pageSize,
      ...filters
    })
    tableData.value = data.items
    setTotal(data.total)
  } catch (error) {
    ElMessage.error('获取分配单列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  resetPage()
  fetchAllocationList()
}

// 重置
const handleReset = () => {
  Object.assign(filters, {
    orderType: undefined,
    approvalStatus: undefined,
    executeStatus: undefined,
    keyword: ''
  })
  handleSearch()
}

// 分页变化
const handlePageChange = () => {
  fetchAllocationList()
}

// 新建
const handleCreate = () => {
  selectedOrderId.value = null
  createDialogVisible.value = true
}

// 导出
const handleExport = () => {
  ElMessage.info('导出功能开发中')
}

// 查看详情
const handleView = (row: any) => {
  selectedOrderId.value = row.id
  detailDialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  selectedOrderId.value = row.id
  createDialogVisible.value = true
}

// 提交审批
const handleSubmit = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定提交该分配单进行审批吗？', '提示', {
      type: 'warning'
    })

    // TODO: 调用提交审批API
    ElMessage.success('提交成功')
    fetchAllocationList()
  } catch (error) {
    // 用户取消
  }
}

// 审批
const handleApprove = (row: any) => {
  selectedOrderId.value = row.id
  detailDialogVisible.value = true
}

// 执行
const handleExecute = (row: any) => {
  selectedOrderId.value = row.id
  detailDialogVisible.value = true
}

// 删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定删除该分配单吗？', '提示', {
      type: 'warning'
    })

    await deleteAllocationOrder(row.id)
    ElMessage.success('删除成功')
    fetchAllocationList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 保存成功回调
const handleSaveSuccess = () => {
  fetchAllocationList()
}

// 操作成功回调
const handleActionSuccess = () => {
  fetchAllocationList()
}

// 审批状态标签类型
const getApprovalStatusType = (status: string) => {
  const item = Object.values(APPROVAL_STATUS).find(item => item.value === status)
  return item?.type || ''
}

// 审批状态名称
const getApprovalStatusName = (status: string) => {
  const item = Object.values(APPROVAL_STATUS).find(item => item.value === status)
  return item?.label || status
}

// 执行状态标签类型
const getExecuteStatusType = (status: string) => {
  const map: Record<string, string> = {
    pending: 'info',
    executing: 'warning',
    completed: 'success'
  }
  return map[status] || ''
}

// 执行状态名称
const getExecuteStatusName = (status: string) => {
  const map: Record<string, string> = {
    pending: '待执行',
    executing: '执行中',
    completed: '已完成'
  }
  return map[status] || status
}

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

<style scoped lang="scss">
.allocation-list {
  .toolbar {
    margin-bottom: 16px;

    .toolbar-actions {
      margin-bottom: 16px;
    }

    .filter-section {
      display: flex;
      gap: 10px;
      flex-wrap: wrap;
    }
  }

  .table-card {
    .pagination {
      display: flex;
      justify-content: flex-end;
      margin-top: 16px;
    }
  }
}
</style>
