<script setup lang="ts">
import { ref } from 'vue'
import { Info, Download, Link as LinkIcon, X, ArrowLeft, Check, AlertTriangle } from 'lucide-vue-next'
import { useRouter } from 'vue-router'

const router = useRouter()

interface ScrapDevice {
  sn: string; model: string; scrapDate: string; reason: string; sourceOrder: string
  status: '待审批' | '审批中' | '已审批' | '已驳回' | '回收中' | '已回收'
  applicant: string; approver: string; residualValue: number
  recyclableParts: string[]
}

const scrapDevices = ref<ScrapDevice[]>([
  { sn: 'GD30-2023-001234', model: 'GD-30 Supreme', scrapDate: '2024-03-01', status: '已回收', sourceOrder: 'WO-2024-0001', reason: '主板损坏无法修复', applicant: '李工', approver: '张主管', residualValue: 500, recyclableParts: ['采集板 AC20240308002', '测控板 CT20240308003'] },
  { sn: 'GT20-2023-000567', model: 'GT-20', scrapDate: '2024-03-05', status: '已审批', sourceOrder: 'WO-2024-0025', reason: '多个核心部件损坏', applicant: '王工', approver: '张主管', residualValue: 300, recyclableParts: ['电源模块 PS20240308004'] },
  { sn: 'GD30-2023-000890', model: 'GD-30 Supreme', scrapDate: '2024-03-08', status: '待审批', sourceOrder: 'WO-2024-0048', reason: '维修成本超过设备价值', applicant: '李工', approver: '', residualValue: 800, recyclableParts: ['采集板 AC20240309001', '发射板 TX20240309002', '升压板 BO20240309003'] },
  { sn: 'GD30-2023-001100', model: 'GD-30 Supreme', scrapDate: '2024-03-10', status: '审批中', sourceOrder: 'WO-2024-0052', reason: '设备老化严重', applicant: '张工', approver: '', residualValue: 200, recyclableParts: [] },
  { sn: 'GT20-2023-001200', model: 'GT-20', scrapDate: '2024-03-12', status: '已驳回', sourceOrder: 'WO-2024-0055', reason: '通信模块故障', applicant: '王工', approver: '张主管', residualValue: 0, recyclableParts: [] },
])

// Drawers
const showDetailDrawer = ref(false)
const showApprovalDrawer = ref(false)
const showRecycleDrawer = ref(false)
const currentDevice = ref<ScrapDevice | null>(null)
const approvalComment = ref('')
const recycleNote = ref('')
const recycleChecked = ref<Set<string>>(new Set())

const openDetail = (d: ScrapDevice) => { currentDevice.value = d; showDetailDrawer.value = true }
const openApproval = (d: ScrapDevice) => { currentDevice.value = d; approvalComment.value = ''; showApprovalDrawer.value = true }
const openRecycle = (d: ScrapDevice) => {
  currentDevice.value = d; recycleNote.value = ''
  recycleChecked.value = new Set()
  showRecycleDrawer.value = true
}

const getStatusStyle = (s: ScrapDevice['status']) => {
  const map: Record<string, any> = {
    '待审批': { backgroundColor: '#FFFBE6', color: '#FAAD14', border: '1px solid #FFE58F' },
    '审批中': { backgroundColor: '#eef5f0', color: '#4a7c59', border: '1px solid #a3c4ad' },
    '已审批': { backgroundColor: '#F6FFED', color: '#52C41A', border: '1px solid #B7EB8F' },
    '已驳回': { backgroundColor: '#FFF1F0', color: '#FF4D4F', border: '1px solid #FFCCC7' },
    '回收中': { backgroundColor: '#eef5f0', color: '#4a7c59', border: '1px solid #a3c4ad' },
    '已回收': { backgroundColor: '#F6FFED', color: '#52C41A', border: '1px solid #B7EB8F' },
  }
  return map[s]
}

