<template>
  <div id="">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="120px"
      class="demo-ruleForm"
      :disabled="status === 'info'"
    >
      <First :ruleForm="ruleForm"></First>
      <Second :ruleForm="ruleForm" @backGoodsList="backGoodsList"></Second>
      <Three :ruleForm="ruleForm" @backTenantList="backTenantList"></Three
    ></el-form>
    <div style="text-align: center">
      <el-button @click="close">取消</el-button>
      <el-button
        v-loading="loading"
        type="primary"
        @click="submitForm('ruleForm')"
        v-if="status !== 'info'"
        >保存</el-button
      >
      <el-button
        v-loading="loading"
        type="primary"
        @click="submitForm('ruleForm', true)"
        v-if="status !== 'info'"
        >发布</el-button
      >
    </div>
  </div>
</template>

<script>
import First from "./first.vue";
import Second from "./second.vue";
import Three from "./three.vue";
export default {
  components: { First, Second, Three },
  data() {
    return {
      loading: false,
      ruleForm: {
        publishStatus: 0,
        goodsList: [], //商品列表
        tenantList: [], //机构列表
      },
      rules: {
        name: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
        posterTempId: [
          { required: true, message: "请选择模板", trigger: "change" },
        ],
        timeList: [
          { required: true, message: "请选择活动时间", trigger: "change" },
        ],
        freezingPeriod: [
          { required: true, message: "请输入佣金冻结天数", trigger: "blur" },
        ],
      },
      id: "",
      status: "",
    };
  },
  created() {
    this.id = this.$route.query.id;
    this.status = this.$route.query.status;
    if (this.id) {
      this.getInit();
    }
  },
  methods: {
    close() {
      this.$store.dispatch("tagsView/exitView", this.$route).then((res) => {
        this.$router.push({
          path: "activityList",
        });
      });
    },
    getInit() {
      this.$api.distributiontempdata(this.id).then((res) => {
        res.data.timeList = [
          parseInt(res.data.startTime * 1000),
          parseInt(res.data.endTime * 1000),
        ];
        res.data.goodsList = res.data.goodsList || [];
        res.data.tenantList = res.data.tenantList || [];
        this.$nextTick(() => {
          this.ruleForm = res.data;
        });
      });
    },
    //提交
    submitForm(formName, status) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.checkGoodsFunc()
            .then(() => {
              this.loading = true;
              var data = JSON.parse(JSON.stringify(this.ruleForm));
              data.startTime = data.timeList[0] / 1000;
              data.endTime = data.timeList[1] / 1000;
              if (status) {
                data.publishStatus = 1;
              }
              this.$api[
                data.id ? "editdistributiontemp" : "distributiontempsave"
              ](data)
                .then((res) => {
                  this.$message.success("成功");
                  setTimeout(() => {
                    this.$store
                      .dispatch("tagsView/exitView", this.$route)
                      .then((res) => {
                        this.$router.push({
                          path: "activityList",
                        });
                      });
                  }, 300);
                })
                .finally(() => {
                  this.loading = false;
                });
            })
            .catch((err) => {
              this.$message.error(err);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //处理商品佣金逻辑
    checkGoodsFunc() {
      return new Promise((resolve, reject) => {
        for (let i = 0; i < this.ruleForm.goodsList.length; i++) {
          if (this.ruleForm.goodsList[i].profitType === 1) {
            //百分比处理
            if (this.ruleForm.goodsList[i].profitMax > 100) {
              return reject(`请检查第${i + 1}个商品的数值设置`);
            } else {
              let countNum =
                parseFloat(this.ruleForm.goodsList[i].profitOne) +
                parseFloat(this.ruleForm.goodsList[i].profitTwo) +
                parseFloat(this.ruleForm.goodsList[i].profitThree);
              if (countNum > 100) {
                return reject(
                  `请检查第${
                    i + 1
                  }个商品的佣金设置，三个级别佣金相加不能大于数值`
                );
              }
            }
          }
          if (this.ruleForm.goodsList[i].profitType === 2) {
            //固定金额处理
            if (
              this.ruleForm.goodsList[i].profitMax >
              this.ruleForm.goodsList[i].goodsPrice
            ) {
              return reject(`请检查第${i + 1}个商品的数组设置`);
            } else {
              let countNum =
                parseFloat(this.ruleForm.goodsList[i].profitOne) +
                parseFloat(this.ruleForm.goodsList[i].profitTwo) +
                parseFloat(this.ruleForm.goodsList[i].profitThree);
              if (countNum > this.ruleForm.goodsList[i].profitMax) {
                return reject(
                  `请检查第${
                    i + 1
                  }个商品的佣金设置，三个级别佣金相加不能大于数值`
                );
              }
            }
          }
        }
        resolve();
      });
    },
    //商品列表选中返回
    backGoodsList(e) {
      this.$nextTick(() => {
        this.ruleForm.goodsList.push(...e);
      });
    },
    //机构列表选中返回
    backTenantList(e) {
      this.$nextTick(() => {
        this.ruleForm.tenantList.push(...e);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/.el-button {
  border-radius: 8px;
}

/deep/.el-dialog {
  border-radius: 8px;

  .el-dialog__header {
    padding: 0;

    .hearders {
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0px 18px 0px 20px;
      border-bottom: 1px solid #e2e2e2;

      .leftTitle {
        font-size: 14px;
        font-weight: bold;
        color: #2f4378;
      }

      .rightBoxs {
        display: flex;
        align-items: center;

        img {
          width: 14px;
          height: 14px;
          margin-left: 13px;
          cursor: pointer;
        }
      }
    }
  }

  .el-dialog__footer {
    padding: 0;

    .dialog-footer {
      padding: 0px 40px;
      height: 70px;
      border-top: 1px solid #e2e2e2;
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
  }
}

.imgBox {
  width: 100%;
  // height: 210px;
  border: 1px solid #e2e2e2;
  border-radius: 8px;
  padding: 8px 8px 3px;
  display: flex;
  flex-direction: column;
  align-items: center;
  .imgLabel {
    flex: 1;
    width: 100%;
    border: 1px dotted #e2e2e2;
    color: #999;
    font-size: 14px;
    cursor: pointer;
    border-radius: 8px;

    .msPhoto {
      display: flex;
      justify-content: center;
      align-items: center;
      max-width: 100%;
      max-height: 270px;

      img {
        max-width: 100%;
        max-height: 270px;
      }
    }

    .imgbbx {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;

      i {
        font-weight: bold;
        margin: 14px 0;
        font-size: 24px;
      }
    }
  }

  p {
    margin: 5px 0px;
  }
}
</style>
