<template>
  <div class="order-audit-container">
    <PageTitle title="审核订单" />

    <!-- 主Tab切换 -->
    <StatusTabs v-model="activeMainTab" :tabs="mainTabs" type="line" @change="handleMainTabChange" />

    <!-- 状态Tab切换 -->
    <StatusTabs v-model="activeStatusTab" :tabs="currentStatusTabs" type="pill" />

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input v-model="queryParams.keyword" placeholder="搜索" style="width: 150px" clearable>
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-date-picker
        v-model="queryParams.dateRange"
        type="daterange"
        range-separator="—"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        style="width: 240px"
      />
    </div>

    <!-- 筛选栏 -->
    <div class="filter-bar">
      <span class="filter-label">下单部门</span>
      <el-select v-model="queryParams.department" placeholder="请选择" style="width: 100px" clearable>
        <el-option label="某某部门" value="某某部门" />
      </el-select>
      <span class="filter-label">筛选</span>
      <el-select v-model="queryParams.filter1" placeholder="请选择" style="width: 100px" clearable>
        <el-option label="条件1" value="1" />
        <el-option label="条件2" value="2" />
      </el-select>
    </div>

    <!-- 订单列表 -->
    <div class="order-list">
      <div v-for="(order, orderIndex) in orderList" :key="orderIndex" class="order-card">
        <div class="order-header">
          <el-checkbox v-model="order.checked" />
          <span class="order-time">{{ order.orderTime }}</span>
          <span class="order-info">订单号：{{ order.orderNo }}</span>
          <el-button type="primary" link class="detail-btn" @click="handleViewDetail(order)">
            订单详情 <el-icon><ArrowRight /></el-icon>
          </el-button>
        </div>

        <div class="product-list">
          <div class="product-row">
            <div class="product-cell product-info-cell">
              <div class="product-image">
                <el-image :src="order.products[0].image" fit="contain">
                  <template #error>
                    <div class="image-placeholder">
                      <el-icon :size="30" color="#ccc"><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
              </div>
              <div class="product-detail">
                <div class="product-name">{{ order.products[0].name }}</div>
                <div class="product-spec">{{ order.products[0].spec1 }} {{ order.products[0].spec2 }}</div>
                <div class="product-price">¥{{ order.products[0].price }}</div>
              </div>
              <div class="product-quantity">x{{ order.products[0].quantity }}</div>
            </div>
            <div class="product-cell amount-cell">
              <div class="amount-info">
                <span class="label">支付款</span>
                <span class="value highlight">¥{{ order.payAmount }}</span>
              </div>
              <div class="amount-info">
                <span class="label">{{ order.payMethod }}</span>
              </div>
            </div>
            <div class="product-cell status-cell">
              <span :class="['status-text', getStatusClass(order.auditStatus)]">{{ getStatusText(order.auditStatus) }}</span>
              <el-button type="primary" link size="small">查看订单轨迹</el-button>
              <template v-if="order.auditStatus !== 'pending' && activeMainTab === 'myAudit'">
                <el-button type="primary" link size="small">查看审批流</el-button>
              </template>
              <template v-if="activeMainTab === 'myApply'">
                <span v-if="order.auditStatus === 'approved'" class="result-text success">审批通过</span>
                <span v-else-if="order.auditStatus === 'rejected'" class="result-text danger">审批驳回</span>
                <span v-else-if="order.auditStatus === 'cancelled'" class="result-text danger">审批取消</span>
                <el-button type="primary" link size="small">查看审批流</el-button>
              </template>
              <el-button v-if="order.fileCount" type="primary" link size="small">
                审核文件({{ order.fileCount }})
              </el-button>
            </div>
            <div class="product-cell action-cell">
              <template v-if="activeMainTab === 'myAudit' && order.auditStatus === 'pending'">
                <el-button type="primary" link size="small" @click="handleApprove(order)">同意</el-button>
                <el-button type="danger" link size="small" @click="handleReject(order)">拒绝</el-button>
              </template>
              <template v-if="activeMainTab === 'myApply' && order.auditStatus === 'pending'">
                <el-button type="primary" link size="small" @click="handleCancelApply(order)">取消申请</el-button>
              </template>
            </div>
          </div>
        </div>
      </div>
      <el-empty v-if="orderList.length === 0" description="暂无审核订单" />
    </div>

    <!-- 审批弹窗 -->
    <el-dialog v-model="auditDialogVisible" :title="auditDialogTitle" width="450px">
      <el-form ref="auditFormRef" :model="auditForm" :rules="auditRules" label-width="80px">
        <el-form-item label="审批意见" prop="opinion">
          <el-input v-model="auditForm.opinion" type="textarea" :rows="4" placeholder="请输入审批意见" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleSubmitAudit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Search, Document, User, ArrowRight, Picture } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { PageTitle, StatusTabs } from '@/components'

