<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="5" style="border-right: 1px solid #e4e7ed;">
        <div style="font-weight: 900;">订单列表</div>
        <div style="display: flex; align-items: center; gap: 5px; margin-top: 10px;">
          <!-- 主搜索和添加 -->
          <el-input style="flex: 1;" prefix-icon="el-icon-search" placeholder="输入订单编号搜索"
            v-model="queryParams.orderCode"></el-input>
          <el-button icon="el-icon-search" @click="toggleQuery"></el-button>
          <el-button type="primary" icon="el-icon-plus" style="margin-left: 0;" @click="handleAdd"
            v-hasPermi="['crm:order:add']"></el-button>
        </div>
        <div v-show="showQuery"
          style="display: flex; align-items: center; gap: 5px; margin-top: 10px; flex-wrap: wrap;">
          <!-- 查询区，通过上方的查询按钮控制显示隐藏 -->
          <!-- 客户行业和客户等级的下拉选 -->
          <!-- <el-select style="width: 100px;" v-model="queryParams.customerId" placeholder="客户" clearable>
            <el-option v-for="item in dict.type.customer_industry" :key="item.value" :label="item.label"
              :value="item.value" />
          </el-select> -->
          <el-input style="width: 100px;" v-model="queryParams.salesman" placeholder="销售员" clearable />
          <el-select style="width: 100px;" v-model="queryParams.orderStatus" placeholder="订单状态" clearable>
            <el-option v-for="(value, key) in ORDER_STATUS" :key="value" :label="key" :value="value" />
          </el-select>
          <!-- <el-select style="width: 100px;" v-model="queryParams.financeStatus" placeholder="财务状态" clearable>
            <el-option v-for="item in dict.type.finance_status" :key="item.value" :label="item.label"
              :value="item.value" />
          </el-select> -->
        </div>
        <div>
          <!-- 列表区域 -->
          <KLPList :listData="orderList" listKey="orderId" :loading="orderLoading" field1="orderCode" field2="salesman"
            field4="companyName" field5="contactPerson"  @item-click="handleOrderClick">
            <template slot="actions" slot-scope="{ item }">
              <el-button type="danger" size="mini" @click="handleDelete(item)" icon="el-icon-delete"
                v-hasPermi="['crm:order:add']"></el-button>
            </template>
          </KLPList>
        </div>
      </el-col>

      <el-col :span="19">
        <el-empty description="选择订单查看更多信息" v-if="!form.orderId"></el-empty>
        <el-tabs v-model="activeTab" type="border-card" v-else>
          <el-tab-pane label="订单详情" name="detail">
            <div class="order-detail" v-if="activeTab === 'detail'">
              <!-- 订单详情内容 -->
              <el-descriptions :column="2" :border="true" title="订单基本信息" style="margin-bottom: 20px;">
                <el-descriptions-item label="订单编号">{{ form.orderCode }}</el-descriptions-item>
                <el-descriptions-item label="销售员">{{ form.salesman }}</el-descriptions-item>
                <el-descriptions-item label="交货日期">{{ form.deliveryDate }}</el-descriptions-item>
                <el-descriptions-item label="合同号">{{ form.contractCode }}</el-descriptions-item>
                <el-descriptions-item label="客户公司">{{ form.companyName }}</el-descriptions-item>
                <el-descriptions-item label="联系人">{{ form.contactPerson }}</el-descriptions-item>
                <el-descriptions-item label="联系电话">{{ form.contactWay }}</el-descriptions-item>
                <el-descriptions-item label="备注" :span="2">{{ form.remark }}</el-descriptions-item>
              </el-descriptions>

              <el-descriptions :border="true" title="订单明细" />
              <OrderDetail :orderId="currentOrder.orderId" :editable="false" />
            </div>
          </el-tab-pane>
          <el-tab-pane label="订单编辑" name="edit" v-hasPermi="['crm:order:edit']">
            <div class="order-detail" v-if="activeTab === 'edit'">
              <OrderEdit :initValue="currentOrder" :customerList="customerList" @save="handleOrderSave" />
              <el-descriptions title="订单明细" />
              <OrderDetail :orderId="currentOrder.orderId" />
            </div>
          </el-tab-pane>
          <el-tab-pane label="财务状态" name="finance" v-hasPermi="['crm:order:finance']">
            <div class="order-finance" v-if="activeTab === 'finance'">
              <!-- 财务状态内容 -->
              <ReceiveTable :order="currentOrder" />
            </div>
          </el-tab-pane>
          <el-tab-pane label="订单异议" name="dispute" v-hasPermi="['crm:order:objection']">
            <div class="order-dispute" v-if="activeTab === 'dispute'">
              <!-- 订单异议内容 -->
              <OrderObjection :order="currentOrder" />
            </div>
          </el-tab-pane>
          <el-tab-pane label="操作记录" name="record" v-hasPermi="['crm:order:record']">
            <div class="order-record" v-if="activeTab === 'record'">
              <!-- 操作记录内容 -->
              <OrderRecord :orderId="currentOrder.orderId" />
            </div>
          </el-tab-pane>
          <!-- <el-tab-pane label="钢卷追溯" name="trace">
            <div class="order-trace" v-if="activeTab === 'trace'">
            </div>
          </el-tab-pane> -->
        </el-tabs>
      </el-col>
    </el-row>

    <!-- 添加或修改正式订单主对话框 -->
    <el-dialog title="添加正式订单" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单编号" prop="orderCode">
          <el-input v-model="form.orderCode" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="客户" prop="customerId">
          <!-- <el-input v-model="form.customerId" placeholder="请输入客户" /> -->
          <el-select v-model="form.customerId" placeholder="请选择客户">
            <el-option v-for="item in customerList" :key="item.customerId" :label="item.customerCode"
              :value="item.customerId" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单总金额" prop="orderAmount">
          <el-input v-model="form.orderAmount" placeholder="请输入订单总金额" />
        </el-form-item>
        <el-form-item label="销售员" prop="salesman">
          <el-input v-model="form.salesman" placeholder="请输入销售员" />
        </el-form-item>
        <el-form-item label="合同号" prop="contractCode">
          <el-input v-model="form.contractCode" placeholder="请输入合同号" />
        </el-form-item>
        <el-form-item label="交货日期" prop="deliveryDate">
          <el-date-picker clearable v-model="form.deliveryDate" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择交货日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import KLPList from '@/components/KLPUI/KLPList/index.vue'
