<template>
  <div>
    <el-alert
      title="基础信息"
      type="info"
      :closable="false"
      class="baseMsg"
    ></el-alert>

    <div class="m-core">
      <el-form
        :label-position="labelPosition"
        :model="baseForm"
        ref="vipform"
        label-width="140px"
        :rules="vipformRules"
        class="vipform"
      >
        <el-form-item label="活动名称" prop="name">
          <el-input
            style="width: 400px"
            v-model.trim="baseForm.name"
            :disabled="isDisabled || status != 'DRAFT'"
          ></el-input>
        </el-form-item>
        <!--   @visible-change="$forceUpdate()" -->
        <el-form-item label="适用分部" prop="organ">
          <select-all
            v-model.trim="baseForm.organ"
            style="width: 400px"
            multiple
            filterable
            @change="onOrganChange"
            clearable
            :disabled="isDisabled || status != 'DRAFT'"
          >
            <el-option
              v-for="(item, index) in selects.branchs"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </select-all>
          <!-- <el-button @click="onCheckAllBranch">适用所有分部</el-button> -->
        </el-form-item>
        <el-form-item label="活动描述" prop="description">
          <el-input
            type="textarea"
            v-model.trim="baseForm.description"
            style="width: 400px"
            :rows="5"
            placeholder="请输入活动说明"
            :disabled="isDisabled || status != 'DRAFT'"
          ></el-input>
        </el-form-item>
        <el-form-item label="活动渠道" prop="activityChannel">
          <el-select
            v-model.trim="baseForm.activityChannel"
            placeholder="请选择活动渠道"
            clearable
            style="width: 400px !important"
            :disabled="isDisabled || status != 'DRAFT'"
            @change="changeActivityChannel"
          >
            <el-option label="乐团小课" :value="1"></el-option>
            <el-option label="常规小课" :value="2"></el-option>
            <el-option label="学生购买" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="活动类型"
          prop="activityType"
          v-if="baseForm.activityChannel !== 1"
        >
          <el-select
            v-model.trim="baseForm.activityType"
            placeholder="请选择活动类型"
            clearable
            style="width: 400px !important"
            @change="changeActivityType"
            :disabled="isDisabled || status != 'DRAFT'"
          >
            <el-option label="课程活动" :value="0"></el-option>
            <el-option label="会员活动" :value="1"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="活动生效时间" prop="activeTime">
          <el-date-picker
            :disabled="isDisabled"
            v-model.trim="baseForm.activeTime"
            type="datetimerange"
            :default-time="['00:00:00', '23:59:59']"
            range-separator="至"
            value-format="yyyy-MM-dd HH:mm:ss"
            start-placeholder="开始日期"
            :picker-options="{
              firstDayOfWeek: 1
            }"
            end-placeholder="结束日期"
          ></el-date-picker>
          <el-tooltip placement="top" popper-class="mTooltip">
            <div slot="content">
              可通过该方案购买课程的时间范围，到达开始时间才可购买，到达结束时间后不可购买，不填则不限制且立即生效
            </div>
            <i
              class="el-icon-question micon el-tooltip"
              style="font-size: 18px; color: #f56c6c"
            ></i>
          </el-tooltip>
        </el-form-item>
        <div v-if="baseForm.activityChannel !== 1">
          <!-- <el-form-item label="排课时间范围" prop="courseTime">
            <el-date-picker
              :disabled="isDisabled"
              v-model.trim="baseForm.courseTime"
              type="datetimerange"
              :default-time="['00:00:00', '23:59:59']"
              range-separator="至"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始日期"
              :picker-options="{
                firstDayOfWeek: 1
              }"
              end-placeholder="结束日期"
            ></el-date-picker>
            <el-tooltip placement="top" popper-class="mTooltip">
              <div slot="content">
                通过该方案购买的课程排课时，课程时间不可超过该时间范围，不填则不限制
              </div>
              <i
                class="el-icon-question micon el-tooltip"
                style="font-size: 18px; color: #f56c6c"
              ></i>
            </el-tooltip>
          </el-form-item> -->
          <el-form-item label="适用学员" prop="applyToStudentType">
            <el-row>
              <el-col style="width: 400px">
                <select-all
                  v-model.trim="baseForm.applyToStudentType"
                  style="width: 400px"
                  multiple
                  filterable
                  clearable
                  placeholder="请选择适用学员"
                  @change="applyToStudentTypeChange"
                  :disabled="isDisabled"
                >
                  <el-option label="新学员" value="1"></el-option>
                  <el-option label="老学员" value="0"></el-option>
                  <el-option label="会员" value="2"></el-option>
                  <el-option label="非会员" value="3"></el-option>
                </select-all>
              </el-col>
              <el-tooltip placement="top" popper-class="mTooltip">
                <div slot="content">
                  可通过该方案购买课程的学员群体，不填则不限制
                </div>
                <i
                  class="el-icon-question micon el-tooltip"
                  style="font-size: 18px; color: #f56c6c; margin-left: 3px"
                ></i>
              </el-tooltip>
            </el-row>
          </el-form-item>
          <el-form-item label="可购买次数" prop="studentMaxUsedTimes">
            <el-input
              style="width: 400px"
              type="number"
              v-model.trim="baseForm.studentMaxUsedTimes"
              :disabled="isDisabled"
            >
              <template slot="append"
                >次</template
              >
            </el-input>
            <el-tooltip placement="top" popper-class="mTooltip">
              <div slot="content">
                学员可以购买该活动方案的次数限制，不填则不限制
              </div>
              <i
                class="el-icon-question micon el-tooltip"
                style="font-size: 18px; color: #f56c6c"
              ></i>
            </el-tooltip>
          </el-form-item>
          <!-- <el-form-item label="是否充值课程余额" prop="isPayToBalance">
          <el-select
            v-model.trim="baseForm.isPayToBalance"
            placeholder="请选择是否充值课程余额"
            clearable
            style="width: 400px !important"
            :disabled="isDisabled || status != 'DRAFT' || balanceDis"
          >
            <el-option label="课程余额" :value="1"></el-option>
            <el-option label="资格限制" :value="0"></el-option>
          </el-select>
          <el-tooltip placement="top" popper-class="mTooltip">
            <div slot="content">
              课程余额：学员缴费金额进入课程余额，排课时扣减课程余额，若课程余额不足则不可排课<br/>
              资格限制：学员缴费金额不进入课程余额，学员购买后增加可排课次数，排课后扣减可排课次数
              会员活动默认为资格限制，不可修改
            </div>
            <i
              class="el-icon-question micon el-tooltip"
              style="font-size: 18px; color: #f56c6c"
            ></i>
          </el-tooltip>
        </el-form-item> -->
        </div>
        <el-form-item
          label="活动售价"
          prop="marketPrice"
          :rules="[
            {
              required: true,
              message: '请选输入活动售价',
              trigger: 'blur'
            },
            {
              pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
              message: '请输入正确的金额'
            }
          ]"
        >
          <el-input
            style="width: 400px"
            type="number"
            v-model.trim="baseForm.marketPrice"
            :disabled="isDisabled || status != 'DRAFT'"
          >
            <template slot="append"
              >元</template
            >
          </el-input>
          <el-tooltip placement="top" popper-class="mTooltip">
            <div slot="content">
              该字段仅用于关联的营销活动中本方案的销售价格，后台、老师端为学员创建课程不受此价格影响
            </div>
            <i
              class="el-icon-question micon el-tooltip"
              style="font-size: 18px; color: #f56c6c"
            ></i>
          </el-tooltip>
        </el-form-item>
        <el-form-item
          label="活动原价"
          prop="originalPrice"
          :rules="[
            { required: true, message: '请选输入活动原价', trigger: 'blur' },
            {
              pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
              message: '请输入正确的金额'
            }
          ]"
        >
          <el-input
            style="width: 400px"
            type="number"
            v-model.trim="baseForm.originalPrice"
            :disabled="isDisabled || status != 'DRAFT'"
          >
            <template slot="append"
              >元</template
            >
          </el-input>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { vipGroupCategory, addVipActive } from "@/api/vipSeting";