const router = useRouter()

const activeMainTab = ref('myAudit')
const activeStatusTab = ref('all')
const auditDialogVisible = ref(false)
const auditDialogTitle = ref('审批')
const auditFormRef = ref()
const currentAuditOrder = ref<any>(null)
const currentAuditAction = ref('')

const mainTabs = [
  { key: 'myAudit', label: '我审批的', icon: Document },
  { key: 'myApply', label: '我申请的', icon: User }
]

const auditStatusTabs = [
  { key: 'all', label: '全部订单' },
  { key: 'pending', label: '待审批' },
  { key: 'approved', label: '已审批' }
]

const applyStatusTabs = [
  { key: 'all', label: '全部订单' },
  { key: 'pending', label: '审批中' },
  { key: 'approved', label: '审批通过' },
  { key: 'rejected', label: '审批驳回' },
  { key: 'cancelled', label: '审批取消' }
]

const currentStatusTabs = computed(() => {
  return activeMainTab.value === 'myAudit' ? auditStatusTabs : applyStatusTabs
})

const queryParams = reactive({
  keyword: '',
  dateRange: null,
  department: '',
  filter1: ''
})

const auditForm = reactive({ opinion: '' })
const auditRules = { opinion: [{ required: true, message: '请输入审批意见', trigger: 'blur' }] }

const myAuditOrders = ref([
  { orderTime: '2025/12/05 16:15:06', orderNo: '489283929283298392', payAmount: '181', payMethod: '微信支付', auditStatus: 'pending', fileCount: 1, checked: false, products: [{ id: 1, name: '清华同方超越E500台式机电脑(i3-6100/4G/1T/19.5寸)', spec1: '规格02', spec2: '规格01', price: '181', quantity: 1, image: '' }] },
  { orderTime: '2025/12/05 16:15:06', orderNo: '489283929283298393', payAmount: '181', payMethod: '微信支付', auditStatus: 'approved', fileCount: 1, checked: false, products: [{ id: 1, name: '清华同方超越E500台式机电脑(i3-6100/4G/1T/19.5寸)', spec1: '规格02', spec2: '规格01', price: '181', quantity: 1, image: '' }] },
  { orderTime: '2025/12/05 16:15:06', orderNo: '489283929283298394', payAmount: '181', payMethod: '微信支付', auditStatus: 'rejected', fileCount: 1, checked: false, products: [{ id: 1, name: '清华同方超越E500台式机电脑(i3-6100/4G/1T/19.5寸)', spec1: '规格02', spec2: '规格01', price: '181', quantity: 1, image: '' }] }
])

const myApplyOrders = ref([
  { orderTime: '2025/12/05 16:15:06', orderNo: '489283929283298392', payAmount: '181', payMethod: '微信支付', auditStatus: 'approved', fileCount: 1, checked: false, products: [{ id: 1, name: '清华同方超越E500台式机电脑(i3-6100/4G/1T/19.5寸)', spec1: '规格02', spec2: '规格01', price: '181', quantity: 1, image: '' }] },
  { orderTime: '2025/12/05 16:15:06', orderNo: '489283929283298393', payAmount: '181', payMethod: '微信支付', auditStatus: 'pending', fileCount: 1, checked: false, products: [{ id: 1, name: '清华同方超越E500台式机电脑(i3-6100/4G/1T/19.5寸)', spec1: '规格02', spec2: '规格01', price: '181', quantity: 1, image: '' }] },
  { orderTime: '2025/12/05 16:15:06', orderNo: '489283929283298394', payAmount: '181', payMethod: '微信支付', auditStatus: 'rejected', fileCount: 1, checked: false, products: [{ id: 1, name: '清华同方超越E500台式机电脑(i3-6100/4G/1T/19.5寸)', spec1: '规格02', spec2: '规格01', price: '181', quantity: 1, image: '' }] },
  { orderTime: '2025/12/05 16:15:06', orderNo: '489283929283298395', payAmount: '181', payMethod: '微信支付', auditStatus: 'cancelled', fileCount: 1, checked: false, products: [{ id: 1, name: '清华同方超越E500台式机电脑(i3-6100/4G/1T/19.5寸)', spec1: '规格02', spec2: '规格01', price: '181', quantity: 1, image: '' }] }
])

