<template>
  <div style="background: #f3f4f8">
    <h2 class="title">注册说明</h2>
    <div class="noticeInfo">
      1、您注册时所选择的乐团声部，即为乐团录取最终确认的声部，请您务必仔细填写；<br />
      2、为避免因部分已注册家长放弃名额导致乐团声部失衡，系统设定各声部限额放大20%比例开放注册，系统自动按照完全完成注册的先后顺序确认录取名单，因此，超员后有可能出现无法注册的情况，请您理解。如果其他声部仍有名额，在您孩子的身体条件适合该乐器的前提下，我们将优先予以调配。
    </div>

    <template v-if="courseViewType == 2">
      <h2 class="title">学习工具包</h2>
      <div class="yunTrain">
        <img :src="trainBg" />
        <div class="toolText">
          <p class="toolTitle">
            乐器练习云教练
            <i class="icon_video" @click="videoStatus = true"></i>
          </p>
          <p class="toolDate">有效期说明：自开课之日起6个月内有效</p>
        </div>
      </div>
    </template>

    <template v-if="courseViewType == 1 && courseShowInfo.length > 0">
      <div class="yunTrain" style="margin-top: 12px">
        <img :src="trainBg" />
        <div class="toolText">
          <p class="toolTitle">服务</p>
          <p class="toolDate" v-if="serviceValidDate">
            服务有效期:{{ serviceValidDate }}
          </p>
        </div>
      </div>
    </template>

    <h2 class="titles" style="margin-top: 12px" v-if="courseViewType == 0">
      <img :src="trainSmallBg" />
      <span>乐团课程</span>
    </h2>
    <template class="section">
      <!-- 所有不可选的课程合集 -->
      <div class="section" v-if="courseShowStatus && courseViewType == 1">
        <el-row
          class="option-row"
          v-for="(item, index) in courseShowInfo"
          :class="[!item.isStudentOptional ? 'disabled' : '']"
          :key="index"
          @click.native="onCourseChange(item)"
        >
          <el-col :span="16">
            <i
              class="check_default"
              :class="[item.isStatus ? 'check_active' : '']"
            ></i>
            <span style="display: flex; align-items: center">
              <template v-if="item.courseType == 'PROJECT'"
                >{{ chargeTypeName }} </template
              ><template v-else>{{ item.courseType | coursesType }}</template>
            </span>
            <el-icon
              v-if="item.courseType == 'PROJECT'"
              class="el-icon-question"
              @click.native="onQuestions('amr')"
            />
          </el-col>
          <el-col :span="8">
            <span style="color: #1a1a1a"
              >￥{{ item.courseCurrentPrice | moneyFormat }}</span
            >
          </el-col>
        </el-row>
      </div>

      <div class="section" v-if="courseViewType == 2">
        <div v-for="(item, index) in toolsPackage" :key="index">
          <el-row
            class="option-row"
            style="padding-top: 0"
            @click.native="onTrainChange(item)"
          >
            <el-col :span="18">
              <i
                class="check_default"
                :class="[item.isStatus ? 'check_active' : '']"
              ></i>
              <span style="display: flex; align-items: center">
                <template>{{ item.name }}</template>
              </span>
            </el-col>
            <el-col :span="6">
              <span style="color: #1a1a1a" v-if="courseViewType == 2"
                >￥{{ cloudTeacherFee | moneyFormat }}</span
              >
            </el-col>
          </el-row>
          <el-row
            style="padding-left: 0.24rem"
            v-if="item.childGoodsList && courseViewType == 2"
          >
            <el-col
              v-for="(child, index) in item.childGoodsList"
              :key="child.name"
            >
              <span style="font-size: 12px; color: #808080"
                >{{ child.name }}
                {{ item.childGoodsList.length - 1 == index ? "" : "、" }}</span
              >
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 可选课程信息集合 -->
      <div class="section" v-if="courseViewType == 0">
        <el-row class="title-row" v-if="courseViewType == 0">
          <el-col :span="12">课程类型</el-col>
          <!-- <el-col :span="5" :offset="1" style="text-align: right;">原价</el-col> -->
          <el-col :span="11" :offset="1" style="text-align: right">现价</el-col>
        </el-row>
        <el-row
          class="option-row"
          v-for="(item, index) in courseInfo"
          :key="index"
          @click.native="onCourseChange(item)"
        >
          <el-col :span="12">
            <i
              class="check_default"
              :class="[
                item.isStatus ? 'check_active' : '',
                !item.isStudentOptional ? 'disabled' : '',
              ]"
            ></i
            ><template v-if="item.courseType == 'PROJECT'">{{
              item.name
            }}</template
            ><template v-else>{{ item.courseType | coursesType }}</template>
          </el-col>
          <!-- <el-col :span="6">
						<del style="color: #AAA; font-size: 12px;">￥{{ item.courseOriginalPrice | moneyFormat }}</del>
					</el-col> -->
          <el-col :span="11" :offset="1">
            <span style="color: #1a1a1a"
              >￥{{ item.courseCurrentPrice | moneyFormat }}</span
            >
          </el-col>
        </el-row>
      </div>
    </template>

    <div
      class="section"
      v-if="
        courseInfo &&
        courseInfo.length > 0 &&
        isClickStatus &&
        courseViewType == 1
      "
    >
      <h2 class="title">{{ "乐团课程" }}</h2>
      <el-row class="title-row">
        <el-col :span="12">课程类型</el-col>
        <!-- <el-col :span="5" :offset="1" style="text-align: right;">原价</el-col> -->
        <el-col :span="11" :offset="1" style="text-align: right">现价</el-col>
      </el-row>
      <!-- 可选课程信息集合 -->
      <template v-for="(item, index) in courseInfo">
        <el-row
          class="option-row"
          :key="index"
          @click.native="onCourseChange(item)"
          v-if="item.isStudentOptional"
        >
          <el-col :span="12">
            <i
              class="check_default"
              :class="[
                item.isStatus ? 'check_active' : '',
                !item.isStudentOptional ? 'disabled' : '',
              ]"
            ></i
            ><template v-if="item.courseType == 'PROJECT'">{{
              item.name
            }}</template
            ><template v-else>{{ item.courseType | coursesType }}</template>
          </el-col>
          <!-- <el-col :span="6">
						<del style="color: #AAA; font-size: .12rem;">￥{{ item.courseOriginalPrice | moneyFormat }}</del>
					</el-col> -->
          <el-col :span="11" :offset="1">
            <span style="color: #1a1a1a"
              >￥{{ item.courseCurrentPrice | moneyFormat }}</span
            >
          </el-col>
        </el-row>
      </template>
    </div>

    <h2
      class="titles"
      v-if="instrumentResultList && instrumentResultList.length > 0"
    >
      <img :src="trainSmallBg" />
      <span>乐器</span>
    </h2>
    <div
      class="section"
      v-if="instrumentResultList && instrumentResult.length > 0"
    >
      <div v-for="(i, index) in instrumentResultList" :key="index">
        <template v-if="leBaoStatus && i[0].kitType == 'owned'">
          <!-- <el-row class="title-row">
                        <el-col :span="12" :offset="1">服务项目</el-col>
                        <el-col :span="11" style="text-align: right;">现价</el-col>
                    </el-row> -->
          <el-row
            class="option-row"
            style="
              padding-bottom: 10px;
              margin-top: 8px;
              border-top: 1px solid #f0f0f0;
            "
            @click.native="onLeBao"
          >
            <el-col :span="12">
              <i
                class="check_default"
                :class="[buyMaintenance ? 'check_active' : '']"
              ></i
              >乐器保养（一年）<el-icon
                style="padding-left: 0"
                name="question"
                @click.stop.native="onQuestions('instrument')"
              />
            </el-col>
            <!-- <el-col :span="6">
                            <del style="color: #AAA; font-size: .12rem;">￥{{ 500 | moneyFormat }}</del>
                        </el-col> -->
            <el-col :span="11" :offset="1">
              <span style="color: #1a1a1a">￥{{ 300 | moneyFormat }}</span>
            </el-col>
          </el-row>
        </template>
        <el-row class="title-row">
          <el-col :span="12">
            <template v-if="i[0]['kitType'] == 'GROUP'">
              团购乐器{{ courseViewType == 2 ? "(赠送辅件一套)" : null }}
            </template>
            <template v-if="i[0]['kitType'] == 'LEASE'">
              乐器租赁{{ courseViewType == 2 ? "(请自行购买辅件)" : null }}
            </template>
            <template v-if="i[0]['kitType'] == 'FREE'">
              免费乐器{{ courseViewType == 2 ? "(请自行购买辅件)" : null }}
            </template>
            <template v-if="i[0]['kitType'] == 'owned'">
              自备乐器{{ courseViewType == 2 ? "(请自行购买辅件)" : null }}
            </template>
          </el-col>

          <el-col :span="5" :offset="1" style="text-align: right">
            <template
              v-if="['GROUP', 'LEASE', 'FREE'].includes(i[0]['kitType'])"
              >原价</template
            >
          </el-col>
          <el-col :span="5" :offset="1" style="text-align: right">
            <template v-if="['GROUP', 'FREE'].includes(i[0]['kitType'])"
              >现价</template
            >
            <template v-if="i[0]['kitType'] == 'LEASE'">租赁押金</template>
          </el-col>
        </el-row>

        <div v-for="(con, index) in i" :key="index" @click="instrumentF(con)">
          <el-row class="option-row" v-if="courseViewType == 2 && organId == 50 && !toolsPackage[0].isStatus">
            <el-col :span="12">
              <i
                class="check_default"
                :class="[con.checked ? 'check_active' : '']"
              ></i>
              <div>
                {{ con.name }}
                <div
                  v-if="con.goodsList"
                  style="font-size: 12px; color: #808080"
                >
                  {{ con.goodsList[0].specification }}
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <del
                style="color: #808080; font-size: 12px"
                v-if="con.kitType != 'owned'"
                >￥{{ con.marketPrice | moneyFormat }}</del
              >
            </el-col>
            <el-col :span="6">
              <span style="color: #1a1a1a" v-if="con.kitType == 'LEASE'"
                >￥{{
                  Number((con.depositFee - con.coupon).toFixed(2)) | moneyFormat
                }}</span
              >
              <span style="color: #1a1a1a" v-if="con.kitType == 'FREE'"
                >￥{{ 0 | moneyFormat }}</span
              >
              <span style="color: #1a1a1a" v-if="con.kitType == 'GROUP'"
                >￥{{
                  Number((con.marketPrice - con.coupon).toFixed(2)) | moneyFormat
                }}</span
              >
            </el-col>
          </el-row>
          <el-row class="option-row" v-else>
            <el-col :span="12">
              <i
                class="check_default"
                :class="[con.checked ? 'check_active' : '']"
              ></i>
              <div>
                {{ con.name }}
                <div
                  v-if="con.goodsList"
                  style="font-size: 12px; color: #808080"
                >
                  {{ con.goodsList[0].specification }}
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <del
                style="color: #808080; font-size: 12px"
                v-if="con.kitType != 'owned'"
                >￥{{ con.marketPrice | moneyFormat }}</del
              >
            </el-col>
            <el-col :span="6">
              <span style="color: #1a1a1a" v-if="con.kitType == 'LEASE'"
                >￥{{
                  Number((con.depositFee - con.coupon).toFixed(2)) | moneyFormat
                }}</span
              >
              <span style="color: #1a1a1a" v-if="con.kitType == 'FREE'"
                >￥{{ 0 | moneyFormat }}</span
              >
              <span style="color: #1a1a1a" v-if="con.kitType == 'GROUP'"
                >￥{{
                  Number((con.price - con.coupon).toFixed(2)) | moneyFormat
                }}</span
              >
            </el-col>
          </el-row>
          <el-row
            style="
              padding: 8px 0px 8px 24px;
              border-top: 1px solid rgb(240, 240, 240);
            "
            v-if="con.childGoodsList && con.kitType == 'GROUP'"
          >
            <el-col
              :span="24"
              style="font-size: 14px; color: #1a1a1a; padding-bottom: 3px"
              >赠送辅件</el-col
            >
            <el-col>
              <span style="font-size: 12px; color: #808080">
                {{ con.childGoodsNames }}
              </span>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>

    <h2 class="titles" v-if="accessOries.length > 0 && accessIsShowStatus">
      <img :src="trainSmallBg" />
      <span>辅件</span>
    </h2>
    <div
      class="section"
      v-if="accessOries.length > 0 && accessIsShowStatus"
      key="accessOries"
    >
      <el-row class="title-row">
        <el-col :span="12">服务项目</el-col>
        <el-col :span="5" :offset="1" style="text-align: right">原价</el-col>
        <el-col :span="5" :offset="1" style="text-align: right">现价</el-col>
      </el-row>

      <div v-for="(instr, index) in accessOries" :key="index">
        <el-row class="option-row" @click.native="onAuxiliarie(instr)">
          <el-col :span="12">
            <i
              class="check_default"
              :class="[instr.checked ? 'check_active' : '']"
            ></i
            >{{ instr.name }}
          </el-col>
          <el-col :span="6">
            <del style="color: #808080; font-size: 12px"
              >￥{{
                instr.goodsList[0]
                  ? instr.goodsList[0].marketPrice
                  : 0 | moneyFormat
              }}</del
            >
          </el-col>
          <el-col :span="6">
            <span style="color: #1a1a1a" v-if="instr.price == 0">免费</span>
            <span style="color: #1a1a1a" v-else
              >￥{{ instr.price | moneyFormat }}</span
            >
          </el-col>
        </el-row>
        <el-row style="padding-left: 24px" v-if="instr.childGoodsList">
          <el-col>
            <span
              v-for="(child, index) in instr.childGoodsList"
              :key="child.id"
              style="font-size: 12px; color: #808080"
              >{{ child.name }}
              {{ instr.childGoodsList.length - 1 == index ? "" : "，" }}</span
            >
          </el-col>
        </el-row>
      </div>
    </div>

    <div class="buy">
      <div class="price">
        <p class="oldprice">
          <del class="text">原价</del>
          <del style="font-size: 13px"
            >￥{{ orderInfo.marketPrice | moneyFormat }}</del
          >
        </p>
        <p class="now_price">
          <span class="text">仅需支付</span>
          <span style="font-weight: bold">￥{{ needPrice | moneyFormat }}</span>
        </p>
      </div>

      <a class="btn-submit">购买</a>
    </div>

    <el-dialog
      title="视屏"
      :visible.sync="videoStatus"
      :modal-append-to-body="false"
      :append-to-body="true"
      class="videoDialog"
      width="30%"
    >
      <video
        style="width: 100%"
        v-if="videoStatus"
        controls="controls"
        class="ql-video"
        :src="'https://daya.ks3-cn-beijing.ksyun.com/202105/SWmqmvW.mp4'"
        :poster="require('../../../assets/images/musicGroup/video_bg.png')"
      />
    </el-dialog>
  </div>
