<template>
  <div class="approval-assistant">
    <!-- 助手头部 -->
    <div class="assistant-header">
      <div class="header-left">
        <IconRobot style="font-size: 20px; color: var(--color-primary); margin-right: 8px;" />
        <h3>智能审批助手</h3>
      </div>
      <div class="header-right">
        <a-switch
          v-model="assistantEnabled"
          size="small"
          @change="toggleAssistant"
        >
          <template #checked>启用</template>
          <template #unchecked>禁用</template>
        </a-switch>
      </div>
    </div>

    <!-- 助手内容 -->
    <div v-if="assistantEnabled && currentApproval" class="assistant-content">
      <!-- 审批建议 -->
      <div class="assistant-section">
        <div class="section-header">
          <IconLightbulb style="color: var(--color-warning); margin-right: 8px;" />
          <span>审批建议</span>
        </div>
        <div class="section-content">
          <div class="recommendation-card" :class="getRecommendationClass()">
            <div class="recommendation-icon">
              <IconCheckCircle v-if="recommendation === 'APPROVE'" />
              <IconCloseCircle v-else-if="recommendation === 'REJECT'" />
              <IconExclamationCircle v-else />
            </div>
            <div class="recommendation-content">
              <div class="recommendation-title">
                {{ getRecommendationTitle() }}
              </div>
              <div class="recommendation-reason">
                {{ getRecommendationReason() }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 风险评估 -->
      <div class="assistant-section">
        <div class="section-header">
          <IconShield style="color: var(--color-danger); margin-right: 8px;" />
          <span>风险评估</span>
        </div>
        <div class="section-content">
          <div class="risk-indicators">
            <div 
              v-for="risk in riskFactors" 
              :key="risk.type"
              class="risk-item"
              :class="getRiskClass(risk.level)"
            >
              <div class="risk-icon">
                <IconExclamationCircle v-if="risk.level === 'HIGH'" />
                <IconWarning v-else-if="risk.level === 'MEDIUM'" />
                <IconCheckCircle v-else />
              </div>
              <div class="risk-info">
                <div class="risk-title">{{ risk.title }}</div>
                <div class="risk-description">{{ risk.description }}</div>
              </div>
              <div class="risk-score">{{ risk.score }}%</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 快速审批 -->
      <div class="assistant-section">
        <div class="section-header">
          <IconThunderbolt style="color: var(--color-success); margin-right: 8px;" />
          <span>快速审批</span>
        </div>
        <div class="section-content">
          <div class="quick-actions">
            <a-button 
              type="primary" 
              size="small"
              :disabled="recommendation !== 'APPROVE'"
              @click="handleQuickApprove"
            >
              <template #icon>
                <IconCheckCircle />
              </template>
              快速通过
            </a-button>
            <a-button 
              type="text" 
              size="small"
              status="danger"
              :disabled="recommendation !== 'REJECT'"
              @click="handleQuickReject"
            >
              <template #icon>
                <IconCloseCircle />
              </template>
              快速拒绝
            </a-button>
            <a-button 
              type="text" 
              size="small"
              @click="handleManualReview"
            >
              <template #icon>
                <IconEdit />
              </template>
              手动审批
            </a-button>
          </div>
        </div>
      </div>

      <!-- 审批历史分析 -->
      <div class="assistant-section">
        <div class="section-header">
          <IconBarChart style="color: var(--color-info); margin-right: 8px;" />
          <span>审批历史分析</span>
        </div>
        <div class="section-content">
          <div class="history-stats">
            <div class="stat-item">
              <div class="stat-number">{{ historyStats.total }}</div>
              <div class="stat-label">总申请数</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ historyStats.approved }}</div>
              <div class="stat-label">通过率</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ historyStats.avgTime }}</div>
              <div class="stat-label">平均审批时间</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 助手未启用提示 -->
    <div v-else-if="!assistantEnabled" class="assistant-disabled">
      <IconRobot style="font-size: 48px; color: var(--color-text-3); margin-bottom: 16px;" />
      <p>智能审批助手已禁用</p>
      <a-button type="primary" size="small" @click="assistantEnabled = true">
        启用助手
      </a-button>
    </div>

    <!-- 无审批数据提示 -->
    <div v-else class="no-approval-data">
      <IconFile style="font-size: 48px; color: var(--color-text-3); margin-bottom: 16px;" />
      <p>请选择要审批的申请</p>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, ref, watch } from 'vue'
import {
  IconRobot,
  IconLightbulb,
  IconShield,
  IconThunderbolt,
  IconBarChart,
  IconFile,
  IconCheckCircle,
  IconCloseCircle,
  IconExclamationCircle,
  IconWarning,
  IconEdit
} from '@arco-design/web-vue/es/icon'
import message from '@arco-design-design/web-vue/es/message'
import type { EquipmentApprovalResp } from '@/apis/equipment/type'
import { BusinessType, ApprovalStatus } from '@/apis/equipment/type'

