<template>
  <el-dialog
    v-model="visible"
    title="分配单详情"
    width="900px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-tabs v-model="activeTab" type="border-card">
      <!-- 基本信息 -->
      <el-tab-pane label="基本信息" name="basic">
        <el-descriptions v-if="orderDetail" :column="2" border>
          <el-descriptions-item label="分配单号">
            {{ orderDetail.orderCode }}
          </el-descriptions-item>
          <el-descriptions-item label="单据类型">
            <el-tag>{{ orderDetail.orderTypeName }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="标题" :span="2">
            {{ orderDetail.title }}
          </el-descriptions-item>
          <el-descriptions-item label="目标机构">
            {{ orderDetail.targetOrganization?.orgName }}
          </el-descriptions-item>
          <el-descriptions-item label="申请人">
            {{ orderDetail.applicant?.realName }}
          </el-descriptions-item>
          <el-descriptions-item label="资产数量">
            {{ orderDetail.assetCount }}
          </el-descriptions-item>
          <el-descriptions-item label="审批状态">
            <el-tag :type="getApprovalStatusType(orderDetail.approvalStatus)">
              {{ getApprovalStatusName(orderDetail.approvalStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="执行状态">
            <el-tag :type="getExecuteStatusType(orderDetail.executeStatus)">
              {{ getExecuteStatusName(orderDetail.executeStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDateTime(orderDetail.createdAt) }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ orderDetail.remark || '-' }}
          </el-descriptions-item>
        </el-descriptions>
      </el-tab-pane>

      <!-- 资产明细 -->
      <el-tab-pane label="资产明细" name="assets">
        <el-table
          :data="orderDetail?.assets || []"
          border
          max-height="400"
        >
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="assetCode" label="资产编码" width="180" />
          <el-table-column prop="assetName" label="资产名称" min-width="150" />
          <el-table-column prop="deviceType.typeName" label="设备类型" width="120" />
          <el-table-column prop="brand.brandName" label="品牌" width="120" />
          <el-table-column prop="organization.orgName" label="当前机构" width="150" />
          <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>
      </el-tab-pane>

      <!-- 审批流程 -->
      <el-tab-pane label="审批流程" name="approval">
        <el-timeline>
          <el-timeline-item
            v-for="(item, index) in approvalHistory"
            :key="index"
            :timestamp="formatDateTime(item.createdAt)"
            placement="top"
            :type="getTimelineType(item.approvalStatus)"
            :icon="getTimelineIcon(item.approvalStatus)"
          >
            <el-card>
              <div class="approval-item">
                <div class="approval-header">
                  <span class="approval-operator">{{ item.operator?.realName }}</span>
                  <el-tag :type="getApprovalStatusType(item.approvalStatus)" size="small">
                    {{ getApprovalStatusName(item.approvalStatus) }}
                  </el-tag>
                </div>
                <div v-if="item.approvalRemark" class="approval-remark">
                  {{ item.approvalRemark }}
                </div>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </el-tab-pane>
    </el-tabs>

    <!-- 操作区域 -->
    <div v-if="orderDetail" class="action-section">
      <!-- 待审批状态 -->
      <div v-if="orderDetail.approvalStatus === 'pending'" class="action-group">
        <el-divider content-position="left">审批操作</el-divider>
        <el-input
          v-model="approvalForm.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入审批意见"
          maxlength="500"
          show-word-limit
        />
        <div class="action-buttons">
          <el-button type="success" :loading="actionLoading" @click="handleApprove(true)">
            通过
          </el-button>
          <el-button type="danger" :loading="actionLoading" @click="handleApprove(false)">
            拒绝
          </el-button>
        </div>
      </div>

      <!-- 已通过待执行状态 -->
      <div v-if="orderDetail.approvalStatus === 'approved' && orderDetail.executeStatus === 'pending'" class="action-group">
        <el-divider content-position="left">执行操作</el-divider>
        <el-button type="primary" :loading="actionLoading" @click="handleExecute">
          开始执行
        </el-button>
      </div>

      <!-- 执行中状态 -->
      <div v-if="orderDetail.executeStatus === 'executing'" class="action-group">
        <el-divider content-position="left">执行操作</el-divider>
        <el-button type="success" :loading="actionLoading" @click="handleComplete">
          完成执行
        </el-button>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { getAllocationOrderDetail, approveAllocationOrder } from '@/api'
import { ASSET_STATUS, APPROVAL_STATUS } from '@/utils/constants'
import dayjs from 'dayjs'

interface Props {
  modelValue: boolean
  orderId?: number | null
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const activeTab = ref('basic')
const orderDetail = ref<any>(null)
const approvalHistory = ref<any[]>([])
const actionLoading = ref(false)

const approvalForm = reactive({
  remark: ''
})

// 获取分配单详情
const fetchOrderDetail = async () => {
  if (!props.orderId) return

  try {
    const data = await getAllocationOrderDetail(props.orderId)
    orderDetail.value = data
    // TODO: 获取审批历史
    approvalHistory.value = []
  } catch (error) {
    ElMessage.error('获取详情失败')
  }
}

// 审批
const handleApprove = async (approved: boolean) => {
  if (!approvalForm.remark && !approved) {
    ElMessage.warning('请输入拒绝原因')
    return
  }

  actionLoading.value = true

  try {
    await approveAllocationOrder(props.orderId!, {
      approvalStatus: approved ? 'approved' : 'rejected',
      approvalRemark: approvalForm.remark
    })

    ElMessage.success(approved ? '审批通过' : '已拒绝')
    emit('success')
    fetchOrderDetail()
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    actionLoading.value = false
  }
}

// 执行
const handleExecute = async () => {
  actionLoading.value = true

  try {
    // TODO: 调用执行API
    ElMessage.success('开始执行')
    emit('success')
    fetchOrderDetail()
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    actionLoading.value = false
  }
}

// 完成
const handleComplete = async () => {
  actionLoading.value = true

  try {
    // TODO: 调用完成API
    ElMessage.success('执行完成')
    emit('success')
    fetchOrderDetail()
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    actionLoading.value = false
  }
}

// 获取审批状态标签类型
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
}

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

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

// 获取时间轴类型
const getTimelineType = (status: string) => {
  const map: Record<string, string> = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return map[status] || 'primary'
}

// 获取时间轴图标
const getTimelineIcon = (status: string) => {
  // TODO: 返回对应的图标组件
  return null
}

// 格式化日期时间
const formatDateTime = (datetime: string) => {
  return datetime ? dayjs(datetime).format('YYYY-MM-DD HH:mm:ss') : '-'
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  // 重置
  setTimeout(() => {
    activeTab.value = 'basic'
    orderDetail.value = null
    approvalHistory.value = []
    approvalForm.remark = ''
  }, 300)
}

// 监听orderId变化
watch(
  () => props.orderId,
  (orderId) => {
    if (orderId && props.modelValue) {
      fetchOrderDetail()
    }
  }
)

// 监听对话框打开
watch(
  () => props.modelValue,
  (val) => {
    if (val && props.orderId) {
      fetchOrderDetail()
    }
  }
)
</script>

<style scoped lang="scss">
.action-section {
  margin-top: 20px;

  .action-group {
    .action-buttons {
      margin-top: 16px;
      display: flex;
      gap: 12px;
    }
  }
}

.approval-item {
  .approval-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;

    .approval-operator {
      font-weight: 500;
      font-size: 14px;
    }
  }

  .approval-remark {
    font-size: 14px;
    color: #606266;
    line-height: 1.5;
  }
}
</style>