const statCounts = {
  total: scrapDevices.value.length,
  pending: scrapDevices.value.filter(d => d.status === '待审批' || d.status === '审批中').length,
  approved: scrapDevices.value.filter(d => d.status === '已审批').length,
  recycled: scrapDevices.value.filter(d => d.status === '已回收').length,
}

const flowSteps = [
  { label: '申请报废', desc: '维修工单发起' },
  { label: '主管审批', desc: '审核报废原因' },
  { label: '物料检测', desc: '检测可回收物料' },
  { label: '回收入库', desc: '物料回收登记' },
  { label: '报废完成', desc: '设备注销' },
]
</script>

<template>
  <div class="p-6">
    <!-- Header -->
    <div class="mb-6">
      <div class="flex items-center justify-between mb-2">
        <h2 class="text-2xl font-semibold">报废管理</h2>
        <button class="px-4 py-2 rounded flex items-center gap-2" style="border: 1px solid #D9D9D9; color: rgba(0,0,0,0.85)">
          <Download :size="16" /> 导出
        </button>
      </div>
      <p class="text-sm" style="color: rgba(0,0,0,0.45)">管理报废设备审批与物料回收</p>
    </div>

    <!-- Approval Flow -->
    <div class="bg-white p-6 rounded-lg mb-6" style="box-shadow: 0 1px 2px rgba(0,0,0,0.05)">
      <h3 class="text-base font-semibold mb-4">报废审批流程</h3>
      <div class="flex items-center justify-between">
        <div v-for="(step, i) in flowSteps" :key="i" class="flex items-center gap-3 flex-1">
          <div class="text-center flex-1">
            <div class="w-10 h-10 rounded-full flex items-center justify-center mx-auto mb-2" :style="{ backgroundColor: '#eef5f0', border: '2px solid #4a7c59', color: '#4a7c59', fontWeight: 600, fontSize: '14px' }">{{ i + 1 }}</div>
            <div class="text-sm font-medium">{{ step.label }}</div>
            <div class="text-xs" style="color: rgba(0,0,0,0.45)">{{ step.desc }}</div>
          </div>
          <div v-if="i < flowSteps.length - 1" style="color: #D9D9D9; font-size: 18px; flex-shrink: 0">&#8594;</div>
        </div>
      </div>
    </div>

    <!-- Stats -->
    <div class="grid grid-cols-4 gap-6 mb-6">
      <div class="bg-white p-6 rounded-lg" style="box-shadow: 0 1px 2px rgba(0,0,0,0.05)">
        <div class="text-sm mb-2" style="color: rgba(0,0,0,0.45)">报废总数</div>
        <div class="text-3xl font-semibold">{{ statCounts.total }}</div>
      </div>
      <div class="bg-white p-6 rounded-lg" style="box-shadow: 0 1px 2px rgba(0,0,0,0.05)">
        <div class="text-sm mb-2" style="color: rgba(0,0,0,0.45)">待审批</div>
        <div class="text-3xl font-semibold" style="color: #FAAD14">{{ statCounts.pending }}</div>
      </div>
      <div class="bg-white p-6 rounded-lg" style="box-shadow: 0 1px 2px rgba(0,0,0,0.05)">
        <div class="text-sm mb-2" style="color: rgba(0,0,0,0.45)">已审批待回收</div>
        <div class="text-3xl font-semibold" style="color: #4a7c59">{{ statCounts.approved }}</div>
      </div>
      <div class="bg-white p-6 rounded-lg" style="box-shadow: 0 1px 2px rgba(0,0,0,0.05)">
        <div class="text-sm mb-2" style="color: rgba(0,0,0,0.45)">已回收</div>
        <div class="text-3xl font-semibold" style="color: #52C41A">{{ statCounts.recycled }}</div>
      </div>
    </div>

    <!-- Filter -->
    <div class="bg-white p-6 rounded-lg mb-6" style="box-shadow: 0 1px 2px rgba(0,0,0,0.05)">
      <div class="grid grid-cols-4 gap-4">
        <div>
          <label class="block text-sm mb-2" style="color: rgba(0,0,0,0.65)">设备SN号</label>
          <input type="text" class="w-full px-3 py-2 border rounded" style="border-color: #D9D9D9" placeholder="搜索SN" />
        </div>
        <div>
          <label class="block text-sm mb-2" style="color: rgba(0,0,0,0.65)">状态</label>
          <select class="w-full px-3 py-2 border rounded" style="border-color: #D9D9D9; background-color: #fff">
            <option>全部</option><option>待审批</option><option>审批中</option><option>已审批</option><option>已驳回</option><option>回收中</option><option>已回收</option>
          </select>
        </div>
        <div>
          <label class="block text-sm mb-2" style="color: rgba(0,0,0,0.65)">报废日期</label>
          <input type="date" class="w-full px-3 py-2 border rounded" style="border-color: #D9D9D9" />
        </div>
        <div class="flex items-end">
          <button class="w-full px-4 py-2 rounded text-white" style="background-color: #4a7c59">查询</button>
        </div>
      </div>
    </div>

    <!-- Table -->
    <div class="bg-white rounded-lg mb-6" style="box-shadow: 0 1px 2px rgba(0,0,0,0.05)">
      <div class="p-6 border-b" style="border-color: #F0F0F0">
        <h3 class="text-lg font-semibold">报废设备列表</h3>
      </div>
      <div class="overflow-x-auto">
        <table class="w-full">
          <thead style="background-color: #FAFAFA">
            <tr>
              <th class="px-5 py-3 text-left text-sm font-medium" style="color: rgba(0,0,0,0.85)">设备SN</th>
              <th class="px-5 py-3 text-left text-sm font-medium" style="color: rgba(0,0,0,0.85)">型号</th>
              <th class="px-5 py-3 text-left text-sm font-medium" style="color: rgba(0,0,0,0.85)">报废原因</th>
              <th class="px-5 py-3 text-left text-sm font-medium" style="color: rgba(0,0,0,0.85)">申请人</th>
              <th class="px-5 py-3 text-left text-sm font-medium" style="color: rgba(0,0,0,0.85)">状态</th>
              <th class="px-5 py-3 text-left text-sm font-medium" style="color: rgba(0,0,0,0.85)">来源工单</th>
              <th class="px-5 py-3 text-left text-sm font-medium" style="color: rgba(0,0,0,0.85)">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(d, i) in scrapDevices" :key="i" class="border-b" style="border-color: #F0F0F0">
              <td class="px-5 py-4 text-sm">{{ d.sn }}</td>
              <td class="px-5 py-4 text-sm" style="color: rgba(0,0,0,0.65)">{{ d.model }}</td>
              <td class="px-5 py-4 text-sm" style="color: rgba(0,0,0,0.65)">{{ d.reason }}</td>
              <td class="px-5 py-4 text-sm" style="color: rgba(0,0,0,0.65)">{{ d.applicant }}</td>
              <td class="px-5 py-4"><span class="px-2 py-0.5 rounded text-xs" :style="getStatusStyle(d.status)">{{ d.status }}</span></td>
              <td class="px-5 py-4">
                <router-link :to="'/repair/' + d.sourceOrder" class="text-sm flex items-center gap-1" style="color: #4a7c59">
                  <LinkIcon :size="14" /> {{ d.sourceOrder }}
                </router-link>
              </td>
              <td class="px-5 py-4">
                <div class="flex items-center gap-3 text-sm">
                  <button style="color: #4a7c59" @click="openDetail(d)">详情</button>
                  <button v-if="d.status === '待审批' || d.status === '审批中'" style="color: #4a7c59" @click="openApproval(d)">审批</button>
                  <button v-if="d.status === '已审批'" style="color: #52C41A" @click="openRecycle(d)">回收入库</button>
                  <button v-if="d.status === '已驳回'" style="color: #FA8C16">重新申请</button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- Detail Drawer -->
    <div v-if="showDetailDrawer && currentDevice" class="fixed inset-0 z-50 flex justify-end" style="background-color: rgba(0,0,0,0.45)" @click.self="showDetailDrawer = false">
      <div class="bg-white w-[520px] h-full flex flex-col" style="box-shadow: -4px 0 12px rgba(0,0,0,0.1)">
        <div class="flex items-center gap-3 p-5 border-b" style="border-color: #F0F0F0">
          <button @click="showDetailDrawer = false" class="p-1 rounded hover:bg-gray-100" style="color: rgba(0,0,0,0.65)"><ArrowLeft :size="18" /></button>
          <h3 class="text-lg font-semibold">报废详情</h3>
          <span class="px-2 py-0.5 rounded text-xs" :style="getStatusStyle(currentDevice.status)">{{ currentDevice.status }}</span>
        </div>
        <div class="flex-1 overflow-y-auto p-6 space-y-5">
          <div class="p-5 rounded-lg" style="background-color: #FAFAFA; border: 1px solid #F0F0F0">
            <h4 class="text-base font-semibold mb-3">设备信息</h4>
            <div class="space-y-2 text-sm" style="color: rgba(0,0,0,0.65)">
              <div>设备SN：{{ currentDevice.sn }}</div>
              <div>设备型号：{{ currentDevice.model }}</div>
              <div>报废日期：{{ currentDevice.scrapDate }}</div>
              <div>报废原因：{{ currentDevice.reason }}</div>
              <div>残值评估：{{ currentDevice.residualValue }} 元</div>
            </div>
          </div>
          <div class="p-5 rounded-lg" style="background-color: #FAFAFA; border: 1px solid #F0F0F0">
            <h4 class="text-base font-semibold mb-3">审批信息</h4>
            <div class="space-y-2 text-sm" style="color: rgba(0,0,0,0.65)">
              <div>申请人：{{ currentDevice.applicant }}</div>
              <div>审批人：{{ currentDevice.approver || '待分配' }}</div>
              <div>来源工单：{{ currentDevice.sourceOrder }}</div>
            </div>
          </div>
          <div v-if="currentDevice.recyclableParts.length" class="p-5 rounded-lg" style="background-color: #FAFAFA; border: 1px solid #F0F0F0">
            <h4 class="text-base font-semibold mb-3">可回收物料</h4>
            <div class="flex flex-wrap gap-2">
              <span v-for="p in currentDevice.recyclableParts" :key="p" class="px-3 py-1 rounded text-xs" style="background-color: #eef5f0; color: #4a7c59; border: 1px solid #a3c4ad">{{ p }}</span>
            </div>
          </div>
          <!-- Approval Timeline -->
          <div class="p-5 rounded-lg" style="background-color: #FAFAFA; border: 1px solid #F0F0F0">
            <h4 class="text-base font-semibold mb-3">审批记录</h4>
            <div class="space-y-3">
              <div class="flex items-start gap-3">
                <div class="w-6 h-6 rounded-full flex items-center justify-center flex-shrink-0" style="background-color: #F6FFED; border: 1px solid #B7EB8F"><Check :size="12" style="color: #52C41A" /></div>
                <div class="text-sm" style="color: rgba(0,0,0,0.65)">
                  <div>{{ currentDevice.applicant }} 提交报废申请</div>
                  <div class="text-xs" style="color: rgba(0,0,0,0.35)">{{ currentDevice.scrapDate }}</div>
                </div>
              </div>
              <div v-if="currentDevice.status !== '待审批'" class="flex items-start gap-3">
                <div class="w-6 h-6 rounded-full flex items-center justify-center flex-shrink-0" :style="currentDevice.status === '已驳回' ? { backgroundColor: '#FFF1F0', border: '1px solid #FFCCC7' } : { backgroundColor: '#F6FFED', border: '1px solid #B7EB8F' }">
                  <X v-if="currentDevice.status === '已驳回'" :size="12" style="color: #FF4D4F" />
                  <Check v-else :size="12" style="color: #52C41A" />
                </div>
                <div class="text-sm" style="color: rgba(0,0,0,0.65)">
                  <div>{{ currentDevice.approver || '审批中' }} {{ currentDevice.status === '已驳回' ? '驳回申请' : '审批通过' }}</div>
                </div>
              </div>
              <div v-if="currentDevice.status === '已回收'" class="flex items-start gap-3">
                <div class="w-6 h-6 rounded-full flex items-center justify-center flex-shrink-0" style="background-color: #F6FFED; border: 1px solid #B7EB8F"><Check :size="12" style="color: #52C41A" /></div>
                <div class="text-sm" style="color: rgba(0,0,0,0.65)">物料回收完成，设备已注销</div>
              </div>
            </div>
          </div>
        </div>
        <div class="flex items-center justify-center gap-3 p-5 border-t" style="border-color: #F0F0F0">
          <button class="px-6 py-2 rounded text-sm" style="border: 1px solid #D9D9D9; color: rgba(0,0,0,0.85)" @click="showDetailDrawer = false">关闭</button>
          <button v-if="currentDevice.status === '待审批' || currentDevice.status === '审批中'" class="px-6 py-2 rounded text-white text-sm" style="background-color: #4a7c59" @click="showDetailDrawer = false; openApproval(currentDevice)">去审批</button>
          <button v-if="currentDevice.status === '已审批'" class="px-6 py-2 rounded text-white text-sm" style="background-color: #52C41A" @click="showDetailDrawer = false; openRecycle(currentDevice)">回收入库</button>
        </div>
      </div>
    </div>

    <!-- Approval Drawer -->
    <div v-if="showApprovalDrawer && currentDevice" class="fixed inset-0 z-50 flex justify-end" style="background-color: rgba(0,0,0,0.45)" @click.self="showApprovalDrawer = false">
      <div class="bg-white w-[480px] h-full flex flex-col" style="box-shadow: -4px 0 12px rgba(0,0,0,0.1)">
        <div class="flex items-center gap-3 p-5 border-b" style="border-color: #F0F0F0">
          <button @click="showApprovalDrawer = false" class="p-1 rounded hover:bg-gray-100" style="color: rgba(0,0,0,0.65)"><ArrowLeft :size="18" /></button>
          <h3 class="text-lg font-semibold">报废审批</h3>
        </div>
        <div class="flex-1 overflow-y-auto p-6 space-y-5">
          <!-- Warning -->
          <div class="p-4 rounded-lg flex items-start gap-3" style="background-color: #FFF1F0; border: 1px solid #FFCCC7">
            <AlertTriangle :size="18" style="color: #FF4D4F; flex-shrink: 0; margin-top: 2px" />
            <div class="text-sm" style="color: #CF1322">报废操作不可逆，审批通过后设备将进入回收流程，请仔细核实信息。</div>
          </div>
          <!-- Device summary -->
          <div class="p-5 rounded-lg" style="background-color: #FAFAFA; border: 1px solid #F0F0F0">
            <h4 class="text-sm font-semibold mb-3">报废设备</h4>
            <div class="space-y-1 text-sm" style="color: rgba(0,0,0,0.65)">
              <div>{{ currentDevice.sn }} · {{ currentDevice.model }}</div>
              <div>报废原因：{{ currentDevice.reason }}</div>
              <div>残值评估：{{ currentDevice.residualValue }} 元</div>
              <div>申请人：{{ currentDevice.applicant }}</div>
            </div>
          </div>
          <!-- Recyclable parts -->
          <div v-if="currentDevice.recyclableParts.length" class="p-5 rounded-lg" style="background-color: #FAFAFA; border: 1px solid #F0F0F0">
            <h4 class="text-sm font-semibold mb-3">可回收物料（{{ currentDevice.recyclableParts.length }}件）</h4>
            <div class="space-y-1 text-sm" style="color: rgba(0,0,0,0.65)">
              <div v-for="p in currentDevice.recyclableParts" :key="p">{{ p }}</div>
            </div>
          </div>
          <!-- Comment -->
          <div>
            <label class="block text-sm font-medium mb-2">审批意见</label>
            <textarea v-model="approvalComment" class="w-full px-3 py-2 border rounded text-sm" style="border-color: #D9D9D9; min-height: 80px; resize: vertical" placeholder="请输入审批意见..."></textarea>
          </div>
        </div>
        <div class="flex items-center justify-center gap-3 p-5 border-t" style="border-color: #F0F0F0">
          <button class="px-6 py-2 rounded text-sm" style="border: 1px solid #D9D9D9; color: rgba(0,0,0,0.85)" @click="showApprovalDrawer = false">取消</button>
          <button class="px-6 py-2 rounded text-sm" style="border: 1px solid #FF4D4F; color: #FF4D4F" @click="showApprovalDrawer = false">驳回</button>
          <button class="px-6 py-2 rounded text-white text-sm" style="background-color: #4a7c59" @click="showApprovalDrawer = false">审批通过</button>
        </div>
      </div>
    </div>

    <!-- Recycle Drawer -->
    <div v-if="showRecycleDrawer && currentDevice" class="fixed inset-0 z-50 flex justify-end" style="background-color: rgba(0,0,0,0.45)" @click.self="showRecycleDrawer = false">
      <div class="bg-white w-[480px] h-full flex flex-col" style="box-shadow: -4px 0 12px rgba(0,0,0,0.1)">
        <div class="flex items-center gap-3 p-5 border-b" style="border-color: #F0F0F0">
          <button @click="showRecycleDrawer = false" class="p-1 rounded hover:bg-gray-100" style="color: rgba(0,0,0,0.65)"><ArrowLeft :size="18" /></button>
          <h3 class="text-lg font-semibold">物料回收入库</h3>
        </div>
        <div class="flex-1 overflow-y-auto p-6 space-y-5">
          <div class="p-5 rounded-lg" style="background-color: #FAFAFA; border: 1px solid #F0F0F0">
            <h4 class="text-sm font-semibold mb-2">报废设备</h4>
            <div class="text-sm" style="color: rgba(0,0,0,0.65)">{{ currentDevice.sn }} · {{ currentDevice.model }}</div>
          </div>
          <!-- Recyclable parts checklist -->
          <div>
            <h4 class="text-sm font-semibold mb-3">物料检测与回收</h4>
            <div v-if="currentDevice.recyclableParts.length === 0" class="text-sm" style="color: rgba(0,0,0,0.45)">无可回收物料</div>
            <div v-else class="space-y-2">
              <label v-for="p in currentDevice.recyclableParts" :key="p" class="flex items-center gap-3 p-3 rounded cursor-pointer text-sm" :style="{ backgroundColor: recycleChecked.has(p) ? '#F6FFED' : '#FAFAFA', border: recycleChecked.has(p) ? '1px solid #B7EB8F' : '1px solid #F0F0F0' }">
                <input type="checkbox" :checked="recycleChecked.has(p)" @change="recycleChecked.has(p) ? recycleChecked.delete(p) : recycleChecked.add(p)" class="w-4 h-4" style="accent-color: #4a7c59" />
                <span>{{ p }}</span>
                <span v-if="recycleChecked.has(p)" class="ml-auto text-xs" style="color: #52C41A">已检测</span>
              </label>
            </div>
          </div>
          <div>
            <label class="block text-sm font-medium mb-2">回收备注</label>
            <textarea v-model="recycleNote" class="w-full px-3 py-2 border rounded text-sm" style="border-color: #D9D9D9; min-height: 70px; resize: vertical" placeholder="请输入回收备注..."></textarea>
          </div>
        </div>
        <div class="flex items-center justify-center gap-3 p-5 border-t" style="border-color: #F0F0F0">
          <button class="px-6 py-2 rounded text-sm" style="border: 1px solid #D9D9D9; color: rgba(0,0,0,0.85)" @click="showRecycleDrawer = false">取消</button>
          <button class="px-6 py-2 rounded text-white text-sm" style="background-color: #52C41A" @click="showRecycleDrawer = false; router.push('/registration')">确认回收入库</button>
        </div>
      </div>
    </div>
  </div>
</template>