defineOptions({ name: 'ApprovalAssistant' })

interface Props {
  approvalData?: EquipmentApprovalResp | null
}

interface RiskFactor {
  type: string
  title: string
  description: string
  level: 'LOW' | 'MEDIUM' | 'HIGH'
  score: number
}

interface HistoryStats {
  total: number
  approved: number
  avgTime: number
}

const props = withDefaults(defineProps<Props>(), {
  approvalData: null
})

const emit = defineEmits<{
  quickApprove: [data: EquipmentApprovalResp]
  quickReject: [data: EquipmentApprovalResp]
  manualReview: [data: EquipmentApprovalResp]
}>()

// 响应式数据
const assistantEnabled = ref(true)
const currentApproval = computed(() => props.approvalData)

// 审批建议
const recommendation = computed(() => {
  if (!currentApproval.value) return null
  
  const approval = currentApproval.value
  
  // 基于业务规则的建议逻辑
  if (approval.businessType === BusinessType.PROCUREMENT) {
    // 采购审批建议
    if (approval.purchasePrice && approval.purchasePrice > 100000) {
      return 'REJECT' // 高价值采购需要更严格审查
    }
    if (approval.applicantName && approval.applicantName.includes('测试')) {
      return 'REJECT' // 测试用户申请
    }
    return 'APPROVE'
  } else if (approval.businessType === BusinessType.BORROW) {
    // 借用审批建议
    if (approval.applyReason && approval.applyReason.length < 10) {
      return 'REJECT' // 借用原因描述不充分
    }
    return 'APPROVE'
  } else if (approval.businessType === BusinessType.RETURN) {
    // 归还审批建议
    return 'APPROVE' // 归还一般直接通过
  }
  
  return 'REVIEW' // 需要人工审查
})

// 风险评估因素
const riskFactors = computed((): RiskFactor[] => {
  if (!currentApproval.value) return []
  
  const approval = currentApproval.value
  const factors: RiskFactor[] = []
  
  // 价格风险
  if (approval.purchasePrice && approval.purchasePrice > 50000) {
    factors.push({
      type: 'PRICE',
      title: '价格风险',
      description: '采购价格较高，建议详细审查',
      level: 'MEDIUM',
      score: 70
    })
  }
  
  // 申请人风险
  if (approval.applicantName && approval.applicantName.includes('新员工')) {
    factors.push({
      type: 'APPLICANT',
      title: '申请人风险',
      description: '新员工申请，建议加强指导',
      level: 'LOW',
      score: 30
    })
  }
  
  // 设备类型风险
  if (approval.equipmentType && ['危险设备', '精密设备'].includes(approval.equipmentType)) {
    factors.push({
      type: 'EQUIPMENT',
      title: '设备类型风险',
      description: '特殊设备类型，需要专业评估',
      level: 'HIGH',
      score: 85
    })
  }
  
  // 申请时间风险
  if (approval.applyTime) {
    const applyDate = new Date(approval.applyTime)
    const now = new Date()
    const diffDays = Math.ceil((now.getTime() - applyDate.getTime()) / (1000 * 60 * 60 * 24))
    
    if (diffDays > 30) {
      factors.push({
        type: 'TIMING',
        title: '时间风险',
        description: '申请时间较长，可能影响业务',
        level: 'MEDIUM',
        score: 60
      })
    }
  }
  
  return factors
})

// 审批历史统计
const historyStats = computed((): HistoryStats => {
  // 这里应该从API获取真实的统计数据
  // 暂时使用模拟数据
  return {
    total: 156,
    approved: 89,
    avgTime: 2.5
  }
})

// 方法
const toggleAssistant = (enabled: boolean) => {
  if (enabled) {
    message.success('智能审批助手已启用')
  } else {
    message.info('智能审批助手已禁用')
  }
}

const getRecommendationClass = () => {
  switch (recommendation.value) {
    case 'APPROVE':
      return 'recommendation-approve'
    case 'REJECT':
      return 'recommendation-reject'
    default:
      return 'recommendation-review'
  }
}

const getRecommendationTitle = () => {
  switch (recommendation.value) {
    case 'APPROVE':
      return '建议通过'
    case 'REJECT':
      return '建议拒绝'
    default:
      return '需要人工审查'
  }
}

const getRecommendationReason = () => {
  if (!currentApproval.value) return ''
  
  const approval = currentApproval.value
  
  switch (recommendation.value) {
    case 'APPROVE':
      if (approval.businessType === BusinessType.PROCUREMENT) {
        return '采购申请信息完整，价格合理，建议通过'
      } else if (approval.businessType === BusinessType.BORROW) {
        return '借用申请理由充分，设备状态良好，建议通过'
      } else {
        return '申请信息完整，符合审批条件，建议通过'
      }
    case 'REJECT':
      if (approval.businessType === BusinessType.PROCUREMENT) {
        return '采购价格过高或信息不完整，建议拒绝'
      } else if (approval.businessType === BusinessType.BORROW) {
        return '借用理由不充分或设备状态不佳，建议拒绝'
      } else {
        return '申请信息不完整或不符合条件，建议拒绝'
      }
    default:
      return '申请情况复杂，需要审批人员详细审查后决定'
  }
}

