<template>
  <div class="m-container">
    <div class="payInfoWrap">
      <div class="left">
        <el-page-header
          @back="goback"
          style="padding-bottom: 30px"
          :content="
            $route.query.payUserType == 'SCHOOL' ? '学校缴费' : '学员缴费'
          "
        >
        </el-page-header>
        <div class="m-core">
          <el-form :inline="true" :model="form" label-width="120px" ref="form">
            <div class="payTitle">
              <div class="squrt"></div>
              <p>基础信息设置</p>
            </div>
            <el-form-item
              prop="paymentDate"
              :rules="[
                { required: true, message: '请选择缴费时间', trigger: 'blur' },
              ]"
            >
              <template slot="label">
                <p style="position: relative">
                  <span style="color: #f56c6c; margin-right: 4px">*</span>
                  缴费时间
                  <el-tooltip placement="top" popper-class="mTooltip">
                    <div slot="content">在改时间段内学员才可缴费</div>
                    <i
                      class="el-icon-question"
                      style="
                        font-size: 18px;
                        color: #f56c6c;
                        position: relative;
                        top: 2px;
                      "
                    ></i>
                  </el-tooltip>
                </p>
              </template>
              <el-date-picker
                v-model="form.paymentDate"
                type="daterange"
                style="width: 280px"
                :picker-options="{ firstDayOfWeek: 1 }"
                value-format="yyyy-MM-dd"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>
            <el-row>
              <el-form-item
                prop="memo"
                :rules="[
                  { required: true, message: '请输入备注', trigger: 'blur' },
                ]"
              >
                <template slot="label">
                  <p style="position: relative">
                    <span style="color: #f56c6c; margin-right: 4px">*</span>
                    备注
                    <el-tooltip placement="top" popper-class="mTooltip">
                      <div slot="content">本次缴费的内容描述</div>
                      <i
                        class="el-icon-question"
                        style="
                          font-size: 18px;
                          color: #f56c6c;
                          position: relative;
                          top: 2px;
                        "
                      ></i>
                    </el-tooltip>
                  </p>
                </template>
                <el-input
                  type="textarea"
                  style="width: 280px"
                  :rows="2"
                  v-model="form.memo"
                  maxlength="50"
                  show-word-limit
                ></el-input>
              </el-form-item>
            </el-row>
            <div class="payTitle">
              <div class="squrt"></div>
              <p>基础项目配置</p>
            </div>
            <div class="checkWrap">
              <div
                class="checkBtn"
                :class="[
                  teamCourse ? 'active' : '',
                  teamCourseDisabled ? 'disabled' : '',
                ]"
                @click.prevent="
                  () => {
                    if (teamCourseDisabled) return;
                    teamCourse = !teamCourse;
                    if (teamCourse && form.eclass.length < 0) {
                      form.eclass = [];
                      form.eclass.push({});
                    }
                  }
                "
              >
                <p>乐团课</p>
                <el-checkbox
                  v-model="teamCourse"
                  :disabled="teamCourseDisabled"
                ></el-checkbox>
              </div>
              <div
                class="checkBtn"
                :class="[
                  member ? 'active' : '',
                  memberDisabled ? 'disabled' : '',
                ]"
                @click.prevent="
                  () => {
                    if (memberDisabled) return;
                    member = !member;
                    if (member && form.memberList.length < 0) {
                      form.memberList = [];
                      form.memberList.push({});
                    }
                  }
                "
              >
                <p>团练宝</p>
                <el-checkbox
                  v-model="member"
                  :disabled="memberDisabled"
                ></el-checkbox>
              </div>
              <div
                v-if="isShowLeBao"
                class="checkBtn"
                :class="[
                  leBao ? 'active' : '',
                  leBaoDisabled ? 'disabled' : '',
                ]"
                @click.prevent="
                  () => {
                    if (leBaoDisabled) return;
                    leBao = !leBao;
                    if (leBao && form.leBaoList.length < 0) {
                      form.leBaoList = [];
                      form.leBaoList.push({});
                    }
                  }
                "
              >
                <p>乐保</p>
                <el-checkbox
                  v-model="leBao"
                  :disabled="leBaoDisabled"
                ></el-checkbox>
              </div>
              <div
                class="checkBtn"
                :class="[
                  teamActive ? 'active' : '',
                  teamActiveDisabled ? 'disabled' : '',
                ]"
                @click.prevent="
                  () => {
                    if (teamActiveDisabled) return;
                    teamActive = !teamActive;
                    if (teamActive && form.activeList.length < 0) {
                      form.activeList = [];
                      form.activeList.push({});
                    }
                  }
                "
              >
                <p>乐团活动</p>
                <el-checkbox
                  v-model="teamActive"
                  :disabled="teamActiveDisabled"
                ></el-checkbox>
              </div>
            </div>
            <div class="coreList">
              <payTeamCourse
                :form="form"
                :charges="charges"
                :courseUnitPriceSettingsByType="
                  organizationCourseUnitPriceSettingsByType
                "
                v-if="teamCourse"
                @create="addExtraClass"
                @remove="removeExtraClass"
                @moneyChange="syncAllMoney"
                @priceChange="priceChange"
              />
              <payMember
                :memberRankList="memberRankList"
                @moneyChange="syncAllMoney"
                @priceChange="priceChange"
                :rulesForm="rulesForm"
                :organId="organId"
                :form="form"
                v-if="member"
              />
              <payLeBao :form="form" v-if="leBao" :leBaoInfo="leBaoInfo" />
              <payTeamActive
                :form="form"
                v-if="teamActive"
                :activeList="activeList"
                @create="addActive"
                @remove="removeActive"
              />
            </div>
          </el-form>
          <div v-if="!teamCourse && !member && !leBao && !teamActive">
            <empty desc="暂无缴费项目配置" />
          </div>
          <div v-else class="submitBtn" @click="submitForm">确认提交</div>
        </div>
      </div>
    </div>
    <el-dialog
      title="报名声部预览"
      :visible.sync="dialogSubjectVisible"
      width="400px"
      class="subjectPreview"
    >
      <subject-preview
        :preViewData="preViewData"
      ></subject-preview>
    </el-dialog>
  </div>