import { getEmployeeOrgan } from "@/api/buildTeam";
import cleanDeep from "clean-deep";
export default {
  props: ["baseForm", "isDisabled", "status"],
  name: "vipNewActive",
  data() {
    return {
      pageType: "",
      labelPosition: "right",
      vipformRules: {
        name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          {
            min: 1,
            max: 25,
            message: "长度在 1 到 25 个字符",
            trigger: "blur"
          }
        ],
        desc: [
          { required: true, message: "请输入文字描述", trigger: "blur" },
          {
            min: 1,
            max: 200,
            message: "长度在 1 到 200 个字符",
            trigger: "blur"
          }
        ],
        activityType: [
          { required: true, message: "请选择活动类型", trigger: "change" }
        ],
        activityChannel: [
          { required: true, message: "请选择活动渠道", trigger: "change" }
        ],
        courseTime: [
          { required: false, message: "请选择课程时间", trigger: "change" }
        ],
        studentMaxUsedTimes: [
          { required: false, message: "请输入购买次数", trigger: "blur" },
          { pattern: /^\+?[1-9]\d*$/, message: "请输入大于0的正整数" }
        ],
        organ: [
          { required: true, message: "请选择适用分部", trigger: "change" }
        ],
        stauts: [
          { required: true, message: "请选择活动形式", trigger: "change" }
        ],
        applyToStudentType: [
          { required: false, message: "请选择是否新生专享" }
        ],
        isPayToBalance: [
          {
            required: true,
            message: "请选择是否支付到余额",
            trigger: "change"
          }
        ],
        allowOnlineToOffline: [
          { required: true, message: "请选择课程调整方式", trigger: "change" }
        ]
      },
      courseStatusList: [], // 获取所有课程形式
      activeType: "",
      online: true,
      unonline: true,
      onlineSalary: "TEACHER_DEFAULT",
      unonlineSalary: "TEACHER_DEFAULT",
      onlineprice: "",
      unonlineprice: "",
      salaryReadonlyFlag: false,
      paymentReadonlyFlag: false,
      attribute1: "",
      attribute2: "",
      courseNumForm: {
        minCourseNum: "",
        maxCourseNum: "",
        studentMaxUsedTimes: ""
      },
      giveClassPaySalaryFlag: true,
      organList: [],
      onlineClassJoinGradientRewards: false,
      offlineClassJoinGradientRewards: false,
      courseNumrules: {
        minCourseNum: [
          { required: true, message: "请输入最小课时数", trigger: "blur" },
          { validator: this.validateCom, trigger: "blur" },
          { validator: this.validateMin, trigger: "blur" }
        ],
        maxCourseNum: [
          { required: true, message: "请输入最大课时数", trigger: "blur" },
          { validator: this.validateCom, trigger: "blur" },
          { validator: this.validateMax, trigger: "blur" }
        ]
      }
    };
  },

  async mounted() {
    // 首先获取课程形式
    // vipGroupCategory().then(res => {
    //   if (res.code == 200) {
    //     this.courseStatusList = res.data;
    //   }
    // });
    // // 适用分部
    // getEmployeeOrgan().then(res => {
    //   if (res.code == 200) {
    //     this.organList = res.data;
    //   }
    // });
    // 获取类型
    await this.$store.dispatch("setVipGroupCategory");
    // 获取分部
    await this.$store.dispatch("setBranchs");
    // this.onReSet();
    // if (this.$route.query.rules) {
    //   this.rules = this.$route.query.rules;
    // }
    // if (this.$route.query.searchForm) {
    //   this.searchForm = this.$route.query.searchForm;
    // }

    this.pageType = this.$route.query.type;
    if (!this.$route.query.id) {
      this.$refs.vipform.resetFields();
    }
    //
  },

  methods: {
    resetForm() {
      this.$refs.form.resetFields();
    },
    handleMinChange() {
      this.$refs.form.validateField("maxCourseNum");
    },
    handleMaxChange() {
      this.$refs.form.validateField("minCourseNum");
    },
    validateCom(rule, value, callback) {
      const one = Number(value);
      if (Number.isInteger(one)) {
        if (one < MIN_NUMBER) {
          return callback(new Error("输入值必须大于0"));
        } else if (one > MAX_NUMBER) {
          return callback(new Error("输入值必须小于999"));
        }
        return callback();
      }
      return callback(new Error("输入值必须为正整数"));
    },
    validateMin(rule, value, callback) {
      const one = Number(value);
      const max = Number(this.courseNumForm.maxCourseNum);
      if (!max || one <= max) {
        return callback();
      }
      return callback(new Error("输入值不得大于最大课时数"));
    },
    validateMax(rule, value, callback) {
      const one = Number(value);
      const min = Number(this.courseNumForm.minCourseNum);
      if (!min || one >= min) {
        return callback();
      }
      return callback(new Error("输入值不得小于最小课时数"));
    },
    changeStauts(val) {
      console.log(val);
    },
    changeActivityType(val) {
      this.$emit("resetPayInfo");
    },
    changeActivityChannel(val) {
      this.$emit("resetPayInfo");
      this.$emit("resetBaseChannel", val);
    },
    submitFrom() {
      this.$refs.form.validate(isok => {
        if (isok) {
          this.$refs["vipform"].validate(valid => {
            if (valid) {
              // 验证通过
              let coursesStartTime = null,
                coursesEndTime = null,
                startTime = null,
                endTime = null;
              if (
                this.vipform.courseTime &&
                this.vipform.courseTime.length > 0
              ) {
                coursesStartTime = this.vipform.courseTime[0];
                coursesEndTime = this.vipform.courseTime[1];
              }
              if (
                this.vipform.activeTime &&
                this.vipform.activeTime.length > 0
              ) {
                startTime = this.vipform.activeTime[0];
                endTime = this.vipform.activeTime[1];
              }
              let organId = this.vipform.organ.join(",");
              let type = this.activeType;
              if (!type) {
                this.$message.error("请选择活动类型");
                return;
              }
              if (!this.online && !this.unonline) {
                this.$message.error("请选择活动适用范围");
                return;
              }
              if (type == "DISCOUNT") {
                if (!this.attribute1 || this.attribute1 < 0) {
                  this.$message.error("折扣必须大于等于0");
                  return;
                }
              } else if (type == "GIVE_CLASS") {
                if (!this.attribute1) {
                  this.$message.error("请输入多少节开始赠");
                  return;
                }
                if (!this.attribute2) {
                  this.$message.error("请输入赠送课时数");
                  return;
                }
              }
              let vipGroupCategoryIdList = this.vipform.stauts.join(",");
              let onlineSalarySettlement;
              let offlineSalarySettlement;
              if (this.online) {
                // 勾选线上
                if (this.onlineSalary == "RATIO_DISCOUNT") {
                  if (this.onlineprice < 0 || this.onlineprice > 100) {
                    this.$message.error("折扣比必须大于0且小于100");
                    return;
                  }
                } else if (this.onlineSalary == "TEACHER_DEFAULT") {
                  this.onlineprice = 0;
                }
                onlineSalarySettlement = {
                  salarySettlementType: this.onlineSalary,
                  settlementValue: this.onlineprice
                };
              } else {
                onlineSalarySettlement = null;
              }
              if (this.unonline) {
                // 勾选线下
                if (this.unonlineSalary == "RATIO_DISCOUNT") {
                  if (this.unonlineprice < 0 || this.unonlineprice > 100) {
                    this.$message.error("折扣比必须大于0且小于100");
                    return;
                  }
                } else if (this.unonlineSalary == "TEACHER_DEFAULT") {
                  this.unonlineprice = 0;
                }
                offlineSalarySettlement = {
                  salarySettlementType: this.unonlineSalary,
                  settlementValue: this.unonlineprice
                };
              } else {
                offlineSalarySettlement = null;
              }
              let salaryReadonlyFlag = this.salaryReadonlyFlag * 1;
              let paymentReadonlyFlag = this.paymentReadonlyFlag * 1;
              // let giveClassPaySalaryFlag = this.giveClassPaySalaryFlag * 1;
              let vipGroupSalarySettlement = {
                onlineSalarySettlement,
                offlineSalarySettlement
              };
              if (type == "BASE_ACTIVITY") {
                this.courseNumForm.studentMaxUsedTimes = -1;
                this.courseNumForm.minCourseNum = -1;
                this.courseNumForm.maxCourseNum = -1;
              } else if (type == "GIVE_CLASS") {
                this.courseNumForm.minCourseNum = -1;
                this.courseNumForm.maxCourseNum = -1;
              }
              // 发请求创建活动
              addVipActive(
                cleanDeep({
                  coursesStartTime,
                  coursesEndTime,
                  startTime,
                  endTime,
                  name: this.vipform.name,
                  description: this.vipform.desc,
                  applyToStudentType: this.vipform.applyToStudentType,
                  allowOnlineToOffline: this.vipform.allowOnlineToOffline,
                  organId,
                  type,
                  vipGroupCategoryIdList,
                  vipGroupSalarySettlement,
                  salaryReadonlyFlag,
                  paymentReadonlyFlag,
                  giveClassPaySalaryFlag: 1,
                  attribute1: this.attribute1,
                  attribute2: this.attribute2,
                  minCourseNum: this.courseNumForm.minCourseNum,
                  maxCourseNum: this.courseNumForm.maxCourseNum,
                  studentMaxUsedTimes: this.courseNumForm.studentMaxUsedTimes
                    ? this.courseNumForm.studentMaxUsedTimes
                    : -1,
                  offlineClassJoinGradientRewards:
                    this.offlineClassJoinGradientRewards * 1,
                  onlineClassJoinGradientRewards:
                    this.onlineClassJoinGradientRewards * 1
                })
              ).then(res => {
                if (res.code == 200) {
                  this.$message.success("恭喜你,活动创建成功");
                  // this.onReSet();
                  this.$store.dispatch("delVisitedViews", this.$route);
                  this.$router.push({
                    path: "/vipActiveManager/vipActiveList"
                  });
                }
              });
            } else {
              this.$nextTick(() => {
                let isError = document.getElementsByClassName("is-error");
                isError[0].scrollIntoView({
                  block: "center",
                  behavior: "smooth"
                });
              });
              // this.$message.error("请填写必要参数");
            }
          });
        }
      });

      // 线上线下课 勾选就传不勾选就不传
      // addVipActive().then(res => { })
    },
    onOrganChange() {
      // this.$forceUpdate();
      this.$refs.vipform.validateField("organ");
      this.$forceUpdate();
    },
    applyToStudentTypeChange() {
      this.$refs.vipform.validateField("applyToStudentType");
      this.$forceUpdate();
    },
    onCheckAllBranch() {
      // 选择所有分部
      let vipform = this.vipform;
      vipform.organ = [];
      this.selects.branchs.forEach(item => {
        vipform.organ.push(item.id);
      });
      this.$refs.vipform.validateField("organ");
      this.$forceUpdate();
    },

    onReSet() {
      this.vipform = {
        name: "",
        desc: "",
        activeTime: [],
        courseTime: []
      };
      this.activeType = "";
      this.online = true;
      this.unonline = true;
      this.salaryReadonlyFlag = false;
      this.onlineSalary = "TEACHER_DEFAULT";
      this.unonlineSalary = "TEACHER_DEFAULT";
      this.onlineprice = "";
      this.unonlineprice = "";
      this.onlineClassJoinGradientRewards = false;
      this.offlineClassJoinGradientRewards = false;
      this.attribute1 = "";
      this.attribute2 = "";
      this.courseNumForm.maxCourseNum = "";
      this.courseNumForm.minCourseNum = "";
      // this.$refs.vipform.resetFields();
    }
  },
  computed: {
    balanceDis() {
      if (this.baseForm.activityType) {
        this.baseForm.isPayToBalance = 0;
        return true;
      } else {
        return false;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.baseMsg {
  margin: 30px 0;
}
.m-core {
  font-size: 14px;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  // text-align: center;
  .activeRange {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    .left {
      height: 72px;
      line-height: 72px;
    }
    .right {
      .chioseWrap {
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        height: 72px;
        line-height: 72px;
        align-items: center;
        .el-checkbox {
          margin-right: 20px;
        }
        .el-select {
          margin-right: 20px;
        }
      }
    }
  }
  .activeType {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    .left {
      margin-right: 20px;
      p {
        height: 40px;
        line-height: 40px;
      }
    }
    .right {
      > div {
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        height: 40px;
        line-height: 40px;
        margin-bottom: 20px;
        .head {
          width: 120px;
          height: 40px;
          line-height: 40px;
          border: 1px solid #ccc;

          text-align: center;
          border-radius: 5px;
          cursor: pointer;
          margin-right: 10px;
        }
        > .head.active {
          background-color: var(--color-primary);
          color: #fff;
          border: none;
        }
        .title {
          line-height: 40px;
          height: 40px;
        }
      }
    }
  }
}
</style>
<style lang="scss">
.m-core {
  // .vipform {
  //   .el-select {
  //     .el-input__inner {
  //     }
  //   }
  // }
  .activeType {
    .right {
      .el-input {
        width: 150px !important;
      }
    }
  }
}
</style>