const getRiskClass = (level: string) => {
  switch (level) {
    case 'HIGH':
      return 'risk-high'
    case 'MEDIUM':
      return 'risk-medium'
    default:
      return 'risk-low'
  }
}

const handleQuickApprove = () => {
  if (currentApproval.value) {
    emit('quickApprove', currentApproval.value)
    message.success('已触发快速审批通过')
  }
}

const handleQuickReject = () => {
  if (currentApproval.value) {
    emit('quickReject', currentApproval.value)
    message.success('已触发快速审批拒绝')
  }
}

const handleManualReview = () => {
  if (currentApproval.value) {
    emit('manualReview', currentApproval.value)
    message.info('请进行手动审批')
  }
}

// 监听审批数据变化
watch(() => props.approvalData, (newData) => {
  if (newData) {
    console.log('审批助手收到新的审批数据:', newData)
  }
}, { immediate: true })
</script>

<style scoped lang="scss">
.approval-assistant {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  
  .assistant-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    background: var(--color-fill-1);
    border-bottom: 1px solid var(--color-border);
    
    .header-left {
      display: flex;
      align-items: center;
      
      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
      }
    }
  }
  
  .assistant-content {
    padding: 16px;
    
    .assistant-section {
      margin-bottom: 20px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .section-header {
        display: flex;
        align-items: center;
        margin-bottom: 12px;
        font-weight: 500;
        color: var(--color-text-1);
      }
      
      .section-content {
        .recommendation-card {
          display: flex;
          align-items: center;
          padding: 16px;
          border-radius: 8px;
          border: 1px solid var(--color-border);
          
          &.recommendation-approve {
            background: var(--color-success-light-1);
            border-color: var(--color-success);
          }
          
          &.recommendation-reject {
            background: var(--color-danger-light-1);
            border-color: var(--color-danger);
          }
          
          &.recommendation-review {
            background: var(--color-warning-light-1);
            border-color: var(--color-warning);
          }
          
          .recommendation-icon {
            margin-right: 12px;
            font-size: 24px;
            
            .arco-icon {
              &.recommendation-approve & {
                color: var(--color-success);
              }
              
              &.recommendation-reject & {
                color: var(--color-danger);
              }
              
              &.recommendation-review & {
                color: var(--color-warning);
              }
            }
          }
          
          .recommendation-content {
            flex: 1;
            
            .recommendation-title {
              font-weight: 600;
              margin-bottom: 4px;
            }
            
            .recommendation-reason {
              font-size: 13px;
              color: var(--color-text-2);
              line-height: 1.4;
            }
          }
        }
        
        .risk-indicators {
          .risk-item {
            display: flex;
            align-items: center;
            padding: 12px;
            margin-bottom: 8px;
            border-radius: 6px;
            border: 1px solid var(--color-border);
            
            &:last-child {
              margin-bottom: 0;
            }
            
            &.risk-high {
              background: var(--color-danger-light-1);
              border-color: var(--color-danger);
            }
            
            &.risk-medium {
              background: var(--color-warning-light-1);
              border-color: var(--color-warning);
            }
            
            &.risk-low {
              background: var(--color-success-light-1);
              border-color: var(--color-success);
            }
            
            .risk-icon {
              margin-right: 12px;
              font-size: 18px;
            }
            
            .risk-info {
              flex: 1;
              
              .risk-title {
                font-weight: 500;
                margin-bottom: 2px;
              }
              
              .risk-description {
                font-size: 12px;
                color: var(--color-text-2);
              }
            }
            
            .risk-score {
              font-weight: 600;
              font-size: 14px;
              color: var(--color-text-1);
            }
          }
        }
        
        .quick-actions {
          display: flex;
          gap: 8px;
          flex-wrap: wrap;
        }
        
        .history-stats {
          display: flex;
          gap: 16px;
          
          .stat-item {
            text-align: center;
            flex: 1;
            
            .stat-number {
              font-size: 24px;
              font-weight: 600;
              color: var(--color-primary);
              margin-bottom: 4px;
            }
            
            .stat-label {
              font-size: 12px;
              color: var(--color-text-3);
            }
          }
        }
      }
    }
  }
  
  .assistant-disabled,
  .no-approval-data {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 16px;
    text-align: center;
    color: var(--color-text-3);
    
    p {
      margin: 0 0 16px 0;
    }
  }
}
</style>
