<template>
  <div class="p-2">
    <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>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @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
          v-for="(tab, index) in statusTabs"
          :key="index"
          class="tab-item"
          :class="{ active: currentTab === tab.value }"
          @click="handleTabClick(tab.value)"
        >
          {{ tab.label }}
        </div>
      </div>

      <el-table v-loading="loading" :data="orderList" border>
        <el-table-column label="订单单号" align="center" prop="code" />
        <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">
          <template #default="scope">
            <el-tag v-if="scope.row.status === -1" type="info">已撤销</el-tag>
            <el-tag v-else-if="scope.row.status === 0" type="warning">待审核</el-tag>
            <el-tag v-else-if="scope.row.status === 1" type="danger">已驳回</el-tag>
            <el-tag v-else-if="scope.row.status === 2" type="primary">待签批</el-tag>
            <el-tag v-else-if="scope.row.status === 3" type="info">生产中</el-tag>
            <el-tag v-else-if="scope.row.status === 4" type="success">已完成</el-tag>
            <el-tag v-else type="info">未知</el-tag>
          </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" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看详情" placement="top">
              <el-button v-hasPermi="['order:order:query']" link type="primary" icon="View"
                @click="handleViewOrder(scope.row)" />
            </el-tooltip>
          </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 :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="orderRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="订单单号" prop="code">
              <el-input v-model="form.code" placeholder="请输入订单单号" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下单人" prop="placer">
              <el-input v-model="form.placer" placeholder="请输入下单人" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="center">订单明细信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddErpOrderDetail">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteErpOrderDetail">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="form.details" :row-class-name="rowErpOrderDetailIndex"
          @selection-change="handleErpOrderDetailSelectionChange" ref="erpOrderDetailTable">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50" />
          <el-table-column label="型材" prop="modelId" width="200">
            <template #default="scope">
              <el-select v-model="scope.row.modelId" filterable placeholder="请选择型材">
                <el-option v-for="item in modelOptions" :key="item.rowId" :label="item.name" :value="item.rowId" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="颜色" prop="colorId" width="200">
            <template #default="scope">
              <el-select v-model="scope.row.colorId" filterable placeholder="请选择颜色">
                <el-option v-for="item in colorOptions" :key="item.rowId" :label="item.name" :value="item.rowId" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="数量" prop="count" width="150">
            <template #default="scope">
              <el-input-number v-model="scope.row.count" :min="1" controls-position="right" placeholder="请输入数量" />
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark">
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 订单详情对话框 -->
    <el-dialog title="订单详情" v-model="detailOpen" width="800px" append-to-body>
      <template v-if="detailOrder">
        <div class="section-title">订单信息</div>
        <el-descriptions :column="2" border size="small">
          <el-descriptions-item label="订单单号" :span="2">{{ detailOrder.code }}</el-descriptions-item>
          <el-descriptions-item label="下单人">{{ detailOrder.placerName }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag v-if="detailOrder.status === -1" type="info">已撤销</el-tag>
            <el-tag v-else-if="detailOrder.status === 0" type="warning">待审核</el-tag>
            <el-tag v-else-if="detailOrder.status === 1" type="danger">已驳回</el-tag>
            <el-tag v-else-if="detailOrder.status === 2" type="primary">待签批</el-tag>
            <el-tag v-else-if="detailOrder.status === 3" type="info">生产中</el-tag>
            <el-tag v-else-if="detailOrder.status === 4" type="success">已完成</el-tag>
            <el-tag v-else type="info">未知</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="下单时间">{{ parseTime(detailOrder.placeTime) }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ parseTime(detailOrder.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="总支数">{{ detailOrder.totalCount }}</el-descriptions-item>
        </el-descriptions>

        <div class="section-title" style="margin-top: 20px">订单明细</div>
        <div class="detail-scroll" v-if="detailOrder.details && detailOrder.details.length > 0">
          <div class="detail-card" v-for="(detail, dIdx) in detailOrder.details" :key="dIdx">
            <div class="detail-card-head">规格清单 #{{ dIdx + 1 }}</div>
            <el-descriptions :column="2" border size="small">
              <el-descriptions-item label="产品型号" :span="2">{{ detail.modelNum || '未知型号' }}</el-descriptions-item>
              <el-descriptions-item label="型号名称" :span="2">{{ detail.modelName || '铝型材主料' }}</el-descriptions-item>
              <el-descriptions-item label="型材材质">{{ detail.material || '6063-T5' }}</el-descriptions-item>
              <el-descriptions-item label="需求支数">
                <span class="count-red">{{ detail.count || 0 }} 支</span>
              </el-descriptions-item>
              <el-descriptions-item label="表面处理">{{ detail.surfaceName || '无' }}</el-descriptions-item>
              <el-descriptions-item label="包装方式">{{ detail.packName || '普通包装' }}</el-descriptions-item>
              <el-descriptions-item label="订单长度">{{ formatNum(detail.length) }} mm</el-descriptions-item>
              <el-descriptions-item label="型材壁厚">{{ formatNum(detail.wallThickness, '1.2') }} mm</el-descriptions-item>
            </el-descriptions>
            <div class="detail-remark" v-if="detail.remark">
              <span class="remark-label">备注：</span>{{ detail.remark }}
            </div>
          </div>
        </div>
        <el-empty v-else description="暂无明细" :image-size="60" />
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Order">
import { listOrder, getOrder, addOrder } from "@/api/erp/order";
import { listModel } from "@/api/erp/model";
import { listColor } from "@/api/erp/color";
import { View } from '@element-plus/icons-vue';

/** @Author: Antigravity */

const { proxy } = getCurrentInstance();

const orderList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");
const detailOpen = ref(false);
const detailOrder = ref(null);
const currentTab = ref(undefined);
const statusTabs = [
  { label: '全部', value: undefined },
  { label: '已撤销', value: -1 },
  { label: '待审核', value: 0 },
  { label: '已驳回', value: 1 },
  { label: '待签批', value: 2 },
  { label: '生产中', value: 3 },
  { label: '已完成', value: 4 }
];

const queryFormRef = ref();

const modelOptions = ref([]);
const colorOptions = ref([]);
const checkedErpOrderDetail = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    code: undefined,
    placer: undefined,
    status: undefined
  },
  rules: {
    placer: [{ required: true, message: "下单人不能为空", trigger: "blur" }]
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询订单列表 */
function getList() {
  loading.ref = true;
  queryParams.value.status = currentTab.value;
  listOrder(queryParams.value).then(response => {
    orderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询型材和颜色选项 */
function getOptions() {
  listModel({}).then(res => {
    modelOptions.value = res.data;
  });
  listColor().then(res => {
    colorOptions.value = res.data;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    rowId: undefined,
    code: undefined,
    placer: undefined,
    status: 0,
    details: []
  };
  proxy.resetForm("orderRef");
}

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

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

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

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加订单";
}

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

/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      addOrder(form.value).then(response => {
        proxy.$modal.msgSuccess("新增成功");
        open.value = false;
        getList();
      });
    }
  });
}


/** 订单明细序号 */
function rowErpOrderDetailIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 订单明细添加按钮操作 */
function handleAddErpOrderDetail() {
  let obj = {};
  obj.modelId = "";
  obj.colorId = "";
  obj.count = 1;
  obj.remark = "";
  form.value.details.push(obj);
}

/** 订单明细删除按钮操作 */
function handleDeleteErpOrderDetail() {
  if (checkedErpOrderDetail.value.length == 0) {
    proxy.$modal.msgError("请选择要删除的订单明细数据");
  } else {
    const details = form.value.details;
    const checkedDetails = checkedErpOrderDetail.value;
    form.value.details = details.filter(function (item) {
      return checkedDetails.indexOf(item.index) == -1;
    });
  }
}

/** 复选框选中数据 */
function handleErpOrderDetailSelectionChange(selection) {
  checkedErpOrderDetail.value = selection.map(item => item.index);
}

/** 格式化数值，匹配小程序端的 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);
}

getOptions();
getList();
</script>

<style scoped>


/* ========== 状态筛选标签栏 ========== */
.status-tabs {
  display: flex;
  gap: 2px;
  margin-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 0;
}
.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);
}

/* ========== 详情弹框样式 ========== */
.section-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
  padding-left: 10px;
  border-left: 3px solid #C1001C;
}
.detail-scroll {
  max-height: 420px;
  overflow-y: auto;
  padding-right: 2px;
}
.detail-card {
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  padding: 14px;
  margin-bottom: 12px;
}
.detail-card-head {
  font-size: 13px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 10px;
}
.count-red {
  color: #ff3b30;
  font-weight: 600;
}
.detail-remark {
  margin-top: 8px;
  padding: 6px 10px;
  background: #fafafa;
  border-radius: 4px;
  font-size: 12px;
  color: #606266;
}
.remark-label {
  color: #909399;
}
</style>