</template>
<script>
import { permission } from "@/utils/directivePage";
import { getSubjectGoodsAndInfoPreview, getType } from "@/api/buildTeam";
import dayjs from "dayjs";
const paymentPatternType = {
  0: "按月",
  1: "按学期",
  2: "一次性",
};
export default {
  props: ["subjectId", "calenderId"],
  data() {
    const query = this.$route.query;
    return {
      videoStatus: false,
      trainBg: require("../../../assets/images/musicGroup/yunTrain_bg.png"),
      trainSmallBg: require("../../../assets/images/musicGroup/yunTrain_small_bg.png"),
      musicGroupId: query.id,
      organId: null,
      result: {}, // 返回结果
      instrument: {}, // 乐器类型
      baseInfo: {}, // 其它类
      money: 580,
      balance: 0, // 余额
      needPrice: 0, // 还需支付
      payType: false, // 是否余额支付
      cloudTeacherFee: 0, // 云教练费用
      cloudTeacherPlusFee: 0, // 云教练+
      orderInfo: {
        marketPrice: 0,
        amount: 0, // 现价总金额
        groupPurchasePrice: 0, // 现价
        goodsGroupIds: null,
        goodsIds: null,
        contractGoodsIds: null, // 选中所有商品ID
        couponPrice: 0, //
        musicClassFee: 0, // 课程现价
        musicMarketClassFee: 0, // 课程原价
        accessPrice: 0, // 辅件现价
        accessMarketPrice: 0, // 辅件原价
        goodsPrice: 0, // 乐器现价
        goodsMarketPrice: 0, // 乐器原价
      }, // 金额列表，金额计算
      toolsPackage: [
        {
          isStatus: true,
          name: "练习系统（六个月）",
          childGoodsList: [{ name: "" }],
        },
      ], // 学习工具包
      courseInfo: [], // 课程信息
      courseShowInfo: [], // 课程信息显示用
      musicGroupSubject: null, // 基本信息
      instrumentResult: [], //乐器
      accessOries: [], // 辅件(打包)
      agreeStatus: true,
      authStatus: false,
      buyList: [], // 信息列表
      ids: [],
      instrumentResultList: [],
      chargeTypeId: null,
      paymentStatus: null,
      paymentPattern: null,
      serviceValidDate: null, // 服务时间
      courseShowStatus: false,
      chargeTypeList: [],
      chargeTypeName: null,
      courseViewType: 0, // 收费模式，0 课程显示，1 AMR系统 2会员
      leBaoStatus: false,
      buyMaintenance: false, // 是否开启乐保
      isClickStatus: false,
      accessStatus: false, // 是否有辅件乐保
      accessIsShowStatus: false, // 是否显示辅件 true 显示， false 不显示
    };
  },
  mounted() {
    this.__init();
  },
  methods: {
    async __init() {
      // 获取数据
      let params = {
        musicGroupId: this.musicGroupId,
        subjectId: this.subjectId,
        calenderId: this.calenderId,
      };
      await getType().then((res) => {
        let result = res.data;
        if (res.code == 200) {
          this.chargeTypeList = result.rows || [];
        }
      });

      await getSubjectGoodsAndInfoPreview(params).then((res) => {
        let result = res;
        if (result.code == 200) {
          let tempResult = result.data;
          this.courseViewType = tempResult.musicGroup.courseViewType || 0;
          this.organId = tempResult.musicGroup.organId;
          this.cloudTeacherFee = tempResult.cloudTeacherFee || 0;
          this.cloudTeacherPlusFee = tempResult.cloudTeacherPlusFee || 0;
          this.paymentPattern = 2;
          if (tempResult.musicGroupPaymentCalender) {
            this.paymentPattern =
              tempResult.musicGroupPaymentCalender.paymentPattern;
            this.serviceValidDate =
              dayjs(
                tempResult.musicGroupPaymentCalender.paymentValidStartDate
              ).format("YYYY/MM/DD") +
              "~" +
              dayjs(
                tempResult.musicGroupPaymentCalender.paymentValidEndDate
              ).format("YYYY/MM/DD");
          }
          let tempInfo = tempResult.musicGroupPaymentCalender
            ? tempResult.musicGroupPaymentCalender
                .musicGroupPaymentCalenderCourseSettingsList
            : null;

          let memberPrivilegesItemList = tempResult.memberPrivilegesItemList
            ? tempResult.memberPrivilegesItemList
            : [];
          let tempMember = [];
          memberPrivilegesItemList.forEach((member) => {
            if (
              member.memberPrivilegesItems &&
              member.memberPrivilegesItems.length > 0
            ) {
              member.memberPrivilegesItems.forEach((item) => {
                tempMember.push(item.name);
              });
            }
          });
          this.toolsPackage = [
            {
              isStatus: true,
              name: "练习系统（六个月）",
              childGoodsList: [{ name: tempMember.join("、") }],
            },
          ];
          // 判断是否有课程
          if (tempInfo && tempInfo.length > 0) {
            let tempCourse = {
              courseCurrentPrice: 0,
              courseOriginalPrice: 0,
              courseType: null,
              name: "器乐练习系统",
            };
            tempInfo.forEach((info) => {
              if (!info.isStudentOptional) {
                this.courseShowStatus = true;
                tempCourse = {
                  courseCurrentPrice:
                    info.courseCurrentPrice + tempCourse.courseCurrentPrice,
                  courseOriginalPrice:
                    info.courseCurrentPrice + tempCourse.courseCurrentPrice,
                  courseType: "PROJECT",
                  isStatus: true,
                  name: "器乐练习系统",
                };
              }
            });
            this.courseShowInfo = [tempCourse];
            // 默认课程都选中
            this.courseInfo = tempInfo;
          } else {
            // 判断是否有课程，如果没有课程则默认显示0
            this.courseInfo = [
              {
                id: -1,
                courseCurrentPrice: 0,
                courseOriginalPrice: 0,
                isStudentOptional: false,
                courseType: "MUSIC",
              },
            ];
          }
          this.isClickStatus = false;
          this.courseInfo.forEach((item) => {
            if (item.isStudentOptional) {
              item.isStatus = false;

              this.isClickStatus = true;
            } else {
              item.isStatus = true;
            }
          });

          // console.log(this.isClickStatus)

          this.musicGroupSubject = tempResult.musicGroupSubjectPlan;
          let instrumentInfo = {};
          let tempInstrument = [];
          tempResult.musicGroupSubjectGoodsGroupList.forEach((item) => {
            if (item.type == "INSTRUMENT") {
              // 获取乐器所有提供方式
              let KGPTJ = item.kitGroupPurchaseTypeJson
                ? JSON.parse(item.kitGroupPurchaseTypeJson)
                : {};
              for (let single in KGPTJ) {
                let tempItem = Object.assign({}, item); // 深拷贝
                tempItem.marketPrice = tempItem.goodsList[0].marketPrice;
                tempItem.kitType = single; // 优惠模式
                tempItem.coupon = KGPTJ[single]; // 优惠金额
                if (instrumentInfo.id) {
                  tempItem.checked = false;
                  if (single == "GROUP") {
                    // 团购
                    if (
                      (instrumentInfo.kitType == "GROUP" &&
                        instrumentInfo.price < tempItem.price) ||
                      instrumentInfo.kitType == "LEASE" ||
                      instrumentInfo.kitType == "FREE"
                    ) {
                      this.instrumentResult.forEach((instrRes) => {
                        instrRes.checked = false;
                      });
                      tempItem.checked = true;
                      instrumentInfo = {
                        id: tempItem.id,
                        price: tempItem.price,
                        kitType: single,
                      };
                    }
                  } else if (single == "LEASE") {
                    // 租赁
                    if (
                      instrumentInfo.kitType == "LEASE" &&
                      instrumentInfo.price < tempItem.price
                    ) {
                      this.instrumentResult.forEach((instrRes) => {
                        instrRes.checked = false;
                      });
                      tempItem.checked = true;
                      instrumentInfo = {
                        id: tempItem.id,
                        price: tempItem.price,
                        kitType: single,
                      };
                    }
                  } else if (single == "FREE") {
                    // 免费
                    if (
                      instrumentInfo.kitType == "FREE" &&
                      instrumentInfo.price < tempItem.price
                    ) {
                      this.instrumentResult.forEach((instrRes) => {
                        instrRes.checked = false;
                      });
                      tempItem.checked = true;
                      instrumentInfo = {
                        id: tempItem.id,
                        price: tempItem.price,
                        kitType: single,
                      };
                    }
                  }
                } else {
                  tempItem.checked = true;
                  instrumentInfo = {
                    id: tempItem.id,
                    price: tempItem.price,
                    kitType: single,
                  };
                }
                let childGoodsNameList = [];
                if (
                  tempItem.childGoodsList &&
                  tempItem.childGoodsList.length > 0
                ) {
                  tempItem.childGoodsList.forEach((child) => {
                    if (child.type != "INSTRUMENT" && child.type != "OTHER") {
                      childGoodsNameList.push(child.name);
                    }
                  });

                  tempItem.childGoodsNames = childGoodsNameList.join("、");
                }
                this.instrumentResult.push(tempItem);
                tempInstrument.push(tempItem);
              }
            } else if (item.type == "ACCESSORIES") {
              item.checked = true;
              this.accessOries.push(item);
            }
          });
          // 添加自备选项
          if (this.instrumentResult.length > 0) {
            // this.instrumentResult.push({
            //     id: -1,
            //     kitType: 'owned',
            //     name: '自备',
            //     price: 0,
            //     marketPrice: 0,
            //     checked: false
            // })
            let owned = {
              id: -1,
              kitType: "owned",
              name: "自备乐器",
              price: 0,
              marketPrice: 0,
              checked: false,
            };
            tempInstrument.push(owned);
            this.instrumentResult.push(owned);
            let sorted = this.groupBy(tempInstrument, (item) => {
              return [item.kitType];
            });
            console.log(sorted);
            this.instrumentResultList = sorted;
            this.chargeTypeList.forEach((item) => {
              if (item.id == tempResult.musicGroup.chargeTypeId) {
                this.chargeTypeName = item.description;
              }
            });

            // 判断辅件是否有乐器维护（编号固定76）
            let accessStatus = false; // 是否有乐保
            this.accessOries.forEach((item) => {
              // 判断子商品是否有乐保
              if (item.childGoodsList && item.childGoodsList.length > 0) {
                item.childGoodsList.forEach((child) => {
                  if (child.id == 76) {
                    accessStatus = true;
                  }
                });
              }
              if (item.goodsIdList == 76) {
                accessStatus = true;
              }
            });
            this.accessStatus = accessStatus;

            // 所有打击乐声部没有乐保【23】
            if (this.subjectId == 23) {
              this.accessStatus = true;
              accessStatus = true;
            }

            // 乐保服务初始化
            this.instrumentResult.forEach((item) => {
              if (item.checked && item.kitType != "owned" && !accessStatus) {
                this.leBaoStatus = true;
                this.buyMaintenance = true;
              }

              if (
                item.checked &&
                item.kitType != "GROUP" &&
                this.courseViewType == 2
              ) {
                this.accessIsShowStatus = true;
              }
              if (this.courseViewType != 2) {
                this.accessIsShowStatus = true;
              }
            });
          }
        }
        // 初始化计算金额
        this.calcPrice();
      });
    },
    onLeBao() {
      this.buyMaintenance = !this.buyMaintenance;
      this.calcPrice();
    },
    groupBy(array, f) {
      var groups = {};
      array.forEach(function (o) {
        var group = JSON.stringify(f(o));
        groups[group] = groups[group] || [];
        groups[group].push(o);
      });
      return Object.keys(groups).map(function (group) {
        return groups[group];
      });
    },
    onQuestions(type) {
      if (type == "amr") {
        this.$alert(
          `<b>革命性的“AMR器乐练习系统”</b><br />它的诞生是基于世界上最优秀的华人管乐指导专家唐嘉宏先生的教育理念，创新开发的一种新型“音乐感官植入程序”，这个程序抛弃了传统的“数线式识谱、机械式节奏、死记式乐理”，它营造出沉浸式可变速演奏过程，采用画面与音乐刺激序列组合而成的特定场景，在趣味性挑战的反复刺激中逐步促进器乐演奏的三核心：“音质→音准→音型”，从而达成演奏各环节水准的均匀提高，产生永久性条件反射式大脑记忆，将多板块知识融会贯通，让抽象的音乐知识刻入脑海里！<br /><br /><b>本练习系统的特点：</b><br /> 1.轻松快速掌握要点，让练习者沉浸其中，远离枯燥！<br /> 2.不假思索就能瞬间唤起反射式记忆，演奏识谱不再慢吞吞！<br /> 3.真正的实践记忆，摆脱纸上谈兵，与实际演奏紧密结合！<br />4.思维+肌肉的双重强化！无缝整合复习系统！<br /> 5.每条练习都经过严谨的编曲，你以为你只是在练习旋律线？其实是整个乐团在为你伴奏！`,
          "AMR器乐练习系统",
          {
            confirmButtonText: "确定",
            dangerouslyUseHTMLString: true,
            callback: (action) => {},
          }
        );
      } else if (type == "instrument") {
        this.$alert(
          `<p style="text-align: justify">1.乐器保养是管乐迷针对乐团学员提供的乐器检查、保养及维修优惠特权；<br />2.该特权为包年制，从开通特权之日起365天内有效；<br />3.特权用户可享受管乐迷提供专业的高级乐器维修技师一年不低于两次下校检查乐器使用情况；<br />4.特权有效期内凭该特权绑定的乐器编号可享受保养人工费减免、非返厂维修人工费优惠等特权;<br />感谢您的信任和支持！</p>`,
          "乐器保养特权",
          {
            confirmButtonText: "确定",
            dangerouslyUseHTMLString: true,
            callback: (action) => {},
          }
        );
      }
    },
    onCourseChange(item) {
      // 判断用户是否可以选择
      if (item.isStudentOptional) {
        item.isStatus = !item.isStatus;
        this.calcPrice();
      }
    },
    onTrainChange(item) {
      // 练习系统可选
      console.log(item);
      item.isStatus = !item.isStatus;
      let courseShowInfo = this.courseShowInfo;
      courseShowInfo.forEach((course) => {
        course.isStatus = item.isStatus;
      });
      let cif = this.courseInfo;
      cif.forEach((c) => {
        if (!c.isStudentOptional) {
          c.isStatus = item.isStatus;
        }
      });
      this.calcPrice();
    },
    onClickCheckbox() {
      //是否使用余额支付
      if (!this.payType) {
        if (this.orderInfo.amount >= this.balance) {
          this.needPrice = Number(
            (this.orderInfo.amount - this.balance).toFixed(2)
          );
        } else {
          this.needPrice = 0;
        }
      } else {
        this.needPrice = this.orderInfo.amount;
      }
      this.payType = !this.payType;
    },
    onAuxiliarie(item) {
      // 辅件切换状态
      item.checked = !item.checked;
      // 重新计算金额
      this.calcPrice();
    },
    instrumentF(item) {
      // 乐器切换状态
      this.instrumentResult.forEach((item) => {
        item.checked = false;
      });
      item.checked = true;
      if (!this.accessStatus) {
        if (item.kitType != "owned") {
          this.leBaoStatus = true;
          this.buyMaintenance = true;
        } else {
          this.leBaoStatus = false;
          this.buyMaintenance = false;
        }
      }
      // 云教练且选择自备则不显示辅件
      if (this.courseViewType == 2) {
        if (item.kitType != "GROUP") {
          this.accessIsShowStatus = true;
        } else {
          this.accessIsShowStatus = false;
        }
      }

      // 重新计算金额
      this.calcPrice();
    },
    calcPrice() {
      let buyList = [],
        ids = [];
      let amount = 0,
        marketPrice = 0,
        goodsPrice = 0, // 乐器两现价
        goodsMarketPrice = 0, // 乐器原价
        goodsGroupIds = {},
        courseKeys = [],
        couponPrice = 0, // 优惠金额
        goodsIds = [],
        tempCourseFee = 0,
        musicClassFee = 0,
        musicMarketClassFee = 0,
        tempAccessPrice = 0,
        tempAccessMarketPrice = 0,
        tempGroupRemissionCourseFee = 0, // 乐团减免费用
        contractGoodsIds = ""; // 合同所需要的商品Id （只需要乐器编号）
      // 课程
      let mgs = this.musicGroupSubject;
      let csi = this.courseInfo;
      // 加上判断是否有课程信息
      // 如果为云教练系统则，没有课程费用
      if (this.courseViewType == 2 && this.toolsPackage[0].isStatus) {
        let tempFee = this.cloudTeacherFee;
        musicClassFee += parseFloat(tempFee);
        marketPrice += parseFloat(tempFee);
      }
      if (mgs) {
        let tempCourse = this.courseShowInfo;
        if (tempCourse.length > 0 && this.courseViewType == 1) {
          let m = 0;
          tempCourse.forEach((item) => {
            m += parseFloat(item.courseCurrentPrice);
            // 不可选的课程才会减免课程费用
            // if (!item.isStudentOptional) {
            //     tempGroupRemissionCourseFee += parseFloat(item.courseCurrentPrice)
            // }
          });
          marketPrice += parseFloat(m);
          buyList.unshift({
            name: this.chargeTypeName,
            type: paymentPatternType[this.paymentPattern],
            price: Number(m.toFixed(2)),
          });
        }
        csi.forEach((item) => {
          if (item.isStatus) {
            if (this.courseViewType != 2) {
              musicClassFee += parseFloat(item.courseCurrentPrice);
            }
            // marketPrice += parseFloat(item.courseOriginalPrice)
            if (item.id > 0) {
              courseKeys.push(item.id);
            }
            // 不可选的课程才会减免课程费用
            if (!item.isStudentOptional) {
              tempGroupRemissionCourseFee += parseFloat(
                item.courseCurrentPrice
              );
            } else {
              marketPrice += parseFloat(item.courseCurrentPrice);
            }

            if (this.courseViewType == 0 && !item.isStudentOptional) {
              marketPrice += parseFloat(item.courseCurrentPrice);
            }
          }
        });
        // }
      }

      // 乐器
      let ir = this.instrumentResult;
      if (ir.length > 0) {
        ir.forEach((item) => {
          if (item.checked) {
            if (item.name != "自备乐器") {
              contractGoodsIds += item.goodsIdList;
            }
            if (item.kitType == "FREE") {
              amount += 0;
              couponPrice = 0; // 优惠金额
            } else if (item.kitType == "LEASE") {
              couponPrice = item.coupon; // 优惠金额
              if (item.name != "自备乐器") {
                amount += item.depositFee;
                goodsPrice += item.depositFee;
              } else {
                amount += 0;
              }
            } else {
              // 团购
              if (
                this.courseViewType == 2 &&
                this.organId == 50 &&
                !this.toolsPackage[0].isStatus
              ) {
                amount += parseFloat(item.marketPrice);
                goodsPrice += parseFloat(item.marketPrice);
                couponPrice = item.coupon ? item.coupon : 0;
              } else {
                amount += parseFloat(item.price);
                goodsPrice += parseFloat(item.price);
                couponPrice = item.coupon ? item.coupon : 0;
              }
            }

            if (item.kitType == "LEASE") {
              if (item.name != "自备乐器") {
                marketPrice += parseFloat(item.marketPrice);
                goodsMarketPrice += item.depositFee;
              }
            } else {
              marketPrice += parseFloat(item.marketPrice);
              goodsMarketPrice += parseFloat(item.marketPrice);
            }
            // item.id ? goodsGroupIds[item.id] : null
            if (item.id) {
              goodsGroupIds[item.id] = item.kitType;
            }
            if (item.kitType == "LEASE") {
              buyList.push({
                name: item.name,
                type: "租赁",
                price: item.depositFee,
              });
            } else if (item.kitType == "GROUP") {
              // 50分部的团购费用根据是否选中
              //  && parseFloat(item.price - couponPrice) > 0
              if (
                this.courseViewType == 2 &&
                this.organId == 50 &&
                !this.toolsPackage[0].isStatus
              ) {
                buyList.push({
                  name: item.name,
                  type: "团购",
                  price: parseFloat(item.marketPrice - couponPrice),
                });
              } else {
                buyList.push({
                  name: item.name,
                  type: "团购",
                  price: parseFloat(item.price - couponPrice),
                });
              }
            } else if (item.kitType == "FREE") {
              buyList.push({
                name: item.name,
                type: "免费",
                price: 0,
              });
            }

            // 是否减免课程费用，必须团购，并且开启了减免课程费用
            if (item.kitType == "GROUP" && item.groupRemissionCourseFee == 1) {
              musicClassFee = parseFloat(
                musicClassFee - tempGroupRemissionCourseFee
              );
            }
          }
        });
      }

      if (this.leBaoStatus && this.buyMaintenance) {
        // 判断是否使用乐保
        // marketPrice += 500
        marketPrice += 300;
        amount += 300;
        buyList.push({
          name: "乐器保养",
          // time: dayjs().format('YYYY/MM/DD') + '~' + dayjs().add(365, 'day').format('YYYY/MM/DD'),
          time: "有效期：从发货之日起一年内有效",
          type: "包年",
          price: 300,
        });
      }

      amount += parseFloat(tempCourseFee + musicClassFee);
      if (
        parseFloat(tempCourseFee + musicClassFee) > 0 &&
        this.courseViewType == 0
      ) {
        buyList.unshift({
          name: "乐团课",
          type: paymentPatternType[this.paymentPattern],
          price: Number((tempCourseFee + musicClassFee).toFixed(2)),
        });
      }
      // 辅件
      if (this.accessOries.length > 0) {
        this.accessOries.forEach((item) => {
          if (item.checked && this.accessIsShowStatus) {
            tempAccessPrice += parseFloat(item.price);
            amount += parseFloat(item.price);
            if (item.goodsList && item.goodsList.length > 0) {
              item.goodsList.forEach((childGoods) => {
                tempAccessMarketPrice += parseFloat(childGoods.marketPrice);
                marketPrice += parseFloat(childGoods.marketPrice);
              });
            }
            goodsGroupIds[item.id] = "ACCESSORIES";

            buyList.push({
              name: item.name,
              type: "团购",
              price: item.price,
            });
          }
        });
        // if (tempAccessPrice > 0) {
        // buyList.push({
        //     name: '辅件',
        //     type: '团购',
        //     price: tempAccessPrice
        // })
        // }
      }
      let tempGroupPurchasePrice = amount;
      // 判断减去优惠金额，是否大于0(这里有可能出现负数)
      if (amount - couponPrice >= 0) {
        amount = Number((amount - couponPrice).toFixed(2));
        this.errorPrice = false;
      } else {
        amount = 0;
        this.errorPrice = true; // 订单金额是否异常
      }

      // if (amount - tempCourseFee - musicClassFee > 0) {
      //     ids.push(1, 2)
      // }
      // if (parseFloat(tempCourseFee + musicClassFee) > 0) {
      //     ids.push(3, 4, 5)
      // }
      this.ids = ids;
      // 计算是否使用过余额
      if (this.payType) {
        let tempPrice = Number((amount - this.balance).toFixed(2));
        if (tempPrice > 0) {
          this.needPrice = tempPrice;
        } else {
          this.needPrice = 0;
        }
      } else {
        this.needPrice = Number(amount.toFixed(2));
      }
      this.buyList = buyList;

      this.orderInfo = {
        amount: Number(amount.toFixed(2)),
        marketPrice: Number(marketPrice.toFixed(2)),
        groupPurchasePrice: tempGroupPurchasePrice,
        couponPrice: couponPrice,
        goodsGroupIds: goodsGroupIds,
        goodsIds: goodsIds.join(","),
        contractGoodsIds: contractGoodsIds,
        courseKeys: courseKeys,
        musicClassFee: musicClassFee,
        musicMarketClassFee: musicMarketClassFee,
        accessMarketPrice: tempAccessMarketPrice,
        accessPrice: tempAccessPrice,
        goodsPrice: goodsPrice,
        goodsMarketPrice: goodsMarketPrice,
      };
    },
    permission(str) {
      return permission(str);
    },
  },
};
</script>
<style lang="less" scoped>
.noticeInfo {
  margin: 0 12px;
  position: relative;
  background: #fff;
  padding: 10px 12px;
  font-size: 14px;
  color: #808080;
  border-radius: 10px;
  line-height: 1.5;
}

