<template>
  <el-form
    v-loading="loading"
    ref="ruleForm"
    :model="ruleForm"
    status-icon
    :size="'mini'"
    :rules="rulesThis"
    :label-width="labelWidth || '100px'"
    class="demo-ruleForm"
  >
    <el-row>
      <el-col :span="12"
        ><el-form-item label="客户名称" prop="companyCode">
          <search-customer
            :value="ruleForm.companyCode"
            :names="ruleForm.companyName"
            :placeholder="'客户名称'"
            :size="'mini'"
            :isDetail="ruleForm.companyName"
            @searchChange="customerChange"
        /></el-form-item>
      </el-col>
      <el-col :span="12"
        ><el-form-item label="服务费" prop="service_charge">
          <digital-input
            :values="ruleForm.service_charge"
            :placeholder="'服务费'"
            :min="0"
            :disabled="false"
            :max="100000000000"
            :position="'right'"
            :precision="2"
            :size="'mini'"
            :controls="false"
            :append="'元'"
            @reschange="number_change($event, 'service_charge')"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="所属平台" prop="platform_id">
          <search-terrace
            :value="ruleForm.platform_id"
            :names="ruleForm.platform_name"
            :disabled="false"
            :size="'mini'"
            :is_show="'1'"
            :placeholder="'所属平台'"
            @searchChange="platform_codesearchChange"
          />
        </el-form-item>
      </el-col>

      <el-col :span="12"
        ><el-form-item label="服务费比例" prop="service_proportion">
          <digital-input
            :values="ruleForm.service_proportion"
            :placeholder="'服务费比例'"
            :min="0"
            :disabled="false"
            :max="100"
            :position="'right'"
            :precision="2"
            :size="'mini'"
            :controls="false"
            :append="'%'"
            @reschange="number_change($event, 'service_proportion')"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="平台商品编号" prop="plat_code">
          <el-input
            placeholder="平台商品编号"
            v-model="ruleForm.plat_code"
            :disabled="false"
            maxlength="50"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-button
          v-if="!disabled"
          :size="'mini'"
          type="primary"
          class="fr"
          @click="submitForm"
          >保 存
        </el-button>
      </el-col>
    </el-row>
  </el-form>
</template>

