<template>
  <div>
    <!-- 客户编号和保存按钮 -->
    <div class="save-btn-container">
      <input class="customer-code-input" type="text" v-model="form.orderCode" placeholder="请输入订单编号" />
      <el-button class="save-btn" type="primary" @click="manualSave">
        保存变更
      </el-button>
    </div>

    <el-form label-width="80px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="customerId">
            <el-select v-model="form.customerId" placeholder="请选择客户名称">
              <el-option v-for="item in customerList" :key="item.customerId" :label="item.customerCode"
                :value="item.customerId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="订单金额" prop="orderAmount">
            <el-input v-model="form.orderAmount" placeholder="请输入订单金额"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="销售员" prop="salesman">
            <el-select v-model="form.salesman" placeholder="请选择销售员">
              <el-option v-for="item in dict.type.wip_pack_saleman" :key="item.value" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <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-col>

        <el-col :span="12">
          <el-form-item label="订单状态" prop="orderStatus">
            <el-select v-model="form.orderStatus" placeholder="请选择订单状态">
              <el-option v-for="(value, label) in ORDER_STATUS" :key="value" :label="label"
                :value="value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="合同号" prop="contractCode">
            <el-select v-model="form.contractId" placeholder="请选择合同号" filterable clearable @change="handleContractChange">
              <el-option v-for="item in contractList" :key="item.contractId" :label="item.contractNo"
                :value="item.contractId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>


        <el-col :span="24">
          <el-form-item label="附件" prop="annexFiles">
            <file-upload v-model="form.annexFiles" />
          </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="4" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { listContract } from '@/api/crm/contract';
import { ORDER_STATUS } from '../js/enum'

export default {
  name: 'OrderEdit',
  props: {
    initValue: {
      type: Object,
      default: () => ({})
    },
    customerList: {
      type: Array,
      default: () => []
    }
  },
  dicts: ['wip_pack_saleman'],
  data() {
    return {
      ORDER_STATUS,
      form: {
        ...this.initValue
      },
      // 防抖计时器标识
      debounceTimer: null,
      contractList: []
    }
  },
  watch: {
    // 深度监听form对象的所有属性变化
    form: {
      deep: true,
      handler() {
        // 每次编辑时先清除之前的计时器
        if (this.debounceTimer) {
          clearTimeout(this.debounceTimer);
        }
        // 重新设置2秒后的保存回调
        this.debounceTimer = setTimeout(() => {
          this.$emit('save', { ...this.form }); // 传递表单副本，避免外部修改影响内部
        }, 2000); // 2秒延迟
      }
    }
  },
  mounted() {
    // 初始化时获取合同列表
    this.getContractList()
  },
  beforeDestroy() {
    // 组件销毁时清除计时器，防止内存泄漏
    if (this.debounceTimer) {
      clearTimeout(this.debounceTimer);
    }
  },
  methods: {
    // 可选：手动触发保存的方法（如需主动保存时调用）
    manualSave() {
      if (this.debounceTimer) {
        clearTimeout(this.debounceTimer);
      }
      this.$emit('save', { ...this.form });
    },
    // 处理合同号选择变化
    handleContractChange(contractId) {
      // 当合同号选择变化时，更新合同金额
      const contract = this.contractList.find(item => item.contractId === contractId)
      if (contract) {
        this.form.contractCode = contract.contractNo
      }
      
    },
    // 获取合同列表
    getContractList() {
      listContract({ pageSize: 1000, pageNum: 1 }).then(res => {
        this.contractList = res.rows || []
      })
    }
  }
}
</script>

<style scoped>
/* 客户编号输入框样式 */
.customer-code-input {
  width: 300px;
  height: 36px;
  padding: 0 15px;
  border: 1px solid #dcdfe6;
  font-size: 14px;
  color: #606266;
  background-color: transparent;
  transition: border-color 0.2s, background-color 0.2s;
  outline: none;
  box-sizing: border-box;
}

/* 输入框 hover 状态 */
.customer-code-input:hover {
  border-color: #c0c4cc;
  background-color: #f5f7fa;
}

/* 输入框 focus 状态 */
.customer-code-input:focus {
  border-color: #409eff;
  background-color: #fff;
}

/* 禁用状态 */
.customer-code-input:disabled {
  background-color: #f5f7fa;
  color: #c0c4cc;
  cursor: not-allowed;
}

/* 保存变更按钮容器 */
.save-btn-container {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

/* 保存按钮自定义样式 */
.save-btn {
  padding: 8px 20px;
  font-size: 14px;
}
</style>