<template>
  <div class="m-container">
    <!-- <h2><div class="squrt"></div>VIP活动方案新增 </h2> -->
    <h2>
      <el-page-header @back="onCancel" :content="title"></el-page-header>
    </h2>

    <el-steps
      :active="active"
      finish-status="success"
      align-center
      class="steps"
    >
      <el-step title="基础信息"></el-step>
      <el-step title="缴费信息"></el-step>
      <el-step title="课酬信息"></el-step>
    </el-steps>
    <div class="wrap">
      <baseInfo
        :baseForm="baseForm"
        v-if="active == 1"
        ref="baseForm"
        @resetPayInfo="resetPayInfo"
        :isDisabled="isDisabled"
        :status="statuss"
      />
      <payInfo
        :payForm="payForm"
        ref="payInfo"
        :activeType="baseForm.activityType"
        @changeCourseType="changeCourseType"
        @changeGiveCourseType="changeGiveCourseType"
        @chageSalary="chageSalary"
        @resetIsLimitNum="resetIsLimitNum"
        v-if="active == 2"
        :remberList="remberList"
        :isDisabled="isDisabled || statuss != 'DRAFT'"
      />
      <salaryInfo
        ref="salaryInfo"
        :salaryForm="salaryForm"
        v-if="active == 3"
        :activeType="baseForm.activityType"
        :payForm="payForm"
        :isDisabled="isDisabled || statuss != 'DRAFT'"
        :status="statuss"
      />
    </div>
    <el-button
      style="margin-top: 12px"
      type="primary"
      @click="prve"
      v-if="active > 1"
      >上一步</el-button
    >
    <el-button
      style="margin-top: 12px"
      type="primary"
      @click="next"
      v-if="active < 3"
      >下一步</el-button
    >

    <el-button
      style="margin-top: 12px"
      type="danger"
      @click="save"
      v-if="!isDisabled && statuss == 'DRAFT'"
      >保存草稿</el-button
    >
    <el-button
      style="margin-top: 12px"
      type="danger"
      @click="submit"
      v-if="active == 3 && !isDisabled && statuss == 'DRAFT'"
      >创建活动</el-button
    >
    <el-button
      style="margin-top: 12px"
      type="danger"
      @click="submit"
      v-if="active == 3 && !isDisabled && statuss != 'DRAFT'"
      >提交修改</el-button
    >
  </div>
</template>