const orderList = computed(() => {
  const orders = activeMainTab.value === 'myAudit' ? myAuditOrders.value : myApplyOrders.value
  if (activeStatusTab.value === 'all') return orders
  if (activeMainTab.value === 'myAudit' && activeStatusTab.value === 'approved') {
    return orders.filter(order => order.auditStatus === 'approved' || order.auditStatus === 'rejected')
  }
  return orders.filter(order => order.auditStatus === activeStatusTab.value)
})

const handleMainTabChange = () => {
  activeStatusTab.value = 'all'
}

const getStatusText = (status: string) => {
  const map: Record<string, string> = {
    pending: activeMainTab.value === 'myAudit' ? '待审批' : '审批中',
    approved: '已完成', rejected: '已完成', cancelled: '已完成'
  }
  return map[status] || status
}

const getStatusClass = (status: string) => {
  if (status === 'approved' || status === 'rejected' || status === 'cancelled') return 'success'
  return 'warning'
}

const handleViewDetail = (order: any) => {
  router.push(`/trade/orderManage/detail/${order.orderNo}`)
}

const handleApprove = (order: any) => {
  currentAuditOrder.value = order
  currentAuditAction.value = 'approve'
  auditDialogTitle.value = '审批通过'
  auditForm.opinion = ''
  auditDialogVisible.value = true
}

const handleReject = (order: any) => {
  currentAuditOrder.value = order
  currentAuditAction.value = 'reject'
  auditDialogTitle.value = '审批拒绝'
  auditForm.opinion = ''
  auditDialogVisible.value = true
}

const handleCancelApply = (order: any) => {
  ElMessageBox.confirm('确定要取消该申请吗？', '提示', {
    confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
  }).then(() => {
    order.auditStatus = 'cancelled'
    ElMessage.success('已取消申请')
  }).catch(() => {})
}

const handleSubmitAudit = async () => {
  const valid = await auditFormRef.value?.validate()
  if (!valid) return
  if (currentAuditAction.value === 'approve') {
    currentAuditOrder.value.auditStatus = 'approved'
    ElMessage.success('审批通过')
  } else {
    currentAuditOrder.value.auditStatus = 'rejected'
    ElMessage.success('已拒绝')
  }
  auditDialogVisible.value = false
}
</script>

<style scoped lang="scss">
.order-audit-container {
  padding: 20px;
  background: #fff;
  min-height: 100%;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 15px;
}

.filter-bar {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;

  .filter-label { font-size: 14px; color: #666; }
}

.order-list {
  .order-card {
    border: 1px solid #eee;
    border-radius: 4px;
    margin-bottom: 15px;
    overflow: hidden;

    .order-header {
      display: flex;
      align-items: center;
      gap: 15px;
      padding: 12px 15px;
      background: #f9f9f9;
      border-bottom: 1px solid #eee;
      font-size: 13px;
      color: #666;

      .order-time { color: #333; }
      .detail-btn { margin-left: auto; }
    }

    .product-list {
      .product-row { display: flex; }

      .product-cell {
        padding: 15px;
        display: flex;
        flex-direction: column;
        justify-content: center;
      }

      .product-info-cell {
        flex: 1;
        flex-direction: row;
        align-items: center;
        gap: 15px;

        .product-image {
          width: 80px;
          height: 80px;
          background: #f5f5f5;
          border-radius: 4px;
          overflow: hidden;
          flex-shrink: 0;

          .el-image { width: 100%; height: 100%; }
          .image-placeholder { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; }
        }

        .product-detail {
          flex: 1;
          .product-name { font-size: 14px; color: #333; margin-bottom: 5px; line-height: 1.4; }
          .product-spec { font-size: 12px; color: #999; margin-bottom: 5px; }
          .product-price { font-size: 16px; font-weight: bold; color: #e60012; }
        }

        .product-quantity { font-size: 13px; color: #666; }
      }

      .amount-cell {
        width: 120px;
        border-left: 1px solid #f5f5f5;

        .amount-info {
          margin-bottom: 5px;
          .label { font-size: 12px; color: #999; }
          .value { font-size: 14px; color: #333; &.highlight { font-size: 16px; font-weight: bold; color: #e60012; } }
        }
      }

      .status-cell {
        width: 140px;
        border-left: 1px solid #f5f5f5;
        align-items: flex-start;
        gap: 5px;

        .status-text { font-size: 13px; font-weight: 500; &.success { color: #67c23a; } &.warning { color: #e6a23c; } }
        .result-text { font-size: 13px; font-weight: 500; &.success { color: #e60012; } &.danger { color: #e60012; } }
      }

      .action-cell {
        width: 100px;
        border-left: 1px solid #f5f5f5;
        align-items: flex-start;
        gap: 5px;
      }
    }
  }
}
</style>
