<template>
  <div class="m-container1">
    <el-page-header
      @back="goback"
      style="padding: 20px"
      :content="$route.query.payUserType == 'SCHOOL' ? '学校缴费' : '学员缴费'"
    >
    </el-page-header>
    <div class="payInfoWrap">
      <div class="left">
        <!-- <div class="Wall"></div> -->
        <div class="m-core1">
          <el-form :inline="true" :model="form" label-width="120px" ref="form">
            <div :class="isField ? 'baseWrapFixed' : 'baseWrap'">
              <div class="payTitle">
                <div class="squrt"></div>
                <p>基础项目配置</p>
                <div class="payContext">请选择您需要的课程配置</div>
                <el-form-item
                  label="计价标准"
                  class="vertical"
                  prop="isShowMusicInsuranceForPay"
                  v-if="$route.query.payUserType == 'SCHOOL'"
                >
                  <el-select
                    size="mini"
                    v-model="form.calenderFeeType"
                    placeholder="请选择计价标准"
                  >
                    <el-option label="按学生" value="STUDENT"> </el-option>
                    <el-option
                      label="按老师"
                      value="TEACHER"
                      :disabled="!teamCourse"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
              <div class="checkWrap">
                <div
                  class="checkBtn"
                  :class="[
                    teamCourse ? 'active' : '',
                    teamCourseDisabled ? 'disabled' : ''
                  ]"
                  :style="{ opacity: teamCourseDisabled ? '0.5' : '1' }"
                  @click.prevent="
                    () => {
                      if (teamCourseDisabled) return;
                      teamCourse = !teamCourse;

                      if (teamCourse && form.eclass.length < 0) {
                        form.eclass = [];
                        form.eclass.push({});
                      }
                      if (!teamCourse) {
                        form.calenderFeeType = 'STUDENT';
                      }
                      // 会员收费 创建续费 默认选中，不可取消选中
                      if (
                        courseViewType == 2 &&
                        $route.query.team_status == 'PROGRESS'
                      ) {
                        member = false;
                        memberDisabled = false;
                        if (teamCourse) {
                          member = true;
                          memberDisabled = true;
                          if (member && form.memberList.length < 0) {
                            form.memberList = [];
                            form.memberList.push({});
                          }
                        }
                      }
                    }
                  "
                >
                  <div class="checkLeft">
                    <img src="../images/checkIcon1.png" alt="" />
                  </div>
                  <div class="checkRight">
                    <p>乐团课</p>
                    <p class="checkSubTitle">创建课程类型标准</p>
                  </div>
                  <div class="checTriangle" v-if="teamCourse">
                    <img src="../images/checkGou.png" alt="" />
                  </div>
                  <!-- <el-checkbox
                    v-model="teamCourse"
                    :disabled="teamCourseDisabled"
                  ></el-checkbox> -->
                </div>
                <div
                  class="checkBtn"
                  :class="[
                    member ? 'active' : '',
                    memberDisabled ? 'disabled' : ''
                  ]"
                  :style="{ opacity: memberDisabled ? '0.5' : '1' }"
                  @click.prevent="
                    () => {
                      if (memberDisabled) return;
                      member = !member;
                      if (member && form.memberList.length < 0) {
                        form.memberList = [];
                        form.memberList.push({});
                      }
                    }
                  "
                >
                  <div class="checkLeft">
                    <img src="../images/checkIcon2.png" alt="" />
                  </div>
                  <div class="checkRight">
                    <p>云练习</p>
                    <p class="checkSubTitle">乐团训练工具</p>
                  </div>
                  <div class="checTriangle" v-if="member">
                    <img src="../images/checkGou.png" alt="" />
                  </div>
                </div>
                <div
                  v-if="
                    isShowLeBao &&
                      tenantId == 1 &&
                      $route.query.team_status != 'PROGRESS'
                  "
                  class="checkBtn"
                  :class="[
                    leBao ? 'active' : '',
                    leBaoDisabled ? 'disabled' : ''
                  ]"
                  :style="{ opacity: leBaoDisabled ? '0.5' : '1' }"
                  @click.prevent="
                    () => {
                      if (leBaoDisabled) return;
                      leBao = !leBao;
                      if (leBao && form.leBaoList.length < 0) {
                        form.leBaoList = [];
                        form.leBaoList.push({});
                      }
                    }
                  "
                >
                  <div class="checkLeft">
                    <img src="../images/checkIcon3.png" alt="" />
                  </div>
                  <div class="checkRight">
                    <p>乐保</p>
                    <p class="checkSubTitle">乐器维修保养</p>
                  </div>
                  <div class="checTriangle" v-if="leBao">
                    <img src="../images/checkGou.png" alt="" />
                  </div>
                </div>
                <div
                  class="checkBtn"
                  :class="[
                    teamActive ? 'active' : '',
                    teamActiveDisabled ? 'disabled' : ''
                  ]"
                  :style="{ opacity: teamActiveDisabled ? '0.5' : '1' }"
                  @click.prevent="
                    () => {
                      if (teamActiveDisabled) return;
                      teamActive = !teamActive;
                      if (teamActive && form.activeList.length < 0) {
                        form.activeList = [];
                        form.activeList.push({});
                      }
                    }
                  "
                >
                  <div class="checkLeft">
                    <img src="../images/checkIcon4.png" alt="" />
                  </div>
                  <div class="checkRight">
                    <p>小课</p>
                    <p class="checkSubTitle">创建活动课程方案</p>
                  </div>
                  <div class="checTriangle" v-if="teamActive">
                    <img src="../images/checkGou.png" alt="" />
                  </div>
                </div>
              </div>
            </div>
            <div class="wall" style="height: 184px" v-if="isField"></div>
            <div class="coreList">
              <payTeamCourse
                :form="form"
                :charges="charges"
                :courseUnitPriceSettingsByType="
                  organizationCourseUnitPriceSettingsByType
                "
                v-if="teamCourse"
                @create="addExtraClass"
                @remove="removeExtraClass"
                @moneyChange="syncAllMoney"
                @priceChange="priceChange"
                @priceChange2="priceChange2"
              />
              <payMember
                ref="payMember"
                :memberRankList="memberRankList"
                @moneyChange="syncAllMoney"
                @priceChange="priceChange"
                :rulesForm="rulesForm"
                :organId="organId"
                :showAutoActivationFlag="showAutoActivationFlag"
                :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"
              />
              <paySchoolInfo
                :form="form"
                :courseUnitPriceSettingsByType="
                  organizationCourseUnitPriceSettingsByType
                "
                :teamCourse="teamCourse"
                :member="member"
                :teamActive="teamActive"
                :leBao="leBao"
                @setAllTotal="setAllTotal"
                v-if="$route.query.payUserType == 'SCHOOL'"
                @checkType="checkType"
              />
              <backMoney
                v-if="
                  $route.query.payUserType == 'SCHOOL' &&
                    form.currentTotalAmount > 0
                "
                :form="form"
              />
            </div>
            <div
              class="teamCourseList coreList"
              v-if="$route.query.payUserType == 'STUDENT'"
            >
              <div class="coreTitle">
                <p>基础信息设置</p>
              </div>
              <el-row :gutter="20">
                <el-col style="width: 430px">
                  <el-form-item
                    prop="paymentDate"
                    :rules="[
                      {
                        required: true,
                        message: '请选择缴费时间',
                        trigger: 'blur'
                      }
                    ]"
                    ref="paymentDate"
                  >
                    <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-col>
                <el-col style="width: 430px">
                  <!--           :rules="[
                      {
                        required: true,
                        message: '请选择缴费时间',
                        trigger: 'blur',
                      },
                    ]" -->
                  <el-form-item prop="isShowSalePrice" ref="isShowSalePrice">
                    <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-select v-model="form.isShowSalePrice">
                      <el-option label="是" :value="true"> </el-option>
                      <el-option label="否" :value="false"> </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col class="memoWrap">
                  <el-form-item
                    class="memoWrapItem"
                    prop="memo"
                    :rules="[
                      {
                        required: true,
                        message: '请输入备注',
                        trigger: 'blur'
                      }
                    ]"
                    ref="memo"
                  >
                    <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
                      style="width: 100%"
                      :rows="3"
                      v-model="form.memo"
                      type="textarea"
                      maxlength="50"
                      show-word-limit
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-form>
          <div
            v-if="
              !teamCourse &&
                !member &&
                !leBao &&
                !teamActive &&
                $route.query.team_status == 'PROGRESS'
            "
          >
            <empty desc="暂无缴费项目配置" />
          </div>
          <div v-else style="text-align: center">
            <el-button class="submitBtn" @click="submitForm">确认</el-button>
          </div>
          <!-- <div  style="text-align: center">
            <el-button class="submitBtn" @click="submitForm">确认</el-button>
          </div> -->
        </div>
      </div>
    </div>
    <el-dialog
      title="报名声部预览"
      :visible.sync="dialogSubjectVisible"
      width="400px"
      class="subjectPreview"
      v-if="dialogSubjectVisible"
    >
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane
          :label="subject.subName"
          lazy
          v-for="(subject, index) in dialogSubjectList"
          :key="index"
          :name="subject.subjectId.toString()"
          style="max-height: 500px; overflow-y: auto"
        >
          <subject-preview
            :subjectId="subject.subjectId"
            :preViewData="preViewData"
          ></subject-preview>
        </el-tab-pane>
      </el-tabs>

      <div>
        <el-button
          style="width: 100%; border-radius: 0; line-height: 30px"
          size="medium"
          type="primary"
          @click="onSubmit"
          >确认提交</el-button
        >
      </div>
    </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 paySchoolInfo from "../modals/paySchoolInfo";