.yunTrain {
  position: relative;
  font-size: 0;
  margin: 0 12px;
  img {
    width: 100%;
  }
  .toolText {
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 0 10px;
  }
  .toolTitle {
    font-size: 16px;
    color: #c1735d;
    display: flex;
    align-items: center;
    padding-top: 2px;
    padding-bottom: 2px;
    .icon_video {
      margin-left: 5px;
      display: inline-block;
      width: 16px;
      height: 16px;
      background: url("../../../assets/images/musicGroup/video_btn.png");
      background-size: contain;
    }
  }
  .toolDate {
    font-size: 12px;
    color: #808080;
  }
}

.title {
  font-size: 18px;
  line-height: 28px;
  font-weight: bold;
  padding-bottom: 5px;
  padding: 12px;
  display: flex;
  align-items: center;
  margin-bottom: 0;
  &::before {
    content: " ";
    width: 4px;
    height: 15px;
    background: #01c1b5;
    display: inline-block;
    margin-right: 7px;
    border-radius: 8px;
  }
}

.titles {
  position: relative;
  font-size: 0;
  margin: 0 12px;
  img {
    width: 100%;
  }
  & > span {
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 0 10px;
    font-size: 16px;
    color: #c1735d;
    font-weight: 500;
  }
}
.section {
  margin: 0 12px;
  padding: 12px 12px 10px;
  background: #fff;
  margin-bottom: 12px;
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;
}

