<!-- 新增/编辑弹窗 -->
<template>
  <ele-modal
    width="700px"
    :visible="visible"
    :append-to-body="true"
    :close-on-click-modal="false"
    custom-class="ele-dialog-form"
    :title="isDetail ? '详情' : (isUpdate ? '修改' : '新增')"
    @update:visible="updateVisible"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="140px"
    >
      <!-- 收/付款条件编码 -->
      <el-form-item :label="conditionType == 'rules' ? '收款条件编码:' : '付款条件编码:'" prop="code">
        <el-input
          v-model="form.code"
          placeholder="自动生成"
          :disabled="true"
        />
      </el-form-item>

      <!-- 收款条件名称 -->
      <el-form-item :label="conditionType == 'rules' ? '收款条件名称:' : '付款条件名称:'" prop="name">
        <el-input
          clearable
          v-model="form.name"
          placeholder="请输入条件名称"
          :disabled="isDetail"
        />
      </el-form-item>

      <!-- 收/付款日计算日期 -->
      <el-form-item :label="conditionType == 'rules' ? '收款日计算日期:' : '付款日计算日期:'" prop="dateType">
        <el-select
          v-model="form.dateType"
          placeholder="请选择"
          style="width: 100%"
          :disabled="isDetail"
        >
          <el-option v-for="item in calcReceiveDateTypeOp" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <!-- 收/付款日确定方式 -->
      <el-form-item :label="conditionType == 'rules' ? '收款日确定方式:' : '付款日确定方式:'" prop="determinationMethod">
        <el-select
          v-model="form.determinationMethod"
          placeholder="请选择"
          style="width: 100%"
          :disabled="isDetail"
          @change="handleConfirmTypeChange"
        >
          <el-option v-for="item in payConfirmTypeOp" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <!-- 月数（X天后显示） -->
      <el-form-item label="月数:" v-if="form.determinationMethod == 2">
        <el-input-number
          v-model="form.determinationMethodMonth"
          :min="0"
          :precision="0"
          controls-position="right"
          style="width: 100%"
          :disabled="isDetail"
        />
      </el-form-item>

      <!-- 天数（X天后显示） -->
      <el-form-item label="天数:" v-if="form.determinationMethod == 2">
        <el-input-number
          v-model="form.determinationMethodDay"
          :min="0"
          :precision="0"
          controls-position="right"
          style="width: 100%"
          :disabled="isDetail"
        />
      </el-form-item>

      <!-- 支付方式列表 -->
      <el-form-item
        v-for="(item, index) in form.rulesTypePOList"
        :key="item.id"
        :label="index === 0 ? '支付方式:' : ''"
        :required="index === 0"
        class="payment-method-item"
      >
        <div class="payment-method-row">
          <el-input-number
            v-model="item.percentage"
            :min="0"
            :max="100"
            :precision="0"
            controls-position="right"
            class="payment-input"
            placeholder="比例"
            :disabled="isDetail"
          />
          <span class="payment-unit">%</span>
          <el-input-number
            v-model="item.paymentSum"
            :min="0"
            :precision="0"
            controls-position="right"
            class="payment-input"
            placeholder="请输入"
            :disabled="isDetail"
          />
          <el-select
            v-model="item.dateType"
            placeholder="请选择"
            class="payment-unit-select"
            :disabled="isDetail"
          >
            <el-option v-for="opt in dateUnitOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
          <DictSelection
            v-model="item.paymentType"
            dictName="支付类型"
            placeholder="请选择"
            class="payment-select"
            :disabled="isDetail"
          />
          <el-button
            v-if="!isDetail && index === form.rulesTypePOList.length - 1"
            type="text"
            icon="el-icon-circle-plus-outline"
            class="add-payment-btn"
            @click="addPaymentRow"
          />
          <el-button
            v-if="!isDetail && form.rulesTypePOList.length > 1 && index !== 0"
            type="text"
            icon="el-icon-remove-outline"
            class="remove-payment-btn"
            @click="removePaymentRow(index)"
          />
        </div>
      </el-form-item>

      <!-- 备注 -->
      <el-form-item label="备注:" prop="remark">
        <el-input
          type="textarea"
          :rows="3"
          v-model="form.remark"
          placeholder="请输入"
          :disabled="isDetail"
        />
      </el-form-item>
    </el-form>

    <template v-slot:footer>
      <template v-if="isDetail">
        <el-button @click="updateVisible(false)">关闭</el-button>
      </template>
      <template v-else>
        <el-button type="primary" :loading="loading" @click="save">
          确定
        </el-button>
        <el-button @click="updateVisible(false)">取消</el-button>
      </template>
    </template>
  </ele-modal>
</template>

