<template>
  <div class="order-page">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="search">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="85px">
          <el-form-item label="订单单号" prop="code">
            <el-input v-model="queryParams.code" placeholder="请输入订单单号" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="下单人" prop="placer">
            <el-input v-model="queryParams.placer" placeholder="请输入下单人" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="单据编号" prop="docCode">
            <el-input v-model="queryParams.docCode" placeholder="请输入单据编号" clearable @keyup.enter="handleQuery" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleQuery">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <div class="status-tabs">
        <div class="status-tabs-left">
          <div v-for="(tab, index) in statusTabs" :key="index" class="tab-item"
            :class="{ active: currentTab === tab.value }" @click="handleTabClick(tab.value)">
            {{ tab.label }}
          </div>
        </div>
        <div class="status-tabs-right">
          <span class="urgent-switch-label">加急订单</span>
          <el-switch v-model="urgentOnly" inline-prompt active-text="仅加急" inactive-text="全部"
            @change="handleUrgentSwitch" />
        </div>
      </div>

      <el-table v-loading="loading" :data="orderList" :row-class-name="urgentRowClassName">
        <el-table-column label="订单单号" align="center" prop="code" />
        <el-table-column label="单据编号" align="center" prop="docCode">
          <template #default="scope">
            <span>{{ scope.row.docCode || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="下单客户" align="center" prop="clientName">
          <template #default="scope">
            <span>{{ scope.row.clientName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="下单人" align="center" prop="placerName" />
        <el-table-column label="下单时间" align="center" prop="placeTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.placeTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="总支数" align="center" prop="totalCount" />
        <el-table-column label="订单状态" align="center" prop="status" min-width="110">
          <template #default="scope">
            <span class="status-pill" :style="statusPillStyle(scope.row.status)">
              <span class="status-pill__dot"
                :style="{ background: orderStatusJson[scope.row.status]?.color || '#909399' }"></span>
              {{ orderStatusJson[scope.row.status]?.text || '待确认' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="130" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button v-if="scope.row.urgentFlag !== 1 && checkPermi(['order:order:urgent'])" link type="danger"
              @click="handleUrgent(scope.row)">加急</el-button>
            <el-button v-hasPermi="['order:order:query']" link type="warning"
              @click="handleViewOrder(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog v-model="detailOpen" width="820px" append-to-body class="order-detail-dialog">
      <template #header>
        <div class="detail-dialog-header">
          <span class="detail-dialog-title">订单详情</span>
          <span v-if="detailOrder" class="detail-code-badge">#{{ detailOrder.code }}</span>
        </div>
      </template>

      <template v-if="detailOrder">
        <div v-if="detailOrder.urgentFlag === 1" class="urgent-banner">
          <span class="urgent-banner__icon">🔥</span>
          <span class="urgent-banner__text">此订单已标记为加急，请优先处理</span>
        </div>

        <div class="detail-info-card" :class="{ 'is-urgent': detailOrder.urgentFlag === 1 }">
          <div class="detail-card-title">
            <span class="detail-card-title__icon">📋</span>
            <span>基本信息</span>
          </div>
          <div class="detail-info-grid">
            <div class="info-item">
              <span class="info-label">订单单号</span>
              <span class="info-value">{{ detailOrder.code }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">单据编号</span>
              <span class="info-value">{{ detailOrder.docCode || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">下单人</span>
              <span class="info-value">{{ detailOrder.placerName }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">下单客户</span>
              <span class="info-value">{{ detailOrder.clientName || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">订单状态</span>
              <span class="info-value">
                <span class="status-pill" :style="statusPillStyle(detailOrder.status)">
                  <span class="status-pill__dot"
                    :style="{ background: orderStatusJson[detailOrder.status]?.color || '#909399' }"></span>
                  {{ orderStatusJson[detailOrder.status]?.text || '待确认' }}
                </span>
              </span>
            </div>
            <div class="info-item">
              <span class="info-label">总支数</span>
              <span class="info-value info-value--highlight">{{ detailOrder.totalCount }} 支</span>
            </div>
            <div class="info-item">
              <span class="info-label">下单时间</span>
              <span class="info-value">{{ parseTime(detailOrder.placeTime) }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">创建时间</span>
              <span class="info-value">{{ parseTime(detailOrder.createTime) }}</span>
            </div>
          </div>
        </div>

        <div class="detail-info-card">
          <div class="detail-card-title">
            <span class="detail-card-title__icon">📦</span>
            <span>订单明细</span>
            <span class="detail-card-title__count">{{ detailOrder.details?.length || 0 }} 项</span>
          </div>
          <div class="detail-scroll" v-if="detailOrder.details && detailOrder.details.length > 0">
            <div class="detail-spec-card" v-for="(detail, dIdx) in detailOrder.details" :key="dIdx">
              <div class="spec-card-header">
                <span class="spec-no">#{{ dIdx + 1 }}</span>
                <span class="spec-model">{{ detail.modelNum || '未知型号' }}</span>
              </div>
              <div class="spec-info-grid">
                <div class="spec-item">
                  <span class="spec-label">型号名称</span>
                  <span class="spec-value">{{ detail.modelName || '铝型材主料' }}</span>
                </div>
                <div class="spec-item">
                  <span class="spec-label">单据编号</span>
                  <span class="spec-value">{{ detail.docCode || '-' }}</span>
                </div>
                <div class="spec-item">
                  <span class="spec-label">项目号</span>
                  <span class="spec-value">{{ detail.itemNo || '-' }}</span>
                </div>
                <div class="spec-item">
                  <span class="spec-label">型材材质</span>
                  <span class="spec-value">{{ detail.material || '6063-T5' }}</span>
                </div>
                <div class="spec-item">
                  <span class="spec-label">表面处理</span>
                  <span class="spec-value">{{ detail.surfaceName || '无' }}</span>
                </div>
                <div class="spec-item">
                  <span class="spec-label">包装方式</span>
                  <span class="spec-value">{{ detail.packName || '普通包装' }}</span>
                </div>
                <div class="spec-item">
                  <span class="spec-label">订单长度</span>
                  <span class="spec-value">{{ formatNum(detail.length) }} mm</span>
                </div>
                <div class="spec-item">
                  <span class="spec-label">型材壁厚</span>
                  <span class="spec-value">{{ formatNum(detail.wallThickness, '1.2') }} mm</span>
                </div>
                <div class="spec-item spec-item--full">
                  <span class="spec-label">需求支数</span>
                  <span class="spec-value spec-value--count">{{ detail.count || 0 }} 支</span>
                </div>
              </div>
              <div class="spec-remark" v-if="detail.remark">
                <span class="spec-remark__icon">💬</span>
                <span>{{ detail.remark }}</span>
              </div>
            </div>
          </div>
          <el-empty v-else description="暂无明细数据" :image-size="60" />
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Order">
import { listOrder, getOrder, markUrgentOrder } from "@/api/erp/order";
import orderStatusJson from "@/json/orderStatus.json";
import { checkPermi } from '@/utils/permission';

/** @Author: Antigravity */

const { proxy } = getCurrentInstance();

const orderList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const detailOpen = ref(false);
const detailOrder = ref(null);
const currentTab = ref(undefined);
const urgentOnly = ref(false);

const statusTabs = [
  { label: '全部', value: undefined },
  { label: '待确认', value: 0 },
  { label: '已确认', value: 1 },
  { label: '已审核', value: 2 },
  { label: '已签批', value: 3 },
  { label: '挤压完成', value: 4 },
  { label: '生产完成', value: 5 },
  { label: '已取消', value: 6 }
];

const queryFormRef = ref();

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    code: undefined,
    placer: undefined,
    isConfirmed: undefined,
    docCode: undefined
  }
});

const { queryParams } = toRefs(data);

/** 查询订单列表 */
function getList() {
  loading.value = true;
  queryParams.value.status = currentTab.value;
  queryParams.value.isConfirmed = undefined;
  queryParams.value.urgentFlag = urgentOnly.value ? 1 : undefined;
  listOrder(queryParams.value).then(response => {
    orderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  queryParams.value.status = currentTab.value;
  queryParams.value.isConfirmed = undefined;
  getList();
}

/** 状态标签点击 */
function handleTabClick(value) {
  currentTab.value = value;
  handleQuery();
}

/** 加急订单开关切换 */
function handleUrgentSwitch() {
  handleQuery();
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields();
  currentTab.value = undefined;
  urgentOnly.value = false;
  handleQuery();
}

/** 查看订单详情 */
function handleViewOrder(row) {
  detailOpen.value = true;
  detailOrder.value = null;
  getOrder(row.rowId).then(res => {
    detailOrder.value = res.data;
  }).catch(() => {
    proxy.$modal.msgError("获取订单详情失败");
  });
}

/** 加急订单 */
function handleUrgent(row) {
  proxy.$modal.confirm(`确认要将订单【${row.code}】标记为加急吗？`).then(() => {
    markUrgentOrder(row.rowId).then(() => {
      proxy.$modal.msgSuccess("标记加急成功");
      getList();
    }).catch(() => {
      proxy.$modal.msgError("标记加急失败");
    });
  }).catch(() => { });
}

/** 加急订单行高亮 */
const urgentRowClassName = ({ row }) => {
  if (row.urgentFlag === 1) return 'row-urgent';
  return '';
};

/** 状态标签 pill 样式 */
const statusPillStyle = (status) => {
  const color = orderStatusJson[status]?.color || '#909399';
  return {
    '--status-color': color,
    color: color
  };
};

/** 格式化数值，匹配小程序端的 toFixed(4) 显示 */
function formatNum(val, fallback = '0') {
  if (val === null || val === undefined || val === '') return fallback;
  const num = Number(val);
  return isNaN(num) ? fallback : num.toFixed(4);
}

getList();
</script>

<style scoped lang="scss">
@use '@/assets/styles/page-common.scss' as *;

.order-page {
  @include page-common-list;
}

/* ========== 状态筛选标签栏 ========== */
.status-tabs {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 0;
}

.status-tabs-left {
  display: flex;
  gap: 2px;
}

.status-tabs-right {
  display: flex;
  align-items: center;
  gap: 8px;
  padding-bottom: 2px;
}

.urgent-switch-label {
  font-size: 13px;
  color: #909399;
  white-space: nowrap;
}

.tab-item {
  position: relative;
  padding: 10px 20px;
  font-size: 14px;
  color: #606266;
  cursor: pointer;
  transition: color 0.25s ease;
  user-select: none;
}

.tab-item::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 50%;
  transform: translateX(-50%) scaleX(0);
  width: 100%;
  height: 2px;
  background: #409eff;
  transition: transform 0.25s ease;
}

.tab-item:hover {
  color: #409eff;
}

.tab-item.active {
  color: #409eff;
  font-weight: 600;
}

.tab-item.active::after {
  transform: translateX(-50%) scaleX(1);
}

/* ========== 详情弹窗样式 ========== */
.order-detail-dialog :deep(.el-dialog) {
  display: flex;
  flex-direction: column;
  max-height: 90vh;
}

.order-detail-dialog :deep(.el-dialog__header) {
  padding: 20px 24px 16px;
  margin-right: 0;
  border-bottom: 1px solid #f1f5f9;
  flex-shrink: 0;
}

.order-detail-dialog :deep(.el-dialog__body) {
  padding: 20px 24px;
  overflow-y: auto;
  flex: 1;
  min-height: 0;
}

.detail-dialog-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.detail-dialog-title {
  font-size: 18px;
  font-weight: 700;
  color: #1a202c;
}

.detail-code-badge {
  padding: 2px 10px;
  border-radius: 6px;
  font-size: 13px;
  font-weight: 500;
  color: #4f46e5;
  background: #eef2ff;
}

/* 加急横幅 */
.urgent-banner {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 16px;
  margin-bottom: 16px;
  border-radius: 8px;
  background: linear-gradient(135deg, #fff5f5 0%, #fff0f0 100%);
  border: 1px solid #fecaca;
}

.urgent-banner__icon {
  font-size: 18px;
}

.urgent-banner__text {
  font-size: 13px;
  font-weight: 600;
  color: #dc2626;
}

/* 信息卡片 */
.detail-info-card {
  background: #fff;
  border: 1px solid #edf2f7;
  border-radius: 12px;
  padding: 20px 24px;
  margin-bottom: 16px;
  transition: border-color 0.2s;
}

.detail-info-card.is-urgent {
  border-color: #fecaca;
  box-shadow: 0 0 0 1px #fecaca;
}

.detail-card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f7f8fc;
  font-size: 15px;
  font-weight: 600;
  color: #1a202c;
}

.detail-card-title__icon {
  font-size: 16px;
}

.detail-card-title__count {
  margin-left: auto;
  font-size: 12px;
  font-weight: 500;
  color: #a0aec0;
  background: #f7f8fc;
  padding: 2px 10px;
  border-radius: 10px;
}

/* 信息网格 */
.detail-info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px 32px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.info-label {
  font-size: 12px;
  color: #a0aec0;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.3px;
}

.info-value {
  font-size: 14px;
  color: #2d3748;
  font-weight: 500;
}

.info-value--highlight {
  font-weight: 700;
  color: #4f46e5;
}

/* 明细滚动区 */
.detail-scroll {
  padding-right: 4px;
}

/* 明细规格卡片 */
.detail-spec-card {
  background: #fafbfc;
  border: 1px solid #edf2f7;
  border-radius: 10px;
  padding: 16px 20px;
  margin-bottom: 10px;
  transition: border-color 0.2s, box-shadow 0.2s;
}

.detail-spec-card:hover {
  border-color: #e2e8f0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.spec-card-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 14px;
  padding-bottom: 10px;
  border-bottom: 1px dashed #e2e8f0;
}

.spec-no {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  border-radius: 6px;
  background: #4f46e5;
  color: #fff;
  font-size: 12px;
  font-weight: 600;
  flex-shrink: 0;
}

.spec-model {
  font-size: 14px;
  font-weight: 600;
  color: #1a202c;
}

.spec-info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px 24px;
}

.spec-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 4px 0;
}

.spec-item--full {
  grid-column: span 2;
  margin-top: 4px;
  padding-top: 8px;
  border-top: 1px dashed #e2e8f0;
}

.spec-label {
  font-size: 12px;
  color: #8899aa;
}

.spec-value {
  font-size: 13px;
  color: #2d3748;
  font-weight: 500;
}

.spec-value--count {
  font-size: 15px;
  font-weight: 700;
  color: #ff3b30;
}

.spec-remark {
  display: flex;
  align-items: flex-start;
  gap: 6px;
  margin-top: 10px;
  padding: 8px 12px;
  background: #fff;
  border-radius: 6px;
  font-size: 12px;
  color: #718096;
  line-height: 1.5;
}

.spec-remark__icon {
  flex-shrink: 0;
  font-size: 13px;
}

/* ========== 加急订单行高亮 ========== */
:deep(.row-urgent > td) {
  background: #fff5f5 !important;
}

:deep(.row-urgent > td:first-child) {
  box-shadow: inset 3px 0 0 #ff3b30;
}

:deep(.row-urgent:hover > td) {
  background: #ffefef !important;
}

/* ========== 状态标签 pill ========== */
.status-pill {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 3px 12px;
  border-radius: 20px;
  font-size: 13px;
  font-weight: 500;
  background: color-mix(in srgb, var(--status-color) 10%, #fff);
  border: 1px solid color-mix(in srgb, var(--status-color) 20%, #fff);
  white-space: nowrap;
}

.status-pill__dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  flex-shrink: 0;
}
</style>