.disabled {
  opacity: 0.5;
  .check_active {
    opacity: 0.5;
  }
}

.buy {
  height: 60px;
  display: flex;
  align-items: center;
  padding: 0 20px;
  border-top: 1px solid #ffe9e9e9;
  color: #000000;
  font-size: 12px;
  background: #fff;

  .price {
    flex: 1;
    font-size: 16px;
  }

  font-size: 16px;

  span {
    color: #fa101d;
  }

  .text {
    font-size: 12px;
    width: 60px;
    display: inline-block;
    color: #000;
  }

  del {
    color: #b5b5b5;

    &.text {
      color: #b5b5b5;
    }
  }

  .btn-submit {
    display: inline-block;
    font-size: 18px;
    color: #fff;
    background: #01c1b5;
    border-radius: 100px;
    padding: 8px 36px;
  }
}

.iframe {
  width: 100%;
  height: 100%;
  -webkit-overflow-scrolling: touch;
  overflow-y: scroll;
  border-top: none !important;
  min-height: calc(100vh - 41px);
}

.countDownContent {
  line-height: 40px;
  text-align: center;
  font-size: 14px;
  border-bottom: 1px solid #ccc;

  .van-count-down {
    display: inline;
    color: #f00;
  }
}

.loadingOrder {
  width: 90%;
  height: 180px;
  display: flex;
  align-items: center;
  justify-content: center;

  .van-loading__text {
    color: #444;
  }
}