import backMoney from "../modals/backMoney";
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,
  getAutoActivationFlag
} from "../api";
import {
  getMusicGroupPaymentCalenderDetail,
  findMusicGroupSubjectInfo,
  getAgreement
} from "@/api/buildTeam";
import { vipGroupActivity } from "@/api/vipSeting";
export default {
  components: {
    payTeamCourse,
    payMember,
    payLeBao,
    payTeamActive,
    subjectPreview,
    paySchoolInfo,
    backMoney
  },
  data() {
    return {
      form: {
        paymentType: "",
        memo: "",
        eclass: [{}],
        memberList: [
          {
            period: "",
            num: "",
            name: "",
            actualAmount: "",
            memberRankSettingId: "",
            optionalFlag: null,
            autoActivationFlag: false
          }
        ],
        leBaoList: [{}],
        activeList: [{}],
        teacherFeeList: [],
        isShowMemberForPay: true,
        isShowMusicInsuranceForPay: true,
        isShowVipCourseForPay: true,
        isShowMusicCourseForPay: true,
        leixing: "1",
        isShowSalePrice: true,
        calenderFeeJson: {
          discountTotal: "",
          allTotal: "",
          sutdentNumber: ""
        },
        calenderFeeType: "STUDENT",
        musicGroupCalenderRefundPeriods: [{ refundDate: "", refundAmount: "" }],
        currentTotalAmount: 0,
        contractUrl: ""
      },
      teamCourse: false,
      member: false,
      teamActive: false,
      leBao: false,
      memberDisabled: false,
      teamCourseDisabled: false,
      teamActiveDisabled: 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, // 预览
      dialogSubjectList: [],
      activeName: null,
      preViewData: {},
      tenantId: null,
      isField: false,
      showAutoActivationFlag: false,
      initDetail: false
    };
  },
  mounted() {
    let tenantConfig = sessionStorage.getItem("tenantConfig");
    tenantConfig = tenantConfig ? JSON.parse(tenantConfig) : {};
    if (tenantConfig.tenantId && tenantConfig.tenantId != "undefined") {
      this.tenantId = tenantConfig.tenantId;
    }
    this.organizationCourseUnitPriceSettings = JSON.parse(
      localStorage.getItem("organizationCourseUnitPriceSettings")
    );
    this.baseInfo = JSON.parse(localStorage.getItem("payMusicBase"));
    // 判断乐团状态 缴费类型
    window.addEventListener("scroll", this.getScroll);
    this.init();
  },
  beforeDestroy() {
    window.removeEventListener("scroll", this.getScroll);
  },
  methods: {
    async init() {
      this.organId = this.musicGroup?.organId;
      this.courseViewType = this.baseInfo?.musicGroup?.courseViewType;
      if (
        this.courseViewType != 2 &&
        this.$route.query.team_status == "DRAFT"
      ) {
        // 课程团的创建缴费
        this.teamCourse = true;
        // 现在课程团不在
        // this.teamCourseDisabled = true;
        this.form.paymentType = "MUSIC_APPLY";
      } else if (
        this.courseViewType == 2 &&
        this.$route.query.team_status == "DRAFT"
      ) {
        // 会员团的创建缴费
        this.member = true;
        this.memberDisabled = true;
        // 乐团创建缴费时，若乐团【收费模式】为【会员收费】，则缴费项目中【课程】【会员】两项都默认选中且必选，不可去掉
        this.teamCourse = true;
        this.teamCourseDisabled = true;
      } else if (this.$route.query.team_status == "PROGRESS") {
        this.leBao = false;
        this.leBaoDisabled = true;
      }

      if (this.$route.query.payUserType == "SCHOOL") {
        // this.member = false;
        // this.memberDisabled = true;
        this.leBao = false;
        this.leBaoDisabled = true;
        // this.teamActive = false;
        // this.teamActiveDisabled = true;
      } else {
      }
      await this.getCharges(); // 续费的选择缴费类型
      await this.formatCourse(); // 临时加课的类型选择以及价格
      await this.getMemberList(); // 获取会员(团练保信息)

      await this.getLeBao(); // 获取乐保
      await this.getActive(); // 获取活动
      await this.getMemberRules();
      await this.getAgreement(); // 获取是否有正在启用得协议
      if (this.$route.query.calenderId) {
        // 说明是修改  查缴项目详情
        this.initDetail = true;
        await 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;
              this.isSetCourseSettingsId = true;
            } else {
              this.form.leixing = "2";
            }

            if (
              res.data?.calender?.startPaymentDate &&
              res.data?.calender?.deadlinePaymentDate
            ) {
              this.$set(this.form, "paymentDate", [
                res.data?.calender?.startPaymentDate,
                res.data?.calender?.deadlinePaymentDate
              ]);
            }

            this.$set(
              this.form,
              "contractUrl",
              res.data?.calender?.contractUrl
            );
            this.$set(this.form, "memo", res.data?.calender?.memo);

            this.$set(
              this.form,
              "isShowMemberForPay",
              res.data?.calender?.paymentItemShowState?.isShowMemberForPay
            );
            this.$set(
              this.form,
              "isShowMusicInsuranceForPay",
              res.data?.calender?.paymentItemShowState
                ?.isShowMusicInsuranceForPay
            );
            this.$set(
              this.form,
              "isShowVipCourseForPay",
              res.data?.calender?.paymentItemShowState?.isShowVipCourseForPay
            );
            this.$set(
              this.form,
              "isShowSalePrice",
              res.data?.calender?.isShowSalePrice
            );
            this.$set(
              this.form,
              "isShowMusicCourseForPay",
              res.data?.calender?.paymentItemShowState?.isShowMusicCourseForPay
            );
            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.$set(
                this.form,
                "calenderFeeType",
                res.data?.calender?.calenderFeeType
              );
              this.$nextTick(() => {
                this.teamCourse = true;

                this.$set(this.form, "eclass", res.data?.course);
                console.log(
                  [...res.data?.course],
                  "res.data?.course",
                  this.form
                );
                this.initDetail = true;
                this.$set(
                  this.form,
                  "payUserType",
                  res.data?.calender?.payUserType
                );

                this.$set(
                  this.form,
                  "musicGroupCalenderRefundPeriods",
                  res.data?.calenderRefundPeriods
                );

                let calenderFeeJson = res.data?.calender?.calenderFeeJson;
                if (calenderFeeJson) {
                  calenderFeeJson = JSON.parse(calenderFeeJson);
                  this.$set(this.form, "calenderFeeJson", calenderFeeJson);
                  if (this.form.calenderFeeType == "TEACHER") {
                    this.$set(
                      this.form,
                      "teacherFeeList",
                      calenderFeeJson.teacherFeeList
                    );
                  }
                }
              });
            } else {
              this.$set(
                this.form,
                "calenderFeeType",
                res.data?.calender?.calenderFeeType
              );
              this.$set(
                this.form,
                "musicGroupCalenderRefundPeriods",
                res.data?.calenderRefundPeriods
              );
              let calenderFeeJson = res.data?.calender?.calenderFeeJson;
              if (calenderFeeJson) {
                calenderFeeJson = JSON.parse(calenderFeeJson);
                this.$set(this.form, "calenderFeeJson", calenderFeeJson);
              }
            }
            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);
      }
    },
    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 getAgreement() {
      try {
        const res = await getAgreement();
        if (!res.data) {
          this.submitList.push("agreement");
        }
      } catch (e) {}
    },
    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;
        // 获取是否展示会员是否自动生效
        const memberRes = await getAutoActivationFlag();
        this.showAutoActivationFlag = memberRes.data;
      } catch (e) {
        console.log(e);
      }
    },
    async getCharges() {
      const organId = this.musicGroup?.organId;
      const courseViewType = this.musicGroup?.courseViewType;
      try {
        const res = await musicGroupOrganizationCourseSettingsQueryPage({
          row: 9999,
          courseViewType,
          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");
        } else {
          if (this.form.leixing == 1 && this.teamCourse) {
            this.$set(
              this.form,
              "musicGroupOrganizationCourseSettingId",
              this.charges[0].id
            );
          }
        }
      } 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 == "teamDraft" ||
        query.type == "feeAudit" ||
        query.type == "FEE_AUDIT_FAILED"
      ) {
        this.$store.dispatch("delVisitedViews", this.$route);
        this.$router.push({
          path: "/business/resetTeaming",
          query
        });
      }
    },
    formatCourse() {
      // 格式化课程类型
      const organId = this.musicGroup?.organId;
      const courseViewType = this.musicGroup?.courseViewType;
      console.log(
        this.musicGroup.courseViewType,
        "musicGroup.courseViewType",
        this.organizationCourseUnitPriceSettings
      );
      const _ = {};
      const list = (this.organizationCourseUnitPriceSettings || []).filter(
        item =>
          organId &&
          organId == item.organId &&
          courseViewType != null &&
          courseViewType == item.courseViewType
      );
      console.log(list, "list");
      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();
    },
    priceChange2(item, index) {
      const _ = [...this.form.eclass];
      _[index] = item;
      this.$set(this.form, "eclass", [..._]);
    },
    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);
    },
    async onPreview() {
      // 开始预览
      const musicGroupId = this.$route.query.id;
      await findMusicGroupSubjectInfo({ musicGroupId: musicGroupId }).then(
        res => {
          if (res.code == 200) {
            this.dialogSubjectList = res.data.musicGroupSubjectPlans;
            // 默认预览第一个
            if (this.dialogSubjectList.length <= 0) {
              this.$message.error("请先设置声部信息");
              return;
            }
            this.activeName = this.dialogSubjectList[0].subjectId.toString();
            this.dialogSubjectVisible = true;
          } else {
            this.$message.warning("没有可预览的声部");
          }
        }
      );
    },
    checkType() {
      this.$refs.form.validate();
    },
    submitForm() {
      this.$refs.form.validate(async (isok, obj) => {
        if (isok) {
          // 学校缴费没有预览
          if (this.$route.query.payUserType == "SCHOOL") {
            this.$confirm(
              this.$route.query.calenderId ? "是否修改缴费" : "是否创建缴费?",
              "提示",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              }
            )
              .then(() => {
                this.onSubmit();
              })
              .catch(() => {});
          } else {
            const preViewData = this.formatPreviewData();
            this.preViewData = preViewData;
            await this.onPreview();
          }
        } else {
          this.$nextTick(() => {
            this.scrollView(obj);
          });
        }
      });
    },
    onSubmit() {
      this.$refs.form.validate(async isok => {
        if (isok) {
          let obj = this.fommatDate();
          if (obj.payUserType == "SCHOOL") {
            let total = 0;
            this.form.musicGroupCalenderRefundPeriods.forEach(item => {
              total += item.refundAmount * 1;
            });
            if (total != this.form.currentTotalAmount) {
              this.$message.error("付款金额与回款金额不一致,请重新设置");
              return;
            }
          }
          if (this.$route.query.calenderId) {
            obj.calenderId = this.$route.query.calenderId;
            try {
              const res = await musicGroupresetCalender(obj);
              if (res.code == 200) {
                this.$message.success("修改缴费成功");
                this.goback();
              }
              if (res.code == 207) {
                await this.$confirm(
                  res.msg || `当前乐团存在未排课的缴费项目，请再次确认操作`,
                  "提示",
                  {
                    type: "warning"
                  }
                );
                obj.confirmCreate = true;
                await musicGroupresetCalender(obj);
                this.$message.success("修改缴费成功");
                this.goback();
              }
            } catch (e) {
              console.log(e);
            }
          } else {
            try {
              const res = await musicGroupcreateCalender(obj);
              if (res.code == 200) {
                this.$message.success("创建缴费成功");
                this.goback();
              }
              if (res.code == 207) {
                await this.$confirm(
                  res.msg || `当前乐团存在未排课的缴费项目，请再次确认操作`,
                  "提示",
                  {
                    type: "warning"
                  }
                );
                obj.confirmCreate = true;
                await musicGroupcreateCalender(obj);
                this.$message.success("创建缴费成功");
                this.goback();
              }
            } catch (e) {
              console.log(e);
            }
          }
        }
      });
    },
    scrollView(object) {
      console.log(object);
      for (const i in object) {
        let dom = this.$refs[i];
        // 这里是针对遍历的情况（多个输入框），取值为数组
        if (Object.prototype.toString.call(dom) !== "[object Object]") {
          if (dom) {
            dom = dom[0];
          }
        }

        // 第一种方法（包含动画效果）
        dom.$el.scrollIntoView({
          // 滚动到指定节点
          // 值有start,center,end，nearest，当前显示在视图区域中间
          block: "center",
          // 值有auto、instant,smooth，缓动动画（当前是慢速的）
          behavior: "smooth"
        });
        break; // 跳出循环了
      }
    },

    formatPreviewData() {
      // 格式化预览数据
      const form = this.form;
      // 重置小班课数据
      let tmpActiveList = form.activeList?.length > 0 ? form.activeList : [];
      let activeList = [];
      if (tmpActiveList.length > 0) {
        tmpActiveList.forEach(active => {
          if (active.activityId) {
            active.categoryName = active.vipGroupCategoryNames;
            activeList.push(active);
          }
        });
      }
      let memberObj =
        form.memberList?.length > 0 ? { ...form.memberList[0] } : null;
      // 获取会员名称
      if (memberObj) {
        this.memberRankList.forEach(item => {
          if (item.id == memberObj.memberRankSettingId) {
            memberObj.name = item.name;
          }
        });
      }
      console.log(memberObj, "memberObj", activeList, form.eclass);
      let tempCourseList = form.eclass?.length > 0 ? form.eclass : [];
      let courseList = [];
      if (tempCourseList.length > 0) {
        tempCourseList.forEach(course => {
          if (course.courseType) {
            course.isStudentOptional = true;
            courseList.push(course);
          }
        });
      }
      return {
        payUserType: this.$route.query.payUserType,
        musicGroup: this.musicGroup,
        paymentCalender: {
          calender: {
            isShowSalePrice: form.isShowSalePrice
          },
          activity: [...activeList], // 小班课
          course: courseList, // 课程
          member: memberObj, // 云练习
          memberPrivilegesItemList: [], // 会员基本内容
          repair:
            form.leBaoList?.length > 0 &&
            this.isShowLeBao &&
            this.$route.query.team_status != "PROGRESS"
              ? { ...form.leBaoList[0], optionalFlag: false }
              : null // 乐保
        },
        isShowMemberForPay: form.isShowMemberForPay,
        isShowMusicInsuranceForPay: form.isShowMusicInsuranceForPay,
        isShowVipCourseForPay: form.isShowVipCourseForPay,
        isShowMusicCourseForPay: form.isShowMusicCourseForPay
      };
    },
    fommatDate() {
      if (this.$route.query.payUserType == "STUDENT") {
        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]?.memberRankSettingId
              ? { ...this.form.memberList[0] }
              : null,
          musicGroupPaymentCalenderCourseSettingsList:
            this.form.eclass?.length > 0 ? this.form.eclass : null,
          musicGroupId: this.$route.query.id,
          paymentItemShowState: JSON.stringify({
            isShowMemberForPay: this.form.isShowMemberForPay,
            isShowMusicInsuranceForPay: this.form.isShowMusicInsuranceForPay,
            isShowVipCourseForPay: this.form.isShowVipCourseForPay,
            isShowMusicCourseForPay: this.form.isShowMusicCourseForPay
          }),
          isShowSalePrice: this.form.isShowSalePrice
        };
      } else {
        let calenderFeeJson = this.form.calenderFeeJson;
        if (this.form.calenderFeeType == "TEACHER") {
          calenderFeeJson.teacherFeeList = this.form.teacherFeeList;
        }

        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]?.memberRankSettingId
              ? { ...this.form.memberList[0] }
              : null,
          musicGroupPaymentCalenderCourseSettingsList:
            this.form.eclass?.length > 0 ? this.form.eclass : null,
          musicGroupId: this.$route.query.id,
          paymentItemShowState: JSON.stringify({
            isShowMemberForPay: this.form.isShowMemberForPay,
            isShowMusicInsuranceForPay: this.form.isShowMusicInsuranceForPay,
            isShowVipCourseForPay: this.form.isShowVipCourseForPay,
            isShowMusicCourseForPay: this.form.isShowMusicCourseForPay
          }),
          calenderFeeType: this.form.calenderFeeType,
          calenderFeeJson: JSON.stringify(calenderFeeJson),
          musicGroupCalenderRefundPeriods: this.form
            .musicGroupCalenderRefundPeriods,
          currentTotalAmount: this.form.currentTotalAmount,
          contractUrl: this.form.contractUrl
        };
      }
    },
    getScroll() {
      this.scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      if (!!this.scrollTop && this.scrollTop >= 70) {
        this.isField = true;
      } else {
        this.isField = false;
      }
    },
    setAllTotal(val) {
      this.form.calenderFeeJson.allTotal = val;
      if (this.form.calenderFeeJson.discountTotal) {
        this.form.currentTotalAmount =
          this.form.calenderFeeJson.allTotal -
          this.form.calenderFeeJson.discountTotal;
      } else {
        this.form.currentTotalAmount = this.form.calenderFeeJson.allTotal;
      }

      this.$set(this.form, "currentTotalAmount", this.form.currentTotalAmount);
    },
    currentTotalAmount(val) {
      this.$set(this.form, "currentTotalAmount", val);
    }
  },
  watch: {
    teamCourse(val) {
      if (!val) {
        this.$set(this.form, "eclass", [{}]);
        this.$set(this.form, "leixing", "1");
        this.$set(this.form, "musicGroupOrganizationCourseSettingId", null);
      }
    },
    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", [{}]);
      }
    },
    Eclass: {
      handler(newValue, oldValue) {
        let oldString = JSON.stringify({ ...oldValue });
        let newString = JSON.stringify({ ...newValue });

        // console.log(oldString, newString, this.initDetail, "Eclass");
        if (this.initDetail || oldString == newString) {
          this.initDetail = false;
          return;
        } else {
          let arr = [];
          newValue.forEach(item => {
            arr.push({
              courseType: item.courseType,
              teacherNumber: 0,
              courseNumber: 0,
              courseCurrentPrice: 0
            });
          });
          console.log("type", newValue, oldValue);
          this.$set(this.form, "teacherFeeList", arr);
        }
      },
      deep: true
    },
    // "form.calenderFeeType"(val, oldValue) {
    //   if (val == "TEACHER" && !oldValue) {
    //     let arr = [];
    //     this.form.eclass.forEach((item) => {
    //       arr.push({
    //         courseType: item.courseType,
    //         teacherNumber: 0,
    //         courseNumber: 0,
    //         courseCurrentPrice: 0,
    //       });
    //     });

    //     this.$set(this.form, "teacherFeeList", arr);
    //   }
    // },

    "form.currentTotalAmount"(val) {
      // console.log(val,'form.currentTotalAmount');
      // this.$forceUpdate()
    },
    "form.calenderFeeType"(val, oldValue) {
      console.log(val, oldValue, this.initDetail);
      if (val == "TEACHER" && !this.initDetail) {
        let arr = [];
        this.form.eclass.forEach(item => {
          arr.push({
            courseType: item.courseType,
            teacherNumber: 0,
            courseNumber: 0,
            courseCurrentPrice: 0
          });
        });
        console.log("calenderFeeType", val, oldValue);
        this.$set(this.form, "teacherFeeList", arr);
      }
    },
    async "form.musicGroupOrganizationCourseSettingId"(val) {
      // && !this.rowDetail !this.$route.query.calenderId

      if (val && !this.isSetCourseSettingsId) {
        try {
          const res = await queryByMusicGroupOrganizationCourseSettingsId({
            id: val
          });
          let CourseSettingDetail = res.data.map(course => {
            return {
              ...course
            };
          });
          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;

      if (
        this.courseViewType == 2 &&
        this.$route.query.team_status == "PROGRESS"
      ) {
        this.memberDisabled = false;
        if (val === "1") {
          // 会员收费 创建续费 默认选中，不可取消选中
          this.member = false;
          if (this.teamCourse) {
            this.member = true;
            this.memberDisabled = true;
            if (this.member && this.form.memberList.length < 0) {
              this.form.memberList = [];
              this.form.memberList.push({});
            }
          }
        }
      }
    }
  },
  computed: {
    musicGroup() {
      return this.baseInfo?.musicGroup;
    },
    Eclass() {
      return JSON.parse(JSON.stringify(this.form.eclass));
    }
  }
};
</script>
<style lang="scss" scoped>
@import "~@/views/resetTeaming/modals/pay.scss";
.memoWrap {
  // width: calc(100% - 860px);
  width: 860px;
  .memoWrapItem {
    display: block;
    ::v-deep .el-form-item__content {
      display: inline-block;
      width: calc(100% - 140px);
    }
  }
}
.Wall {
  height: 15px;
  background-color: #f2f2f2;
}
::v-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;
  }
  .baseWrap {
    padding: 20px;
    background-color: #fff;
  }
  .baseWrapFixed {
    top: 105px;
    left: 215px; // 205
    position: fixed;
    background-color: #fff;
    width: calc(100% - 220px);
    z-index: 100;
    padding: 20px;
    box-shadow: rgba(0, 0, 0, 0.05) 0px 2px 3px 3px;
  }
  .left {
    ::v-deep .el-checkbox {
      padding: 8px 10px 7px 10px;
      border-radius: 4px;
    }
    ::v-deep .el-checkbox .el-checkbox__inner {
      border-radius: 50%;
      border: 1px solid var(--color-primary);
      width: 16px;
      height: 16px;
      &:after {
        height: 8px;
        left: 5px;
      }
    }
    ::v-deep .el-checkbox__inner:hover {
      background-color: var(--color-primary);
    }
    ::v-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: 3px;
        height: 16px;
        background: var(--color-primary);
        margin-right: 8px;
        position: relative;
        top: -1px;
        border-radius: 2px;
      }
      .payContext {
        color: var(--color-primary);
        border: 1px solid var(--color-primary);
        font-size: 14px;
        line-height: 22px;
        border-radius: 3px;
        padding: 0 5px;
        margin-left: 12px;
      }
    }
    .checkWrap {
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      align-items: center;
      .checkBtn.active {
        border: 1px solid var(--color-primary);
      }
      .checkBtn {
        position: relative;
        background-color: #fefefe;
        margin-right: 12px;
        padding: 0 22px;
        display: flex;
        flex-direction: row;
        align-items: center;
        border-radius: 6px;
        border: 1px solid #dfe8ec;
        cursor: pointer;
        height: 84px;
        width: 251px;
        overflow: hidden;
        &:hover {
          border: 1px solid var(--color-primary);
        }
        p {
          height: 41px;
          line-height: 41px;
        }
        .checkLeft {
          width: 60px;
          height: 60px;
          margin-right: 16px;
          img {
            width: 100%;
          }
        }
        .checkRight {
          p {
            height: 26px;
            font-size: 19px;
            font-weight: 600;
            color: #1a1a1a;
            line-height: 26px;
          }
          .checkSubTitle {
            font-size: 14px;
            font-weight: 400;
            color: var(--color-primary);
            line-height: 20px;
          }
        }
        .checTriangle {
          border-bottom: 44px solid var(--color-primary);
          border-left: 44px solid transparent;
          position: absolute;
          right: 0;
          bottom: 0;
          width: 0;
          height: 0;
          img {
            width: 19px;
            height: 16px;
            position: absolute;
            top: 22px;
            right: 5px;
          }
        }
      }
      // .checkBtn.disabled {
      //   cursor: not-allowed;
      //   color: #d9d9d9;
      //   background-color: #f2f2f2 !important;
      //   ::v-deep .el-checkbox__inner {
      //     background-color: #fff !important;
      //     border-color: #d9d9d9;
      //     color: #fff;
      //     &::after {
      //       border-color: #d9d9d9;
      //     }
      //   }
      //   &:hover {
      //     background-color: #f2f2f2 !important;
      //     color: #d9d9d9;
      //     ::v-deep .el-checkbox__inner {
      //       background-color: #fff !important;
      //     }
      //   }
      // }
    }
  }
}
.coreList {
  // margin: 14px;
}
</style>
<style lang="less" scoped>
::v-deep .el-dialog__body {
  padding: 15px 0 0;
}
.empty {
  background-color: #fff;
  padding-bottom: 20px;
}
</style>