<script>
  import { addReceiveTerms, updateReceiveTerms, getInfo } from '@/api/rulesManagement/receiveTerms';
  import { calcReceiveDateTypeOp, payConfirmTypeOp, dateUnitOptions } from '@/enum/dict';

  let paymentId = 0;

  export default {
    props: {
      // 收款/付款：rules/terms
      conditionType: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        visible: false,
        loading: false,
        isUpdate: false,
        isDetail: false,
        calcReceiveDateTypeOp,
        payConfirmTypeOp,
        // 支付周期单位（天/月/年）
        dateUnitOptions,
        form: {
          id: null,
          code: '',
          name: '',
          dateType: null,
          determinationMethod: null,
          determinationMethodMonth: 0,
          determinationMethodDay: 0,
          rulesTypePOList: [],
          remark: '',
          ruleState: 1,
          conditionConfigurationType: this.conditionType
        },
        rules: {
          // code: [{ required: true, message: '请输入收款条件编码', trigger: 'blur' }],
          name: [{ required: true, message: '请输入收款条件名称', trigger: 'blur' }],
          dateType: [{ required: true, message: '请选择收款日计算日期', trigger: 'change' }],
          determinationMethod: [{ required: true, message: '请选择收款日确定方式', trigger: 'change' }]
        }
      };
    },
    methods: {
      // 生成编码 SKTJ+年月日+3位数字
      generateCode() {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const random = String(Math.floor(Math.random() * 900) + 100);
        this.form.code = `SKTJ${year}${month}${day}${random}`;
      },

      open(type, row) {
        this.visible = true;
        this.isUpdate = type === 'edit';
        this.isDetail = type === 'detail';
        if ((this.isUpdate || this.isDetail) && row) {
          this.getDetail(row.id)
        } else {
          this.resetForm();
          // this.generateCode();
        }
        this.$nextTick(() => {
          this.$refs.form && this.$refs.form.clearValidate();
        });
      },

      getDetail(id) {
        getInfo(id).then(res => {
          console.log('getInfo res', res);
          this.form = {
            ...res,
          };

        })
      },

      resetForm() {
        this.form = {
          // id: null,
          code: '',
          name: '',
          dateType: '1',        // 默认：订单日期
          determinationMethod: '1',         // 默认：交易日（隐藏月数、天数）
          determinationMethodMonth: 0,
          determinationMethodDay: 0,
          rulesTypePOList: [this.createEmptyPayment()], // 默认：100% 0月 现金
          remark: '',
          ruleState: 1,
          conditionConfigurationType: this.conditionType
        };
      },

      createEmptyPayment() {
        return {
          key: ++paymentId,
          percentage: 100,
          paymentSum: 0,
          dateType: 'month',
          paymentType: '1'
        };
      },

      // 收款日确定方式变化
      handleConfirmTypeChange() {
        if (this.form.determinationMethod == 1) {
          this.form.determinationMethodMonth = 0;
          this.form.determinationMethodDay = 0;
        }
      },

      // 添加支付方式行
      addPaymentRow() {
        this.form.rulesTypePOList.push(this.createEmptyPayment());
      },

      // 移除支付方式行
      removePaymentRow(index) {
        this.form.rulesTypePOList.splice(index, 1);
      },

      // 构建支付方式字符串
      buildPaymentMethod() {
        return this.form.rulesTypePOList
          .map(item => `${item.percentage}% ${item.paymentSum}${item.dateType || 'month'} ${item.paymentType}`)
          .join(',');
      },

      // 构建确认方式描述
      buildConfirmDesc() {
        if (this.form.determinationMethod === 1) {
          return '交易日';
        }
        const parts = [];
        if (this.form.determinationMethodMonth > 0) parts.push(`月数：${this.form.determinationMethodMonth}`);
        if (this.form.determinationMethodDay > 0) parts.push(`天数：${this.form.determinationMethodDay}`);
        if (parts.length === 0) return '0月0天即交易日';
        return parts.join('，');
      },

      save() {
        this.$refs.form.validate((valid) => {
          if (!valid) return;

          // 校验支付方式比例总和
          const totalRatio = this.form.rulesTypePOList.reduce((sum, item) => sum + item.percentage, 0);
          if (totalRatio !== 100) {
            this.$message.warning('支付比例总和必须等于100%');
            return;
          }

          this.loading = true;

          const data = {
            ...this.form,
            // paymentMethod: this.buildPaymentMethod(),
            // confirmDesc: this.buildConfirmDesc()
          };
          // delete data.rulesTypePOList;

          console.log('save data', data);
          // return

          const saveOrUpdate = this.isUpdate ? updateReceiveTerms : addReceiveTerms;
          saveOrUpdate(data)
            .then(() => {
              this.loading = false;
              this.$message.success(this.isUpdate ? '修改成功' : '新增成功');
              this.updateVisible(false);
              this.$emit('done');
            })
            .catch(() => {
              this.loading = false;
            });
        });
      },

      updateVisible(value) {
        this.visible = value;
        if (!value) {
          this.resetForm();
        }
      }
    }
  };
</script>

<style lang="scss" scoped>
  .payment-method-row {
    display: flex;
    align-items: center;
    gap: 8px;
  }
  .payment-input {
    width: 100px;
  }
  .payment-unit {
    color: #606266;
    font-size: 14px;
  }
  .payment-unit-select {
    width: 80px;
  }
  .payment-select {
    width: 120px!important;
  }
  .add-payment-btn,
  .remove-payment-btn {
    font-size: 18px;
    padding: 0;
  }
  .remove-payment-btn {
    color: #f56c6c;
  }
</style>