.pay-section {
  margin-bottom: 10px;
  padding: 10px 8px;
}

.pay-name {
  padding-left: 10px;
  flex: 1 auto;
  font-weight: bold;
}

.logo {
  width: 24px;
  height: 24px;
}

.van-checkbox {
  float: right;

  /deep/.van-checkbox__icon .van-icon {
    border-color: #e9eaef;
    background-color: #e9eaef;
  }

  /deep/.van-checkbox__icon--checked .van-icon {
    background-color: #2dc7aa;
    border-color: #2dc7aa;
  }
}

.needprice {
  display: flex;
  justify-content: space-between;
  padding: 2px 0;

  del {
    font-size: 14px;
    color: #808080;
    font-weight: bold;
  }

  span {
    font-size: 18px;
    color: #f85043;
    font-weight: bold;
  }
}

.couponprice {
  display: flex;
  justify-content: space-between;
}

.use_price {
  display: flex;
  align-items: center;
  font-size: 14px;
  font-weight: bold;

  img {
    padding-right: 8px;
  }

  span {
    font-size: 16px;
  }
}

.check_default {
  margin-right: 8px;
  display: flex;
  align-items: center;
  height: 26px;
  &::before {
    display: block;
    content: " ";
    width: 18px;
    height: 18px;
    background-color: #fff;
    border: 1px solid #e9eaef;
    border-radius: 50%;
  }
  &.check_active {
    &::before {
      display: block;
      content: " ";
      background: url("../../../assets/images/icon_checkbox.png") no-repeat
        center;
      border: 1px solid transparent;
      background-size: contain;
    }
  }
  &.radio_active {
    &::before {
      display: block;
      content: " ";
      background: url("../../../assets/images/icon_radio.png") no-repeat center;
      border: 1px solid transparent;
      background-size: contain;
    }
  }
}

