<template>
  <div class="transfer-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.status"
          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.sourceOrgId"
          placeholder="源机构"
          clearable
          style="width: 150px"
        >
          <el-option
            v-for="org in organizations"
            :key="org.id"
            :label="org.orgName"
            :value="org.id"
          />
        </el-select>

        <el-select
          v-model="filters.targetOrgId"
          placeholder="目标机构"
          clearable
          style="width: 150px"
        >
          <el-option
            v-for="org in organizations"
            :key="org.id"
            :label="org.orgName"
            :value="org.id"
          />
        </el-select>

        <el-date-picker
          v-model="filters.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 280px"
        />

        <el-input
          v-model="filters.keyword"
          placeholder="搜索单号"
          clearable
          style="width: 200px"
          @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
      >
        <el-table-column prop="transferNo" label="调拨单号" width="180" fixed />
        <el-table-column prop="sourceOrg.orgName" label="源机构" width="180" />
        <el-table-column prop="targetOrg.orgName" label="目标机构" width="180" />
        <el-table-column prop="assetCount" label="资产数量" width="100" align="center" />
        <el-table-column prop="totalValue" label="总价值" width="120">
          <template #default="{ row }">
            {{ row.totalValue ? `¥${row.totalValue.toFixed(2)}` : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="审批状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="applicant.username" label="申请人" width="120" />
        <el-table-column prop="createdAt" label="申请时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleView(row)">
              详情
            </el-button>
            <el-button
              v-if="row.status === 'pending'"
              link
              type="warning"
              @click="handleApprove(row)"
            >
              审批
            </el-button>
            <el-button
              v-if="row.status === 'approved'"
              link
              type="success"
              @click="handleExecute(row)"
            >
              执行
            </el-button>
            <el-popconfirm
              v-if="row.status === 'pending'"
              title="确定取消该调拨单吗？"
              @confirm="handleCancel(row.id)"
            >
              <template #reference>
                <el-button link type="danger">取消</el-button>
              </template>
            </el-popconfirm>
          </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>

    <!-- 创建调拨单对话框 -->
    <CreateTransferDialog
      v-model="createDialogVisible"
      @success="handleSaveSuccess"
    />

    <!-- 调拨单详情对话框 -->
    <TransferDetailDialog
      v-model="detailDialogVisible"
      :transfer-id="selectedTransferId"
    />

    <!-- 审批对话框 -->
    <el-dialog
      v-model="approveDialogVisible"
      title="调拨审批"
      width="500px"
    >
      <el-form :model="approveForm" label-width="80px">
        <el-form-item label="审批结果">
          <el-radio-group v-model="approveForm.approved">
            <el-radio :label="true">通过</el-radio>
            <el-radio :label="false">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批意见">
          <el-input
            v-model="approveForm.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入审批意见"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="approveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleApproveSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Plus, Download, Search } from '@element-plus/icons-vue'
import { getTransferList, cancelTransfer, approveTransfer, executeTransfer, getOrganizationTree } from '@/api'
import { usePagination } from '@/composables/usePagination'
import { APPROVAL_STATUS } from '@/utils/constants'
import CreateTransferDialog from './components/CreateTransferDialog.vue'
import TransferDetailDialog from './components/TransferDetailDialog.vue'
import { ElMessage } from 'element-plus'

const organizations = ref<any[]>([])

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

const filters = reactive({
  status: undefined,
  sourceOrgId: undefined,
  targetOrgId: undefined,
  dateRange: null as any,
  keyword: ''
})

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

const createDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const approveDialogVisible = ref(false)
const selectedTransferId = ref<number | null>(null)
const selectedTransfer = ref<any>(null)

const approveForm = reactive({
  approved: true,
  comment: ''
})

// 获取调拨单列表
const fetchTransferList = async () => {
  loading.value = true
  try {
    const params: any = {
      page: pagination.page,
      page_size: pagination.pageSize,
      ...filters
    }
    if (filters.dateRange) {
      params.start_date = filters.dateRange[0]
      params.end_date = filters.dateRange[1]
    }
    delete params.dateRange

    const data = await getTransferList(params)
    tableData.value = data.items
    setTotal(data.total)
  } catch (error) {
    ElMessage.error('获取调拨单列表失败')
  } finally {
    loading.value = false
  }
}

// 获取机构树
const fetchOrganizations = async () => {
  try {
    const tree = await getOrganizationTree()
    const flatten = (nodes: any[]) => {
      const result: any[] = []
      nodes.forEach(node => {
        result.push(node)
        if (node.children) {
          result.push(...flatten(node.children))
        }
      })
      return result
    }
    organizations.value = flatten(tree)
  } catch (error) {
    console.error('获取机构失败', error)
  }
}

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

// 重置
const handleReset = () => {
  Object.assign(filters, {
    status: undefined,
    sourceOrgId: undefined,
    targetOrgId: undefined,
    dateRange: null,
    keyword: ''
  })
  handleSearch()
}

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

// 创建
const handleCreate = () => {
  createDialogVisible.value = true
}

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

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

// 审批
const handleApprove = (row: any) => {
  selectedTransfer.value = row
  approveForm.approved = true
  approveForm.comment = ''
  approveDialogVisible.value = true
}

// 提交审批
const handleApproveSubmit = async () => {
  try {
    await approveTransfer(selectedTransfer.value.id, approveForm)
    ElMessage.success('审批成功')
    approveDialogVisible.value = false
    fetchTransferList()
  } catch (error) {
    ElMessage.error('审批失败')
  }
}

// 执行
const handleExecute = async (row: any) => {
  try {
    await executeTransfer(row.id)
    ElMessage.success('执行成功')
    fetchTransferList()
  } catch (error) {
    ElMessage.error('执行失败')
  }
}

// 取消
const handleCancel = async (id: number) => {
  try {
    await cancelTransfer(id)
    ElMessage.success('取消成功')
    fetchTransferList()
  } catch (error) {
    ElMessage.error('取消失败')
  }
}

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

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

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

onMounted(() => {
  fetchTransferList()
  fetchOrganizations()
})
</script>

<style scoped lang="scss">
.transfer-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>