</template>
<script>
import payTeamCourse from "../modals/payTeamCourse";
import payMember from "../modals/payMember";
import payLeBao from "../modals/payLeBao";
import payTeamActive from "../modals/payTeamActive";
import numeral from "numeral";
import dayjs from "dayjs";
import subjectPreview from "@/views/resetTeaming/modals/subject-preview";
import {
  chargeTypeList,
  musicGroupOrganizationCourseSettingsQueryPage,
} from "@/api/specialSetting";
import { getSysTenantConfig } from "@/views/courseRulersManager/api";
import { sysConfigList } from "@/api/generalSettings";
import {
  queryByMusicGroupOrganizationCourseSettingsId,
  getAllmemberRank,
  musicGroupcreateCalender,
  musicGroupresetCalender,
} from "../api";
import { getMusicGroupPaymentCalenderDetail } from "@/api/buildTeam";
import { vipGroupActivity } from "@/api/vipSeting";
export default {
  components: {
    payTeamCourse,
    payMember,
    payLeBao,
    payTeamActive,
  },
  data() {
    return {
      form: {
        paymentType: "",
        memo: "",
        eclass: [{}],
        memberList: [
          {
            period: "",
            num: "",
            actualAmount: "",
            memberRankSettingId: "",
            optionalFlag: null,
          },
        ],
        leBaoList: [{}],
        activeList: [{}],

        leixing: "2",
      },
      teamCourse: false,
      teamCourseDisabled: false,
      member: false,
      memberDisabled: false,
      teamActive: false,
      teamActiveDisabled: false,
      leBao: false,
      leBaoDisabled: false,
      organizationCourseUnitPriceSettings: null,
      baseInfo: null,
      courseViewType: null,
      charges: null, // 乐团类型对应的收费方式
      memberRankList: [],
      organId: null,
      leBaoInfo: null,
      isShowLeBao: false,
      isSetCourseSettingsId: false,
      activeList: [{}],
      submitList: [],
      organizationCourseUnitPriceSettingsByType: null,
      rulesForm: {
        minMonthFee: null,
        maxMonthFee: null,
        minQuarterlyFee: null,
        maxQuarterlyFee: null,
        minHalfYearFee: null,
        maxHalfYearFee: null,
        minYearFee: null,
        maxYearFee: null,
      },
      dialogSubjectVisible: false, // 预览
      preViewData: {}
    };
  },
  mounted() {
    this.organizationCourseUnitPriceSettings = JSON.parse(
      localStorage.getItem("organizationCourseUnitPriceSettings")
    );
    this.baseInfo = JSON.parse(localStorage.getItem("payMusicBase"));
    // 判断乐团状态 缴费类型

    this.init();
  },
  methods: {
    async init() {
      this.organId = this.musicGroup?.organId;
      this.courseViewType = this.baseInfo?.musicGroup?.courseViewType;
      if (
        this.courseViewType != 2 &&
        this.$route.query.team_status == "PRE_BUILD_FEE"
      ) {
        // 课程团的创建缴费
        this.teamCourse = true;
        this.teamCourseDisabled = true;
        this.form.paymentType = "MUSIC_APPLY";
      } else if (
        this.courseViewType == 2 &&
        this.$route.query.team_status == "PRE_BUILD_FEE"
      ) {
        // 会员团的创建缴费
        this.member = true;
        this.memberDisabled = true;
      }
      if (this.$route.query.payUserType == "SCHOOL") {
        this.member = false;
        this.memberDisabled = true;
        this.leBao = false;
        this.teamActive = false;
        this.leBaoDisabled = true;
        this.teamActiveDisabled = true;
      }
      await this.getCharges(); // 续费的选择缴费类型
      await this.formatCourse(); // 临时加课的类型选择以及价格
      await this.getMemberList(); // 获取会员(团练保信息)
      await this.getLeBao(); // 获取乐保
      await this.getActive(); // 获取活动
      await this.getMemberRules()
      if (this.$route.query.calenderId) {
        // 说明是修改  查缴项目详情
        getMusicGroupPaymentCalenderDetail({
          id: this.$route.query.calenderId,
        }).then((res) => {
          if (res.code == 200) {
            if (res.data?.calender?.musicGroupOrganizationCourseSettingId) {
              this.form.leixing = "1";
              this.form.musicGroupOrganizationCourseSettingId =
                res.data?.calender?.musicGroupOrganizationCourseSettingId;
            } else {
              this.form.leixing = "2";
            }
            this.$set(this.form, "paymentDate", [
              res.data?.calender?.startPaymentDate,
              res.data?.calender?.deadlinePaymentDate,
            ]);
            this.$set(this.form, "memo", res.data?.calender?.memo);
            this.$set(
              this.form,
              "payUserType",
              res.data?.calender?.payUserType
            );

            if (res.data.member) {
              // 团练保
              this.member = true;
              this.$set(this.form, "memberList", [{ ...res.data.member }]);
            }
            if (res.data.repair) {
              this.leBao = true;
              this.$set(this.form, "leBaoList", [{ ...res.data.repair }]);
            }
            if (res.data?.course?.length > 0) {
              this.$nextTick(() => {
                this.teamCourse = true;
                this.isSetCourseSettingsId = true;
                this.$set(this.form, "eclass", res.data?.course);
              });
            }
            if (res.data?.activity?.length > 0) {
              this.teamActive = true;

              this.$set(this.form, "activeList", res.data.activity);
              this.form.activeList.forEach((active) => {
                active.vipGroupCategoryNames = active.categoryName;
              });
            }
          }
        });
      }
      if (this.submitList.length > 0) {
        this.$bus.$emit("showguide", this.submitList);
        return;
      }
    },
    getActive() {
      return vipGroupActivity({
        organId: this.organId,
        rows: 10,
        page: 1,
        status: "PROGRESS",
        activityChannel: 1,
        enable: true,
      }).then((res) => {
        if (res.code == 200) {
          this.activeList = res.data.rows;
          if (this.activeList.length <= 0) {
            this.submitList.push("teamActive");
            // this.$bus.$emit("showguide", ["teamCourseFee"]);
          }
        }
      });
    },
    async getMemberRules() {
      try {
        const res = await sysConfigList({ group: "DEFAULT" });
        const paramName = "cloud_price_range";
        res.data.forEach((item) => {
          if (item.paramName == paramName) {
            const itemValue = item.paranValue
              ? JSON.parse(item.paranValue)
              : null;
            if (itemValue) {
              this.rulesForm = itemValue;
            }

          }
        });
      } catch (e) {
        console.log(e);
      }
    },
    async getLeBao() {
      try {
        const res = await getSysTenantConfig({ group: "MUSIC_REPAIR" });
        this.leBaoInfo = res.data;
        res.data.forEach((element) => {
          if (element.id == 188) {
            this.isShowLeBao = !!element.paranValue;
          }
        });
        // this.$forceUpdate()
      } catch (e) {
        console.log(e);
      }
    },
    async getMemberList() {
      try {
        const res = await getAllmemberRank({ isDefault: 0 });
        this.memberRankList = res.data;
      } catch (e) {
        console.log(e);
      }
    },
    async getCharges() {
      const organId = this.musicGroup?.organId;
      const chargeTypeId = this.musicGroup?.chargeTypeId;
      this.chargeTypeName = this.musicGroup?.chargeTypeName;
      try {
        const res = await musicGroupOrganizationCourseSettingsQueryPage({
          row: 9999,
          chargeTypeId,
          organId,
        });
        const ids = res.data.rows.map((item) => item.id);
        if (!ids.includes(this.form.musicGroupOrganizationCourseSettingId)) {
          this.$set(this.form, "musicGroupOrganizationCourseSettingId", null);
        }
        this.charges = res.data.rows;
        // this.charges =[];
        if (this.charges.length <= 0) {
          this.submitList.push("teamCourseType");
        }
      } catch (error) {}
    },
    goback() {
      let query = { ...this.$route.query };
      query.calenderId = null;
      if (query.type == "resetTeam") {
        this.$store.dispatch("delVisitedViews", this.$route);
        this.$router.push({
          path: "/business/resetTeaming",
          query,
        });
      } else if (query.type == "look") {
        this.$store.dispatch("delVisitedViews", this.$route);
        this.$router.push({
          path: "/business/resetTeaming",
          query,
        });
      } else if (query.type == "PRE_BUILD_FEE" || query.type == "feeAudit") {
        this.$store.dispatch("delVisitedViews", this.$route);
        this.$router.push({
          path: "/business/resetTeaming",
          query,
        });
      }
    },
    formatCourse() {
      // 格式化课程类型
      const organId = this.musicGroup?.organId;
      const chargeTypeId = this.musicGroup?.chargeTypeId;
      const _ = {};
      const list = (this.organizationCourseUnitPriceSettings || []).filter(
        (item) =>
          organId &&
          organId == item.organId &&
          chargeTypeId &&
          chargeTypeId == item.chargeTypeId
      );
      for (const item of list) {
        _[item.courseType] = item;
      }
      this.organizationCourseUnitPriceSettingsByType = _;
      return _;
    },
    priceChange(item, index) {
      const _ = [...this.form.eclass];
      const active =
        this.organizationCourseUnitPriceSettingsByType[item.courseType] || {};
      const price = Math.round(
        numeral(active.unitPrice || 1)
          .multiply(item.courseTotalMinuties || 1)
          .value()
      );
      item.courseCurrentPrice = price;
      item.courseOriginalPrice = price;
      _[index] = item;
      this.$set(this.form, "eclass", [..._]);
      this.syncAllMoney();
    },
    syncAllMoney() {
      let money = 0;
      let first = 0;
      let other = 0;
      let classs = this.form.eclass;
      for (const item of classs) {
        money += item.courseCurrentPrice;
        if (this.cycles && this.cycles.length) {
          if (item.isStudentOptional) {
            first += item.courseCurrentPrice;
          } else {
            const floorMoney = Math.floor(
              item.courseCurrentPrice / this.cycles.length
            );
            const remainder = item.courseCurrentPrice % this.cycles.length;
            first += floorMoney + remainder;
            other += floorMoney;
          }
        }
      }

      // if (!money) {
      // this.$set(this.cycle, "paymentAmount", undefined);
      // } else {
      // this.$set(this.cycle, "paymentAmount", money);
      // }
      // money += parseFloat(this.memberForm.memberPaymentAmount || 0);
      // this.money = money;
      return money;
    },
    addExtraClass() {
      this.form.eclass.push({});
    },
    addActive() {
      this.form.activeList.push({});
    },
    removeActive(index) {
      this.form.activeList[index] = null;
      this.$set(
        this.form,
        "activeList",
        this.form.activeList.filter((item) => !!item)
      );
    },
    removeExtraClass(index) {
      this.form.eclass[index] = null;
      this.$set(
        this.form,
        "eclass",
        this.form.eclass.filter((item) => !!item)
      );
      // this.form.eclass = this.form.eclass.filter((item) => !!item);
    },
    submitForm() {
      this.$refs.form.validate(async (isok) => {
        if (isok) {
          // const preViewData = this.formatPreviewData()
          // this.preViewData = preViewData
          // this.dialogSubjectVisible = true
          let obj = this.fommatDate();
          if (this.$route.query.calenderId) {
            obj.calenderId = this.$route.query.calenderId;
            try {
              const res = await musicGroupresetCalender(obj);
              this.$message.success("修改缴费成功");
              this.goback();
            } catch (e) {
              console.log(e);
            }
          } else {
            try {
              const res = await musicGroupcreateCalender(obj);
              this.$message.success("创建缴费成功");
              this.goback();
            } catch (e) {
              console.log(e);
            }
          }
        }
      });
    },

    formatPreviewData() {
      // 格式化预览数据
      const form = this.form
      // 重置小班课数据
      let activeList = form.activeList?.length > 0 ? form.activeList : []
      if(activeList.length > 0) {
        activeList.forEach(active => {
          active.categoryName = active.vipGroupCategoryNames
        })
      }
      return {
        musicGroup: this.musicGroup,
        activity: [...activeList], // 小班课
        course: form.eclass?.length > 0 ? form.eclass : [], // 课程
        member: form.memberList?.length > 0 ? { ...form.memberList[0] } : null, // 团练宝
        memberPrivilegesItemList: [], // 会员基本内容
        repair: form.leBaoList?.length > 0 ? { ...form.leBaoList[0] } : null, // 乐保
      }
    },
    fommatDate() {
      return {
        payUserType: this.$route.query.payUserType,
        musicGroupOrganizationCourseSettingId:
          this.form.musicGroupOrganizationCourseSettingId || null,
        memo: this.form.memo,
        startPaymentDate: this.form.paymentDate[0],
        deadlinePaymentDate: this.form.paymentDate[1],
        calenderActivityList:
          this.form.activeList?.length > 0 ? this.form.activeList : null,
        musicRepair:
          this.form.leBaoList?.length > 0
            ? { ...this.form.leBaoList[0] }
            : null,
        calenderMember:
          this.form.memberList?.length > 0
            ? { ...this.form.memberList[0] }
            : null,
        musicGroupPaymentCalenderCourseSettingsList:
          this.form.eclass?.length > 0 ? this.form.eclass : null,
        musicGroupId: this.$route.query.id,
      };
    },
  },
  watch: {
    teamCourse(val) {
      if (!val) {
        this.$set(this.form, "eclass",  [{}]);
        this.$set(this.form, "leixing", "2");
      }
    },
    member(val) {
      if (!val) {
        this.$set(this.form, "memberList",  [{}]);
      }
    },
    teamActive(val) {
      if (!val) {
        this.$set(this.form, "activeList",  [{}]);
      }
    },
    leBao(val) {
      if (!val) {
        this.$set(this.form, "leBaoList", [{}]);
      }
    },
    async "form.musicGroupOrganizationCourseSettingId"(val) {
      // && !this.rowDetail

      if (val && !this.isSetCourseSettingsId && !this.$route.query.calenderId) {
        try {
          const res = await queryByMusicGroupOrganizationCourseSettingsId({
            id: val,
          });
          this.$set(this.form, "eclass", res.data);
          // this.syncAllMoney();
        } catch (error) {}
      }
      this.isSetCourseSettingsId = false;
    },
    "form.leixing"(val) {
      this.cycles = [{}];
      this.collapse = [0];
      this.cycle = {};
      if (val != "1") {
        this.$set(
          this.form,
          "musicGroupOrganizationCourseSettingId",
          undefined
        );
      }

      // this.$set(this.cycle, "paymentAmount", undefined);
      // this.$set(this.other, "memo", null);
      if (val === "1" && !this.isSetCourseSettingsId) {
        this.$set(this.form, "eclass", []);
      } else if (val === "2") {
        this.$set(this.form, "eclass", [{}]);
      }
      this.isSetCourseSettingsId = false;
    },
  },
  computed: {
    musicGroup() {
      return this.baseInfo?.musicGroup;
    },
  },
};
</script>
<style lang="scss" scoped>
/deep/.el-form-item__label:before {
  content: "" !important;
  position: absolute;
  color: transparent;
  margin-right: 4px;
}
.payInfoWrap {
  .submitBtn {
    width: 121px;
    height: 41px;
    background: var(--color-primary);
    border-radius: 7px;
    margin: 20px auto;
    line-height: 40px;
    color: #fff;
    text-align: center;
    cursor: pointer;
  }
  .left {
    /deep/.el-checkbox {
      padding: 8px 10px 7px 10px;
      border-radius: 4px;
    }
    /deep/.el-checkbox .el-checkbox__inner {
      border-radius: 50%;
      border: 1px solid var(--color-primary);
      width: 16px;
      height: 16px;
      &:after {
        height: 8px;
        left: 5px;
      }
    }
    /deep/.el-checkbox__inner:hover {
      background-color: var(--color-primary);
    }
    /deep/.el-checkbox.is-checked {
      border-color: #fff;
      color: #fff;
    }
    .payTitle {
      display: flex;
      flex-direction: row;
      align-items: center;
      font-size: 18px;
      font-weight: 600;
      color: #1a1a1a;
      height: 25px;
      margin-bottom: 15px;
      p {
        line-height: 25px;
      }
      .squrt {
        width: 4px;
        height: 16px;
        background: var(--color-primary);
        margin-right: 5px;
        position: relative;
        top: -1px;
      }
    }
    .checkWrap {
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      .checkBtn.active {
        background-color: var(--color-primary);
        color: #fff;
        /deep/.el-checkbox .el-checkbox__inner {
          border: 1px solid #fff;
        }
      }
      .checkBtn {
        transition: border-color 0.25s cubic-bezier(0.71, -0.46, 0.29, 1.46),
          background-color 0.25s cubic-bezier(0.71, -0.46, 0.29, 1.46);
        transition-property: border-color, background-color;
        transition-duration: 0.25s, 0.25s;
        transition-timing-function: cubic-bezier(0.71, -0.46, 0.29, 1.46),
          cubic-bezier(0.71, -0.46, 0.29, 1.46);
        transition-delay: 0s, 0s;
        margin-right: 12px;
        padding-left: 14px;
        display: flex;
        flex-direction: row;
        align-items: center;
        cursor: pointer;
        background: rgba(20, 146, 138, 0.12);
        border-radius: 6px;
        height: 41px;
        &:hover {
          background-color: var(--color-primary);
          color: #fff;
          /deep/.el-checkbox__inner {
            background-color: var(--color-primary);
            border: 1px solid #fff;
          }
        }
        p {
          height: 41px;
          line-height: 41px;
        }
      }
      .checkBtn.disabled {
        cursor: not-allowed;
        color: #d9d9d9;
        background-color: #f2f2f2 !important;
        /deep/.el-checkbox__inner {
          background-color: #fff !important;
          border-color: #d9d9d9;
          color: #fff;
          &::after {
            border-color: #d9d9d9;
          }
        }
        &:hover {
          background-color: #f2f2f2 !important;
          color: #d9d9d9;
          /deep/.el-checkbox__inner {
            background-color: #fff !important;
          }
        }
      }
    }
  }
}
</style>
