<template>
  <div class="app-container">
    <!-- 左右布局容器 -->
    <el-row :gutter="20">
      <!-- 左侧：使用klp-list组件（占6列） -->
      <el-col :span="6" style="display: table-cell;">
        <!-- 搜索表单 - 精简搜索项 -->
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px"
          class="mb-4">
          <el-row :gutter="10">
            <el-col :span="16">
              <el-input v-model="queryParams.orderCode" placeholder="请输入订单编号" clearable @change="handleQuery" />
            </el-col>
            <el-col :span="8">
              <el-button type="primary" plain icon="Plus" size="small" @click="handleAdd" class="w-full">新增订单</el-button>
            </el-col>
          </el-row>
        </el-form>

        <!-- klp-list组件 -->
        <klp-list :list-data="orderList" :model-value="selectedIds" title-field="orderCode" list-key="orderId"
          title-label="订单编号" :loading="loading" @item-click="handleRowClick">
          <!-- 自定义操作按钮 -->
          <template #actions="{ item }">
            <!-- 删除按钮 -->
            <el-button size="small" type="text" style="color: red" icon="Delete"
              @click.stop="handleDelete(item)"></el-button>
          </template>
        </klp-list>

        <!-- 分页组件 -->
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="getList" class="mt-4" layout="total, pager" />
      </el-col>

      <!-- 右侧：详情区（占18列） -->
      <el-col :span="18">
        <div>
          <!-- 未选中行时显示提示 -->
          <div v-if="!selectedOrderId" class="empty-tip">
            <el-empty description="请从左侧选择一个订单查看详情" />
          </div>

          <!-- 选中行时显示Tab详情 -->
          <div v-else>
            <!-- Tab容器 -->
            <el-tabs v-loading="loading" v-model="activeTab" type="border-card" class="mt-2">
              <!-- 订单信息Tab -->
              <el-tab-pane label="订单信息" name="orderInfo">
                <el-form ref="detailForm" :model="form" :rules="rules" label-width="80px" size="small" class="mt-4">
                  <el-form-item label="订单ID" prop="orderId">
                    <el-input style="width: 60%;" v-model="form.orderId" placeholder="无" disabled>
                      <el-button style="padding: -1;" slot="append" size="small" type="text" icon="Document-copy"
                        @click.stop="copyOrderId(form.orderId)"></el-button>
                    </el-input>
                  </el-form-item>

                  <el-form-item label="订单编号" prop="orderCode">
                    <el-input style="width: 60%;" v-model="form.orderCode" placeholder="无" disabled />
                  </el-form-item>

                  <el-form-item label="客户名称" prop="customerId">
                    <customer-select style="width: 60%;" v-model="form.customerId" />
                  </el-form-item>

                  <el-form-item label="销售经理" prop="salesManager">
                    <el-input style="width: 60%;" v-model="form.salesManager" placeholder="无" />
                  </el-form-item>

                  <el-form-item label="含税金额" prop="taxAmount">
                    <el-input-number style="width: 60%;" :controls="false" v-model="form.taxAmount" placeholder="0.00"
                      precision="2" :min="0" />
                  </el-form-item>

                  <el-form-item label="无税金额" prop="noTaxAmount">
                    <el-input-number style="width: 60%;" :controls="false" v-model="form.noTaxAmount" placeholder="0.00"
                      precision="2" :min="0" />
                  </el-form-item>

                  <el-form-item label="订单状态" prop="orderStatus">
                    <el-select style="width: 60%;" v-model="form.orderStatus" @change="handleOrderStatusChange"
                      size="small">
                      <el-option v-for="item in order_status" :key="item.value" :label="item.label"
                        :value="parseInt(item.value)" />
                    </el-select>
                  </el-form-item>

                  <el-form-item label="备注" prop="remark">
                    <el-input style="width: 60%;" v-model="form.remark" placeholder="无" type="textarea" rows="4" />
                  </el-form-item>

                  <!-- 更新按钮 -->
                  <el-form-item class="text-right">
                    <el-button type="primary" size="small" :loading="buttonLoading"
                      @click="submitDetailForm">更新订单信息</el-button>
                  </el-form-item>
                </el-form>
              </el-tab-pane>

              <!-- 订单详情Tab -->
              <el-tab-pane label="订单详情" name="orderDetail">
                <div class="mt-4">
                  <OrderDetailPanel :orderId="selectedOrderId" />
                </div>
              </el-tab-pane>

              <el-tab-pane label="退换货" name="returnExchange">
                <div class="mt-4"> 
                  <ReturnExchange :orderId="selectedOrderId" />
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 新增订单弹窗 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="addForm" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单编号" prop="orderCode">
              <el-input v-model="form.orderCode" placeholder="请输入订单编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerId">
              <customer-select v-model="form.customerId" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售经理" prop="salesManager">
              <el-input v-model="form.salesManager" style="width: 100%;" placeholder="请输入销售经理" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="含税金额" prop="taxAmount">
              <el-input-number :controls="false" style="width: 100%;" v-model="form.taxAmount" placeholder="请输入含税金额"
                precision="2" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="无税金额" prop="noTaxAmount">
              <el-input-number :controls="false" v-model="form.noTaxAmount" placeholder="请输入无税金额" precision="2"
                :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitAddForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getOrder, delOrder, addOrder, updateOrder, listOrder } from "@/api/oms/order";