<script>
import baseInfo from "./modals/baseInfo.vue";
import payInfo from "./modals/payInfo.vue";
import salaryInfo from "./modals/salaryInfo.vue";
import { getAllmemberRank } from "@/views/categroyManager/productSystem/api";
import merge from "webpack-merge";
import {
  vipGroupCategory,
  addVipActive,
  resetVipActive,
  getVipGroupActivity,
} from "@/api/vipSeting";
import cleanDeep from "clean-deep";
const payBaseForm = {
  courseType: "",
  vipGroupCategoryIdList: "",
  applyToStudentType: [],
  teachMode: null,
  allowOnlineToOffline: "",
  singleCourseTime: null,
  isLimitNum: null,
  minCourseNum: null,
  maxCourseNum: null,
  memberRankId: null,
  periodEnum: null,
  discount: 100,
  fullMinusCourseTimes: null,
  giveCourseType: null,
  giveTeachMode: null,
  giveCategoryId: null,
  giveSingleCourseTime: null,
  giveCourseNum: null,
  giveMemberRankId: null,
  giveMemberTime: null,
};
const baseSalaryForm = {
  vipOnlineSalarySettlement: {
    salarySettlementType: null,
    settlementValue: null,
  },
  vipOfflineSalarySettlement: {
    salarySettlementType: null,
    settlementValue: null,
  },
  giveVipOnlineSalarySettlement: {
    salarySettlementType: null,
    settlementValue: null,
  },
  giveVipOfflineSalarySettlement: {
    salarySettlementType: null,
    settlementValue: null,
  },
  practiceSalarySettlement: {
    salarySettlementType: null,
    settlementValue: null,
  },
  givePracticeSalarySettlement: {
    salarySettlementType: null,
    settlementValue: null,
  },
};
export default {
  components: {
    baseInfo,
    payInfo,
    salaryInfo,
  },
  data() {
    return {
      status: "DRAFT",
      active: 1,
      baseForm: {
        name: "",
        description: "",
        activeTime: [],
        courseTime: [],
        organ: [],
        activityType: "",
        applyToStudentType: [],
        studentMaxUsedTimes: "",
        isPayToBalance: "",
        marketPrice: "",
      },
      title: "新建课程活动方案",
      payForm: {
        ...payBaseForm,
      },
      salaryForm: {
        ...baseSalaryForm,
      },
      remberList: [],
    };
  },
  async mounted() {
    try {
      const res = await getAllmemberRank();
      this.remberList = res.data;
    } catch {}

    if (this.$route.query.id) {
      this.baseForm.id = this.$route.query.id;
      const rusult = await getVipGroupActivity({ id: this.$route.query.id });
      this.formatDetail(rusult.data);
    } else {
      this.payInfo = { ...payBaseForm };
      this.salaryForm = JSON.parse(JSON.stringify({ ...baseSalaryForm }));
    }
  },
  methods: {
    onCancel() {
      // if (this.active > 1) {
      //   this.active--;
      //   console.log(this.active);
      // } else {
      this.$store.dispatch("delVisitedViews", this.$route);
      this.$router.push({
        path: "/vipActiveManager/vipActiveList",
        query: { rules: this.rules, searchForm: this.searchForm },
      });
      // }
    },
    next() {
      let flags = true;
      if (this.active == 1) {
        this.$refs.baseForm.$refs.vipform.validate((flag) => {
          flags = flag;
        });
        // 验证表单1
      } else if (this.active == 2) {
        // 验证表单2
        this.$refs.payInfo.$refs.form.validate((flag) => {
          flags = flag;
        });
      }
      if (!flags) {
        return;
      }
      if (this.active < 3) {
        this.active++;
      }
    },
    prve() {
      if (this.active >= 2) {
        this.active--;
      }
    },
    resetPayInfo() {
      this.payForm = {
        ...payBaseForm,
      };
    },
    changeCourseType(val) {
      // this.$emit("changeCourseType", val);
      if (val == "PRACTICE") {
        this.$set(this.payForm, "vipGroupCategoryIdList", "");
        this.$set(this.payForm, "teachMode", "");
        this.$set(this.payForm, "singleCourseTime", 25);
        this.$set(this.payForm, "allowOnlineToOffline", []);
      } else {
        this.$set(this.payForm, "singleCourseTime", 45);
        this.$set(this.payForm, "allowOnlineToOffline", []);
        this.$set(this.payForm, "vipGroupCategoryIdList", "");
        this.$set(this.payForm, "teachMode", "");
      }
      // vip
      // 课程形式
      // 上课模式
      // 单课时长
      // 课程调整方式
      // PRACTICE
    },
    changeGiveCourseType(val) {
      if (val == "PRACTICE") {
        this.$set(this.payForm, "giveSingleCourseTime", 25);
      } else if (val == "VIP") {
        this.$set(this.payForm, "giveSingleCourseTime", 45);
      } else {
        this.$set(this.payForm, "giveSingleCourseTime", null);
      }
      this.$set(this.payForm, "giveCourseNum", null);
      this.$set(this.payForm, "giveCategoryId", null);
      this.$set(this.payForm, "giveMemberRankId", null);
      this.$set(this.payForm, "givePeriod", null);
      this.$set(this.payForm, "giveTeachMode", "");
    },
    chageSalary() {
      this.salaryForm = null;
      this.salaryForm = JSON.parse(JSON.stringify({ ...baseSalaryForm }));

      this.$forceUpdate();
    },
    resetIsLimitNum() {
      this.$set(this.payForm, "maxCourseNum", null);
      this.$set(this.payForm, "minCourseNum", null);
    },
    async submit() {
      this.$refs.salaryInfo.$refs.salaryForm.validate((flag) => {
        if (flag) {
          this.baseForm.status = "PROGRESS";
          this.submitDataFormat("PROGRESS");
        }
      });
    },
    save() {
      this.baseForm.status = "DRAFT";
      this.submitDataFormat("DRAFT");
    },
    submitDataFormat(status) {
      let coursesStartTime = null,
        coursesEndTime = null,
        startTime = null,
        endTime = null;
      if (this.baseForm.courseTime && this.baseForm.courseTime.length > 0) {
        coursesStartTime = this.baseForm.courseTime[0];
        coursesEndTime = this.baseForm.courseTime[1];
      }
      if (this.baseForm.activeTime && this.baseForm.activeTime.length > 0) {
        startTime = this.baseForm.activeTime[0];
        endTime = this.baseForm.activeTime[1];
      }
      let organId = this.baseForm.organ.join(",");
      this.baseForm.studentMaxUsedTimes
        ? this.baseForm.studentMaxUsedTimes
        : (this.baseForm.studentMaxUsedTimes = -1);
      for (let item in this.salaryForm) {
        if (this.salaryForm[item].salarySettlementType == "TEACHER_DEFAULT") {
          this.salaryForm[item].settlementValue = null;
        }
      }
      let applyToStudentType = this.baseForm.applyToStudentType.join(",");
      // let vipGroupCategoryIdList =
      //   this.payForm.vipGroupCategoryIdList.join(",");
      let vipGroupSalarySettlement = this.salaryForm;
      let obj = {
        ...this.baseForm,
        ...this.payForm,
        organId,
        coursesStartTime,
        coursesEndTime,
        startTime,
        endTime,
        applyToStudentType,
        vipGroupSalarySettlement,
      };
      if (this.baseForm.id) {
        resetVipActive(cleanDeep(obj)).then((res) => {
          if (res.code == 200) {
            if (status == "DRAFT") {
              this.$message.success("恭喜你,保存草稿成功");
              this.baseForm.id = res.data.id;
              this.$router.push({
                query: merge(this.$route.query, {
                  id: res.data.id,
                }),
              });
              this.formatDetail(res.data);
            } else {
              localStorage.removeItem("newVip");
              localStorage.removeItem(`newPractice`);
              this.$message.success("活动修改成功");
              this.$store.dispatch("delVisitedViews", this.$route);
              this.$router.push({
                path: "/vipActiveManager/vipActiveList",
              });
            }

            // this.onReSet();
            // this.$store.dispatch("delVisitedViews", this.$route);
            // this.$router.push({
            //   path: "/vipActiveManager/vipActiveList",
            // });
          }
        });
      } else {
        addVipActive(cleanDeep(obj)).then((res) => {
          if (res.code == 200) {
            if (status == "DRAFT") {
              this.$message.success("恭喜你,保存草稿成功");
              this.baseForm.id = res.data.id;
              this.$nextTick(()=>{
                 this.formatDetail(res.data);
              })
              this.$router.push({
                query: merge(this.$route.query, {
                  id: res.data.id,
                }),
              });

            } else {
              this.$message.success("活动创建成功");
              this.$store.dispatch("delVisitedViews", this.$route);
              this.$router.push({
                path: "/vipActiveManager/vipActiveList",
              });
            }
          }
        });
      }
    },
    formatDetail(data) {
      this.status = data.status;
      for (let item in data) {
        if (!(item == "teachMode" || item == "giveTeachMode")) {
          if (data[item] == -1) {
            data[item] = null;
          }
        }
      }
      let activeTime = [];
      let courseTime = [];
      this.title = data.name;
      if (data.startTime) {
        activeTime = [data.startTime, data.endTime];
      }
      if (data.coursesStartTime) {
        courseTime = [data.coursesStartTime, data.coursesEndTime];
      }
      let applyToStudentType = data.applyToStudentType
        ? data.applyToStudentType.split(",")
        : [];
      // 格式化 baseForm
      console.log(data.studentMaxUsedTimes);
      this.$set(this, "baseForm", {
        name: data.name,
        description: data.description,
        activeTime,
        courseTime,
        marketPrice: data.marketPrice,
        organ: data.organId.split(",").map((organ) => {
          return Number(organ);
        }),
        activityType: data.activityType,
        applyToStudentType,
        studentMaxUsedTimes: data.studentMaxUsedTimes,
        isPayToBalance: Number(data.payToBalance),
        id: this.$route.query.id,
      });
      // this.baseForm = {
      //   name: data.name,
      //   description: data.description,
      //   activeTime,
      //   courseTime,
      //   marketPrice: data.marketPrice,
      //   organ: data.organId.split(",").map((organ) => {
      //     return Number(organ);
      //   }),
      //   activityType: data.activityType,
      //   applyToStudentType,
      //   studentMaxUsedTimes,
      //   isPayToBalance: Number(data.payToBalance),
      //   id: this.$route.query.id,
      // };
      // this.$set()
      //格式化payForm
      // console.log(data.vipGroupCategoryIdList
      //     .split(",")
      //     .map((id) => {
      //       return Number(id);
      //     }),)
      this.payForm = {
        courseType: data.courseType,
        vipGroupCategoryIdList: data.vipGroupCategoryIdList
          ? data.vipGroupCategoryIdList.split(",").map((id) => {
              return Number(id);
            })[0]
          : null,
        teachMode: data.teachMode + "",
        allowOnlineToOffline: data.allowOnlineToOffline + "",
        singleCourseTime: data.singleCourseTime,
        isLimitNum: data.minCourseNum ? true : false,
        minCourseNum: data.minCourseNum,
        maxCourseNum: data.maxCourseNum,
        memberRankId: data.memberRankId,
        periodEnum: data.periodEnum,
        discount: data.discount,
        fullMinusCourseTimes: data.fullMinusCourseTimes,
        giveCourseType: data.giveCourseType,
        giveTeachMode: data.giveTeachMode + "",
        giveCategoryId:
          data.giveCategoryId * 1 ? data.giveCategoryId * 1 : null,
        giveSingleCourseTime: data.giveSingleCourseTime,
        giveCourseNum: data.giveCourseNum,
        giveMemberRankId: data.giveMemberRankId,
        givePeriod: data.givePeriodEnum,
        giveMemberTime: data.giveMemberTime ? data.giveMemberTime : null,
      };
      // 格式化缴费金额
      console.log(data.salarySettlementJson);
      if (data.salarySettlementJson && data.salarySettlementJson != "null") {
        this.salaryForm = JSON.parse(JSON.stringify({ ...baseSalaryForm }));
        let result = JSON.parse(data.salarySettlementJson);

        for (let key in result) {
          this.salaryForm[key] = result[key];
        }
      } else {
        this.salaryForm = JSON.parse(JSON.stringify({ ...baseSalaryForm }));
      }
      this.$forceUpdate();
    },
  },
  computed: {
    isDisabled() {
      if (this.$route.query.type == "look") {
        return true;
      } else {
        return false;
      }
    },
    statuss() {
      return this.status;
    },
  },
};
</script>
<style lang="scss" scoped>
.steps {
  margin-top: 30px;
}
/deep/.is-success {
  color: #14928a !important;
  border-color: #14928a !important;
}
</style>