// .check_default {
//             margin-right: 8px;
//             display: block;
//             width: 18px;
//             height: 18px;
//             background-color: #e9eaef;
//             border-radius: 50%;

//             &.check_active {
//                 background: url("../../../assets/images/icon_checkbox.png") no-repeat center;
//                 background-size: contain;
//             }
//         }
.title-row {
  background: #f3f4f8;
  color: #1a1a1a;
  padding: 5px 5px 3px;
  border-radius: 5px;
  font-size: 14px;
}
.option-row {
  line-height: 26px;
  font-size: 14px;
  display: flex;
  // align-items: center;
  position: relative;
  padding: 10px 0 5px;
  box-sizing: border-box;
  cursor: pointer;
  .el-col {
    display: flex;
    // align-items: center;
  }
  .el-col-6,
  .el-col-8,
  .el-col-11 {
    display: flex;
    justify-content: flex-end;
  }
  &.lines {
    margin-top: 5px;
    border-top: 1px solid #ededed;
  }
}

.el-icon-question {
  font-size: 16px;
  color: #4d4d4d;
  padding-left: 5px;
  padding-top: 5px;
}

.fontBold {
  font-weight: bold;
}
.videoDialog {
  /deep/.el-dialog__body {
    padding: 0;
    font-size: 0;
  }
}
</style>
