<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="订单单号" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入订单单号" clearable style="width: 200px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="下单人" prop="placer">
        <el-input v-model="queryParams.placer" placeholder="请输入下单人" clearable style="width: 200px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="订单状态" clearable style="width: 200px">
          <el-option label="已撤销" :value="-1" />
          <el-option label="待审核" :value="0" />
          <el-option label="已驳回" :value="1" />
          <el-option label="待签批" :value="2" />
          <el-option label="生产中" :value="3" />
          <el-option label="已完成" :value="4" />
        </el-select>
      </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>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['erp:order:add']">新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList">
      <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-button link type="primary" icon="Stamp" @click="handleAudit(scope.row)" v-if="scope.row.status === 0"
            v-hasPermi="['erp:order:audit']">审核</el-button>
          <el-button link type="primary" icon="Timer" @click="handleViewAuditHistory(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-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="auditHistoryOpen" width="600px" append-to-body>
      <el-timeline v-if="auditHistoryList.length > 0">
        <el-timeline-item
          v-for="(item, index) in auditHistoryList"
          :key="index"
          hide-timestamp
          :color="item.auditResult === 1 ? '#67c23a' : '#f56c6c'"
        >
          <div class="audit-card" :class="item.auditResult === 1 ? 'card-pass' : 'card-reject'">
            <div class="audit-card-header">
              <el-tag :type="item.auditResult === 1 ? 'success' : 'danger'" effect="dark" size="small">
                {{ item.auditResult === 1 ? '通过' : '驳回' }}
              </el-tag>
              <span class="audit-card-auditor">
                <el-icon><User /></el-icon> {{ item.auditorName || '未知' }}
              </span>
            </div>
            <div v-if="item.rejectReason" class="audit-card-reason">
              <span class="reason-label">驳回理由</span>
              <span class="reason-text">{{ item.rejectReason }}</span>
            </div>
            <div class="audit-card-time">
              <el-icon><Clock /></el-icon> {{ parseTime(item.auditTime) }}
            </div>
          </div>
        </el-timeline-item>
      </el-timeline>
      <el-empty v-else description="暂无审核记录" />
    </el-dialog>

    <!-- 订单审核对话框 -->
    <el-dialog title="订单审核" v-model="auditOpen" width="500px" append-to-body>
      <el-form ref="auditRef" :model="auditForm" :rules="auditRules" label-width="80px">
        <el-form-item label="审核结果" prop="auditResult">
          <el-radio-group v-model="auditForm.auditResult">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="驳回原因" prop="rejectReason" v-if="auditForm.auditResult === 2">
          <el-input v-model="auditForm.rejectReason" type="textarea" placeholder="请输入驳回原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAudit">确 定</el-button>
          <el-button @click="auditOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Order">
import { listOrder, getOrder, addOrder, auditOrder } from "@/api/erp/order";
import { listModel } from "@/api/erp/model";
import { listColor } from "@/api/erp/color";
import { getAuditHistory } from "@/api/erp/orderAudit";
import { User, Clock } 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 auditOpen = ref(false);
const auditHistoryOpen = ref(false);
const auditHistoryList = 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" }]
  },
  auditForm: {},
  auditRules: {
    auditResult: [{ required: true, message: "请选择审核结果", trigger: "change" }],
    rejectReason: [{ required: true, message: "请输入驳回原因", trigger: "blur" }]
  }
});

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

/** 查询订单列表 */
function getList() {
  loading.ref = true;
  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;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

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

/** 审核按钮操作 */
function handleAudit(row) {
  auditForm.value = {
    orderId: row.rowId,
    auditResult: 1,
    rejectReason: undefined
  };
  auditOpen.value = true;
}

/** 查看审核记录 */
function handleViewAuditHistory(row) {
  auditHistoryList.value = [];
  auditHistoryOpen.value = true;
  getAuditHistory(row.rowId).then(res => {
    auditHistoryList.value = res.data || [];
  }).catch(() => {
    proxy.$modal.msgError("获取审核记录失败");
  });
}

/** 提交审核 */
function submitAudit() {
  proxy.$refs["auditRef"].validate(valid => {
    if (valid) {
      auditOrder(auditForm.value).then(response => {
        proxy.$modal.msgSuccess("审核成功");
        auditOpen.value = false;
        getList();
      });
    }
  });
}

/** 提交按钮 */
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);
}

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

<style scoped>
.audit-card {
  background: #fff;
  border-radius: 8px;
  padding: 16px 20px;
  border-left: 4px solid #ebeef5;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: box-shadow 0.2s;
}
.audit-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}
.audit-card.card-pass {
  border-left-color: #67c23a;
}
.audit-card.card-reject {
  border-left-color: #f56c6c;
}

.audit-card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}
.audit-card-auditor {
  font-size: 14px;
  color: #606266;
  display: flex;
  align-items: center;
  gap: 4px;
}

.audit-card-reason {
  background: #fef0f0;
  border-radius: 6px;
  padding: 10px 14px;
  margin-bottom: 12px;
}
.reason-label {
  font-size: 12px;
  color: #f56c6c;
  font-weight: 500;
  display: block;
  margin-bottom: 4px;
}
.reason-text {
  font-size: 13px;
  color: #c03639;
  line-height: 1.5;
}

.audit-card-time {
  font-size: 13px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 4px;
}
</style>