import { listOrder, delOrder } from "@/api/crm/order";
import { listCustomer } from "@/api/crm/customer";
import { ORDER_STATUS, ORDER_TYPE } from '../js/enum'
import { ORDER_ACTIONS, actions } from '../js/actions'
import OrderDetail from '../components/OrderDetail.vue';
import OrderEdit from '../components/OrderEdit.vue';
import OrderObjection from '../components/OrderObjection.vue';
import ReceiveTable from '../components/ReceiveTable.vue';
import OrderRecord from '../components/OrderRecord.vue';

export default {
  name: 'OrderPage',
  components: {
    KLPList,
    OrderDetail,
    OrderEdit,
    OrderObjection,
    ReceiveTable,
    OrderRecord
  },
  dicts: ['customer_level', 'customer_industry'],
  data() {
    return {
      ORDER_STATUS,
      ORDER_TYPE,
      showQuery: false,
      queryParams: {
        orderCode: '',
        customerId: '',
        salesman: '',
        orderStatus: '',
        orderType: ORDER_TYPE['正式订单'],
        financeStatus: ''
      },
      activeTab: 'detail',
      currentOrder: {},
      buttonLoading: false,
      orderList: [],
      orderLoading: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      open: false,
      customerList: [],
    }
  },
  created() {
    this.getList()
    this.getCustomerList()
  },
  methods: {
    toggleQuery() {
      this.showQuery = !this.showQuery
    },
    /** 查询客户列表 */
    getCustomerList() {
      listCustomer({ pageNum: 1, pageSize: 1000 }).then(response => {
        this.customerList = response.rows;
      });
    },
    /** 订单列表项点击事件 */
    handleOrderClick(order) {
      this.currentOrder = order;
      this.form = {
        ...order
      }
      this.activeTab = 'detail';
      console.log('点击订单:', order)
    },
    /** 查询正式订单主列表 */
    getList() {
      this.orderLoading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows || [];
        this.orderLoading = false;
      }).catch(error => {
        console.error('获取正式订单主列表失败:', error)
        this.$message.error('获取数据失败')
        this.orderList = []
        this.orderLoading = false
      })
    },

    // 表单重置
    reset() {
      this.form = {
        orderId: undefined,
        orderCode: undefined,
        orderType: ORDER_TYPE['正式订单'],
        customerId: undefined,
        orderAmount: undefined,
        salesman: undefined,
        deliveryDate: undefined,
        preOrderStatus: undefined,
        auditUser: undefined,
        auditTime: undefined,
        orderStatus: undefined,
        financeStatus: undefined,
        unpaidAmount: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined
      };
      this.resetForm("form");
    },

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

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
    },

    /** 删除按钮操作 */
    handleDelete(order) {
      this.$confirm('确认删除订单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delOrder(order.orderId).then(response => {
          this.$modal.msgSuccess("删除成功");
          this.getList();
        });
      });
    },
    handleOrderSave(form) {
      this.form = form;
      console.log('保存订单:', form, this)
      const that = this;
      that.submitForm()
    },
    /** 提交按钮 */
    async submitForm() {
      if (this.form.orderId) {
        actions[ORDER_ACTIONS.updateOrder].handler(this.form).then(_ => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        }).finally(() => {
          this.buttonLoading = false;
        });
        return;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          actions[ORDER_ACTIONS.createOrder].handler(this.form).then(_ => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          }).finally(() => {
            this.buttonLoading = false;
          });
        }
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
  }
}
</script>