<script>
import {
  add_sum, //加法精算
  accSub, //减法精算
  accMul, //乘法精算
  accDiv, //除法精算
} from "@/utils/validate";
export default {
  name: "exam-form",
  props: ["size", "disabled", "labelWidth", "sitem"],
  /**
   * 属性集合
   * @param {String}        size             : 组件大小             非必填
   * @param {Array}         statusList       : 驳回至备选项          必填
   * @param {Boolean}       disabled         : 是否禁用              必填
   * @param {Boolean}       isMust           : 是否需要展示驳回节点   必填
   *
   *
   */
  /**
   * 事件集合
   * @searchChange             : 选中值变化调用   抛出选中数据
   */
  data() {
    return {
      loading: false,
      is_determine_price: "",
      cgd_charge: "",
      price: "",
      ruleForm: {
        id: "",
        status: "",
        companyCode: [],
        companyName: "",
        service_charge: "",
        service_proportion: "",
        plat_code: "",
        platform_id: "",
        platform_name: "",
      },
      rulesThis: this.rules,
      rules: {
        companyCode: [
          {
            required: true,
            type: "array",
            message: "请选择企业客户",
            trigger: "change",
          },
        ],

        service_charge: [{ required: true, message: "请输入服务费", trigger: "blur" }],
        service_proportion: [
          { required: true, message: "请输入服务费比例", trigger: "blur" },
        ],
        platform_id: [
          {
            required: true,
            message: "请选择平台",
            trigger: "change",
          },
        ],
      },
    };
  },
  watch: {
    newTime: function () {
      this.initForm();
    },
  },
  mounted() {
    this.initForm();
  },
  methods: {
    async initForm() {
      this.loading = true;
      this.rulesThis = this.rules;
      await this.resetForm();
      this.loading = false;
    },
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          console.log(this.sitem);
          const {
            id,
            status,
            companyCode,
            companyName,
            service_charge,
            service_proportion,
            plat_code,
            cgd_charge,
            price,
            is_determine_price,
            expect_service,
            expect_service_proportion,
            platform_id,
            platform_name,
          } = this.sitem;

          console.log(this.sitem)
          
          this.cgd_charge = cgd_charge;
          this.price = price;
          const service = status + "" === "0" ? expect_service : service_charge;
          const proportion =
            status + "" === "0" ? expect_service_proportion : service_proportion;
          this.is_determine_price = is_determine_price;
          this.ruleForm = {
            id: id,
            status: "2",
            companyCode: companyCode ? [companyCode] : [],
            companyName,
            service_charge: service ? service : "0",
            service_proportion: proportion ? proportion : "0",
            plat_code,
            platform_id: platform_id && platform_id + "" !== "0" ? platform_id : "",
            platform_name,
          };
        }
      });
    },
    //购买方公司选择
    customerChange(e) {
      const { code, label } = e;
      this.ruleForm.companyCode = code ? [code] : [];
      this.ruleForm.companyName = label ? label : "";
      this.$refs.ruleForm.validateField("companyCode");
    },
    platform_codesearchChange(e) {
      console.log(e);
      const { id, label } = e;
      this.ruleForm.platform_id = id;
      this.ruleForm.platform_name = label ? label : "";
      this.$refs.ruleForm.validateField("platform_id");
    },
    async number_change(e, key) {
      this.ruleForm[key] = e + "" || "0";
      console.log(e)
      this.$refs.ruleForm.validateField(key);
      await this.num(key);
    },
    async num(key) {
      const is_sale = this.is_determine_price === "1";
      let cgdAdd = 0,
        serAdd = 0,
        qrdAdd = 0,
        rate = 0;
      if (is_sale) {
        qrdAdd = this.price * 1;
      } else {
        cgdAdd = this.cgd_charge * 1;
      }
      if (key === "service_charge") {
        serAdd = this.ruleForm.service_charge ?? "0" * 1;
      }
      if (key === "service_proportion") {
        rate = this.ruleForm.service_proportion ?? "0" * 1;
      }
      if (is_sale && key === "service_charge") {
        if (qrdAdd <= serAdd) {
          this.$message.error("服务费不能大于等于销售单价！");
          await this.set_number_change("service_charge", "0");
          await this.set_number_change("service_proportion", "0");
          return;
        }

        cgdAdd = accSub(qrdAdd, serAdd);
        rate = accMul(accSub(1, accDiv(cgdAdd, qrdAdd)), 100);
        await this.set_number_change("service_proportion", rate);
      }
      if (is_sale && key === "service_proportion") {
        if (rate === 100) {
          this.$message.error("服务费比例不能等于100！");
          await this.set_number_change("service_charge", "0");
          await this.set_number_change("service_proportion", "0");
          return;
        }

        cgdAdd = accMul(qrdAdd, accSub(100, rate));
        serAdd = accSub(qrdAdd, cgdAdd);
        await this.set_number_change("service_charge", serAdd);
      }
      if (!is_sale && key === "service_charge") {
        qrdAdd = add_sum(cgdAdd, serAdd);
        rate = accSub(1, accDiv(cgdAdd, qrdAdd));
        await this.set_number_change("service_proportion", rate);
      }
      if (!is_sale && key === "service_proportion") {
        // qrdAdd = cgdAdd / (100 - rate);
        // serAdd = qrdAdd - cgdAdd;
        if (rate === 100) {
          this.$message.error("服务费比例不能等于100！");
          await this.set_number_change("service_charge", "0");
          await this.set_number_change("service_proportion", "0");
          return;
        }
        qrdAdd = accDiv(cgdAdd, accSub(100, rate));
        serAdd = accSub(qrdAdd, cgdAdd);
        await this.set_number_change("service_charge", serAdd);
      }
    },
    async set_number_change(key, value) {
      this.ruleForm[key] = value + "" || "0";
      this.$refs.ruleForm.validateField(key);
    },
    async submitForm() {
      console.log(this.ruleForm)
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.$emit("searchChange", this.ruleForm);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.exa {
  margin: 20px 0 0 30px;
  font-size: 14px;
  font-weight: bold;
}
</style>