import OrderDetailPanel from './detail.vue';
import { EOrderStatus } from "@/utils/enums";
import CustomerSelect from '@/components/CustomerSelect/index.vue';
import klpList from "@/components/GearList/index.vue";
import { getCurrentInstance } from "vue";
import ReturnExchange from './return.vue';

export default {
  name: "Order",
  components: { OrderDetailPanel, CustomerSelect, klpList, ReturnExchange },
  props: {
    tradeType: {
      type: String,
      required: true
    }
  },
  setup() {
    const { proxy } = getCurrentInstance();
    const { order_status } = proxy.useDict("order_status");

    console.log(order_status);

    return {
      order_status
    }
  },
  computed: {
    orderQueryStatus() {
      return 0
    }
  },
  data() {
    return {
      // 订单状态枚举
      EOrderStatus,
      // 按钮loading
      buttonLoading: false,
      // 列表加载遮罩
      loading: true,
      // 选中的订单ID集合
      selectedIds: {},
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单列表数据
      orderList: [],
      // 新增弹窗标题
      title: "",
      // 新增弹窗显示状态
      open: false,
      // 当前选中的订单ID（控制右侧详情显示）
      selectedOrderId: null,
      // 右侧激活的Tab
      activeTab: "orderDetail",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderCode: undefined,
        customerId: undefined,
        salesManager: undefined,
        tradeType: this.tradeType
      },
      // 表单参数
      form: {
        orderId: undefined,
        orderCode: undefined,
        customerId: undefined,
        salesManager: undefined,
        tradeType: this.tradeType,
        remark: undefined,
        delFlag: undefined,
        createTime: undefined,
        createBy: undefined,
        updateTime: undefined,
        updateBy: undefined,
        taxAmount: 0,
        noTaxAmount: 0,
      },
      // 表单校验规则
      rules: {
        orderCode: [
          { required: true, message: "请输入订单编号", trigger: "blur" }
        ],
        customerId: [
          { required: true, message: "请选择客户名称", trigger: "change" }
        ],
        salesManager: [
          { required: true, message: "请输入销售经理", trigger: "blur" }
        ],
        taxAmount: [
          { required: true, message: "请输入含税金额", trigger: "blur" }
        ],
        noTaxAmount: [
          { required: true, message: "请输入无税金额", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.queryParams.orderStatus = this.orderQueryStatus;
    this.getList();
  },
  methods: {
    /** 查询订单列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;

        // 重置选中状态
        this.selectedIds = {};

        // 如果之前选中的订单不在列表中了，清空选中状态
        if (this.selectedOrderId && !this.orderList.some(item => item.orderId === this.selectedOrderId)) {
          this.selectedOrderId = null;
        }

        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    /** 点击列表项加载详情 */
    handleRowClick(item) {
      this.selectedOrderId = item.orderId;
      this.loadOrderDetail(item.orderId);
    },

    /** 加载订单详情 */
    loadOrderDetail(orderId) {
      this.buttonLoading = true;
      getOrder(orderId).then(response => {
        this.form = { ...response.data };
        this.form.taxAmount = this.form.taxAmount || 0;
        this.form.noTaxAmount = this.form.noTaxAmount || 0;
      }).catch(() => {
        this.$modal.msgError("加载订单详情失败");
      }).finally(() => {
        this.buttonLoading = false;
      });
    },

    /** 订单状态变更 */
    handleOrderStatusChange() {
      updateOrder(this.form).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.getList();
      }).catch(() => {
        this.$modal.msgError("修改失败");
        this.loadOrderDetail(this.selectedOrderId); // 失败后重新加载原数据
      });
    },

    /** 取消新增 */
    cancel() {
      this.open = false;
      this.resetForm("addForm");
      this.form = {
        orderId: undefined,
        orderCode: undefined,
        customerId: undefined,
        salesManager: undefined,
        orderStatus: this.orderQueryStatus,
        tradeType: this.tradeType,
        remark: undefined,
        taxAmount: 0,
        noTaxAmount: 0,
      };
    },

    /** 搜索 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置搜索 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.orderStatus = this.orderQueryStatus;
      this.handleQuery();
    },

    /** 重置表单 */
    resetForm(formRef) {
      if (this.$refs[formRef]) {
        this.$refs[formRef].resetFields();
      }
    },

    /** 复制订单ID */
    copyOrderId(orderId) {
      if (navigator.clipboard) {
        navigator.clipboard.writeText(orderId).then(() => {
          this.$modal.msgSuccess("复制成功");
        }).catch(() => {
          this.$modal.msgError("复制失败，请手动复制");
        });
      } else {
        this.$modal.msgError("浏览器不支持复制功能");
      }
    },

    /** 新增订单 */
    handleAdd() {
      this.resetForm("addForm");
      this.form = {
        orderId: undefined,
        orderCode: undefined,
        customerId: undefined,
        salesManager: undefined,
        orderStatus: this.orderQueryStatus,
        remark: undefined,
        taxAmount: 0,
        noTaxAmount: 0,
      };
      this.open = true;
      this.title = "添加订单";
    },

    /** 提交新增表单 */
    submitAddForm() {
      this.$refs["addForm"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          addOrder(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          }).catch(() => {
            this.$modal.msgError("新增失败");
          }).finally(() => {
            this.buttonLoading = false;
          });
        }
      });
    },

    /** 提交详情更新表单 */
    submitDetailForm() {
      this.$refs["detailForm"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          updateOrder(this.form).then(response => {
            this.$modal.msgSuccess("更新成功");
            this.getList();
          }).catch(() => {
            this.$modal.msgError("更新失败");
          }).finally(() => {
            this.buttonLoading = false;
          });
        }
      });
    },

    /** 删除订单 */
    handleDelete(row) {
      this.$modal.confirm(`是否确认删除订单"${row.orderCode}"？`).then(() => {
        this.loading = true;
        return delOrder([row.orderId]);
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
        // 如果删除的是当前选中的订单，清空详情
        if (this.selectedOrderId === row.orderId) {
          this.selectedOrderId = null;
        }
        this.getList();
      }).catch(() => {
        this.$modal.msgError("删除失败");
      }).finally(() => {
        this.loading = false;
      });
    },

    /** 预订单确认 */
    handleStartProduction(row) {
      this.$modal.confirm(`是否确认将订单"${row.orderCode}"转为正式订单？`).then(() => {
        return updateOrder({
          orderId: row.orderId,
          orderStatus: 1
        });
      }).then(response => {
        this.$modal.msgSuccess("已转化为正式订单");
        if (this.selectedOrderId === row.orderId) {
          this.selectedOrderId = null;
        }
        this.getList();
      }).catch(() => {
        this.$modal.msgError("转化失败");
      });
    }
  }
};
</script>

<style scoped>
/* 页面容器样式 */
.page-container {
  height: 100%;
  padding: 16px;
}

/* 空提示样式 */
.empty-tip {
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 表单样式调整 */
.el-form-item {
  margin-bottom: 16px;
}

::v-deep .el-input-group__append,
::v-deep .el-input-group__prepend {
  width: 20px !important;
  box-sizing: border-box !important;
  padding: 0 10px !important;
  text-align: center !important;
}
</style>
