<template>
  <div>
    <div class="soundBtnWrap">
      <el-button
        type="primary"
        @click="allin"
        v-if="teamStatus != 'resetTeam' && !basdisabled"
        >全选</el-button
      >
      <el-button
        type="danger"
        @click="deleteRow"
        v-if="teamStatus != 'resetTeam' && !basdisabled"
        >删除</el-button
      >
      <el-button type="primary" @click="soundVisible = true" v-if="!basdisabled"
        >添加</el-button
      >
    </div>
    <div class="coreWrap">
      <el-checkbox-group v-model="checkList" @change="lookCheck">
        <el-collapse v-model="chioseActiveSound">
          <el-collapse-item
            v-for="(item, index) in activeSoundList"
            :name="item.id"
            :key="index"
          >
            <template slot="title">
              <div class="coreItemTitle">
                <el-checkbox :label="item.id" :disabled="basdisabled">{{
                  item.sound
                }}</el-checkbox>
              </div>
            </template>
            <div class="coreItem">
              <div class="coreItemRow">
                <p class="title">计划招生人数:</p>
                <el-input
                  :disabled="basdisabled"
                  style="width: 180px"
                  v-model="item.expectedStudentNum"
                ></el-input>
              </div>
            </div>
            <el-divider></el-divider>
            <chioseMusic
              :activeSoundList="activeSoundList"
              :item="item"
              @lookMusic="lookMusic"
              :basdisabled="basdisabled"
            />
            <div class="coreItemRow">
              <p class="title">教辅:</p>
              <el-select
                style="width: 558px !important"
                v-model="item.markChioseList"
                :disabled="basdisabled"
                clearable
                filterable
                multiple
              >
                <el-option
                  v-for="(item, index) in item.markList"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                >
                  <span style="float: left">{{ item.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px; padding-right:20px">{{
                    item.groupPurchasePrice|moneyFormat
                  }}元</span>
                </el-option>
              </el-select>
            </div>
          </el-collapse-item>
        </el-collapse>
      </el-checkbox-group>
    </div>
    <el-dialog title="声部选择" :visible.sync="soundVisible" destroy-on-close>
      <chioseSoundList
        :soundList="soundList"
        :activeSound="activeSound"
        @chioseSound="chioseSound"
      />
    </el-dialog>
  </div>
</template>
<script>
import store from "@/store";
import { formatData } from "@/utils/utils";
import {
  getSubject,
  getDefaultSubject,
  getGoods,
  createTeam,
  getSoundTree,
  findMusicGroupSubjectInfo,
  updateSubjectInfo,
  auditSuccess,
  auditFailed,
  getSubjectGoods,
} from "@/api/buildTeam";
import dayjs from "dayjs";
import chioseSoundList from "./chioseSoundList";
import chioseMusic from "./chioseMusic";
import { findIndex } from "lodash";
import numeral from "numeral";
export default {
  components: { chioseSoundList, chioseMusic },
  data() {
    return {
      soundList: [], // 接口返回的一级二级声部
      soundVisible: false, // 设置声部弹窗
      childSoundList: [],
      activeSoundList: [], //列表上的声部
      activeSound: null, // 展开的列表
      chioseActiveSound: [],
      soundList: [], // 接口返回的一级二级声部
      childSoundList: [],
      teamStatus: "", // 乐团状态
      checkList: [],
      basdisabled: false,
    };
  },
  mounted() {
    this.init();
  },
  activated() {
    this.init();
  },
  methods: {
    init() {
      // 获取第一页的数据
      this.topfor = this.$store.getters.topinfo;
      let type = this.topfor.type;
      let section = this.topfor.section;
      this.teamStatus = this.$route.query.type;
      if (this.$route.query.search) {
        this.Fsearch = this.$route.query.search;
      }
      if (this.$route.query.rules) {
        this.Frules = this.$route.query.rules;
      }
      if (
        this.teamStatus == "look" ||
        this.teamStatus == "teamAudit" ||
        this.teamStatus == "feeAudit"
      ) {
        this.basdisabled = true;
      } else {
        this.basdisabled = false;
      }
      getSoundTree({ tenantId: 1 }).then((res) => {
        if (res.code == 200) {
          this.soundList = res.data.rows;
          if (this.teamStatus == "newTeam" && type && section) {
            getDefaultSubject({
              chargeTypeId: type,
              organId: section,
              number: 1,
            }).then((res) => {
              if (res.code == 200) {
                let activeSound = [];
                this.activeSoundList = res.data.map((item) => {
                  activeSound.push(item.id);
                  return this.initSound(item);
                });
                this.activeSound = activeSound;
                this.chioseActiveSound = activeSound;
                this.changeActiveSound(activeSound.join(","));
              }
            });
          } else {
            this.teamid = this.$route.query.id;
            if (this.teamid) {
              findMusicGroupSubjectInfo({ musicGroupId: this.teamid }).then(
                (res) => {
                  if (res.code == 200) {
                    let activeSound = [];
                    this.activeSoundList = res.data?.musicGroupSubjectPlans.map(
                      (item) => {
                        activeSound.push(item.subjectId);
                        return {
                          id: parseInt(item.subjectId),
                          sound: item.subName,
                          expectedStudentNum: item.expectedStudentNum,
                          chioseMusic: [],
                          markChioseList: [],
                          goodsList: [],
                          markList: [],
                        };
                      }
                    );
                    this.activeSound = activeSound;
                    this.chioseActiveSound = activeSound;
                    this.changeActiveSound(activeSound.join(","));
                    // 格式化商品和教辅
                    res.data.musicGroupSubjectGoodsGroups.forEach((shop) => {
                      let index = findIndex(this.activeSoundList, (o) => {
                        return o.id == shop.subjectId;
                      });

                      if (index != -1) {
                        if (shop.type == "ACCESSORIES") {
                          shop.goodsIdList.split(",").forEach((item) => {
                            this.activeSoundList[index].markChioseList.push(
                              parseInt(item)
                            );
                          });
                        } else if (shop.type == "INSTRUMENT") {
                          // 商品
                          let typeJson = Object.keys(
                            JSON.parse(shop.kitGroupPurchaseTypeJson)
                          );
                          this.activeSoundList[index].chioseMusic.push({
                            musical: parseInt(shop.goodsIdList),
                            type: typeJson,
                            groupPrice: shop.price,
                            borrowPrice: shop.depositFee,
                            groupRemissionCourseFee: Boolean(
                              shop.groupRemissionCourseFee
                            ),
                          });
                        }
                      }
                    });
                  }
                  console.log(this.activeSoundList);
                }
              );
            }
          }
        }
      });
      getSubject({ tenantId: 1 }).then((res) => {
        if (res.code == 200) {
          this.childSoundList = res.data;
        }
      });
    },
    lookCheck(val) {
      this.checkList = [...new Set(val)];
    },
    chioseSound(activeSound) {
      // 同步数据
      this.activeSound = [...new Set(activeSound)];
      let newSoundList = [];

      for (let i in this.childSoundList) {
        if (this.activeSound.includes(this.childSoundList[i].id)) {
          newSoundList.push(this.initSound(this.childSoundList[i]));
        }
      }
      let idList = this.activeSoundList.map((item) => {
        return item.id;
      });
      for (let x in newSoundList) {
        const indexof = idList.indexOf(newSoundList[x]?.id);
        if (indexof > -1) {
          newSoundList[x] = this.activeSoundList[indexof];
        }
      }
      this.activeSoundList = newSoundList;
      let newActiveSound = [];
      this.activeSoundList.forEach((item) => {
        newActiveSound.push(item.id);
      });
      this.activeSound = newActiveSound;
      this.chioseActiveSound = newActiveSound;
      this.changeActiveSound(newActiveSound.join(","));
      this.soundVisible = false;
    },
    initSound(item) {
      let obj = {
        id: item.id,
        sound: item.name,
        expectedStudentNum: item.expectedStudentNum,
        chioseMusic: [
          {
            musical: "",
            type: ["GROUP"],
            groupPrice: 0,
            borrowPrice: 1500,
            groupRemissionCourseFee: Boolean(item.groupRemissionCourseFee),
          },
        ],
        markChioseList: [],
        goodsList: [],
        markList: [],
      };
      return obj;
    },
    changeActiveSound(val) {
      // 写入声部商品和辅件
      getSubjectGoods({
        subjectIds: val,
        chargeTypeId: this.topfor.type,
      }).then((res) => {
        if (res.code == 200) {
          if (res.data) {
            let keys = Object.keys(res.data);
            this.activeSoundList.forEach((item) => {
              if (keys.indexOf(item.id + "") != -1) {
                let goodList = [];
                let markList = [];
                res.data[item.id].forEach((shop) => {
                  if (shop.type == "INSTRUMENT") {
                    goodList.push(shop);
                  } else if (shop.type == "ACCESSORIES") {
                    markList.push(shop);
                  }
                });
                item.goodsList = goodList;
                item.markList = markList;
              }
            });
          }
        }
      });
    },

    lookMusic() {},

    submitInfo(type) {
      // 计划招生人数
      // 可选乐器
      // 教辅

      if (this.activeSoundList.length <= 0) {
        this.$message.error(`请至少设置一个声部`);
        return;
      }
      let flag = true;
      this.activeSoundList.forEach((item) => {
        if (!item.expectedStudentNum) {
          this.$message.error(`请填写${item.sound}的预计招生人数`);
          flag = false;
          return;
        }
        if (!item.chioseMusic[0]?.musical) {
          this.$message.error(`请至少一个选择${item.sound}的可选乐器`);
          flag = false;
          return;
        }
        item.chioseMusic.forEach((music) => {
          if (music.type.indexOf("LEASE") != -1) {
            if (!music.borrowPrice || parseFloat(music.borrowPrice) <= 0) {
              this.$message.error(`请填写正确的${item.sound}租赁押金`);
              flag = false;
            }
          }
        });
      });
      if (!flag) return;
      // 新建团
      let obj = {};
      if (this.teamStatus == "newTeam") {
        this.initCreateTeam(obj);
      }
      //  初始化声部
      obj.musicGroupSubjectGoodsGroups = [];
      obj.musicGroupSubjectPlans = [];
      this.activeSoundList.forEach((active) => {
        // 格式化声部数据
        let item = {
          expectedStudentNum: active.expectedStudentNum,
          subName: active.sound,
          subjectId: active.id,
        };
        obj.musicGroupSubjectPlans.push(item);
        // 格式化商品数据 chioseMusic: [{ musical: '', type: ["GROUP"], groupPrice: 0, borrowPrice: 1500 }],

        active.chioseMusic.forEach((music) => {
          console.log(music);
          let goodsItem = null;
          let depositFee = music.borrowPrice;
          let price = music.groupPrice;
          let groupRemissionCourseFee;
          if (music.type.indexOf("GROUP") != -1) {
            groupRemissionCourseFee = music.groupRemissionCourseFee * 1;
          } else {
            groupRemissionCourseFee = 0;
          }

          let index = findIndex(active.goodsList, (o) => {
            return o.id == music.musical;
          });
          if (index != -1) {
            goodsItem = active.goodsList[index];
          }
          let kitGroupPurchaseTypeJson = {};
          music.type.forEach((type) => {
            kitGroupPurchaseTypeJson[type] = 0;
          });
          // if (Array.isArray(music.type)) {
          //   music.type.forEach((type) => {
          //     kitGroupPurchaseTypeJson[type] = 0;
          //   });
          // }else{
          //   // 字符串
          //   let arr = [ music.type]
          //     arr.forEach((type) => {
          //     kitGroupPurchaseTypeJson[type] = 0;
          //   });
          // }
          kitGroupPurchaseTypeJson = JSON.stringify(kitGroupPurchaseTypeJson);
          if (goodsItem) {
            let some = {
              subjectId: active.id,
              type: "INSTRUMENT",
              goodsIdList: music.musical,
              name: goodsItem.name,
              kitGroupPurchaseTypeJson,
              depositFee,
              price,
              groupRemissionCourseFee,
            };
            obj.musicGroupSubjectGoodsGroups.push(some);
          }
        });
        // 格式化辅件
        //  markChioseList: [],
        // goodsList: [],
        // markList: [],
        active.markChioseList.forEach((ass) => {
          let index = findIndex(active.markList, (o) => {
            return o.id == ass;
          });
          let goodsItem = null;
          if (index != -1) {
            goodsItem = active.markList[index];
          }
          if (goodsItem) {
            let some = {
              subjectId: active.id,
              type: "ACCESSORIES",
              goodsIdList: ass,
              name: goodsItem.name,
              price: goodsItem.groupPurchasePrice,
            };
            obj.musicGroupSubjectGoodsGroups.push(some);
          }
        });
      });
      if (this.teamStatus == "newTeam") {
        createTeam(obj).then((res) => {
          if (res.code == 200) {
            // 成功 跳转到乐团报名详情
            let query = this.$route.query;
            query.type = "teamDraft";
            this.$router.push({
              query: {
                ...query,
                id: res.data,
              },
            });
            this.$emit("chiosetab", 2);
            this.$emit("getBaseInfo", obj);
            //  zheli
          }
        });
      } else {
        obj.musicGroupId = this.teamid;

        if (type) {
          obj.musicGroupStatus = "AUDIT";
        } else {
          obj.musicGroupStatus = "DRAFT";
        }

        updateSubjectInfo(obj).then((res) => {
          if (res.code == 200) {
            this.$message.success("提交成功");
            this.$emit("chiosetab", 2);
          }
        });
      }
    },
    deleteRow() {
      if (this.checkList.length < 1) {
        this.$message.error("请至少勾选一个");
        return;
      }
      for (let i = 0; i < this.activeSoundList.length; i++) {
        let index = this.checkList.indexOf(this.activeSoundList[i].id);
        if (index != -1) {
          this.activeSoundList.splice(i, 1);
          this.activeSound.splice(i, 1);
          i--;
        }
      }
      this.checkList = [];
    },
    allin() {
      this.checkList = [];
      this.activeSoundList.forEach((item, index) => {
        this.checkList.push(item.id);
      });
    },

    initCreateTeam(obj) {
      let enrollClasses;
      this.topfor.startClass
        ? (enrollClasses = this.topfor.startClass.join(","))
        : (enrollClasses = null);
      obj.musicGroup = {
        settlementType: this.topfor.salary,
        applyExpireDate: dayjs(this.topfor.time).format("YYYY-MM-DD HH:mm:ss"),
        chargeTypeId: this.topfor.type,
        cooperationOrganId: this.topfor.school,
        teamTeacherId: this.topfor.boss,
        educationalTeacherId: this.topfor.teacher,
        enrollClasses,
        name: this.topfor.name,
        organId: this.topfor.section,
        paymentPattern: this.topfor.paymentPattern,
        paymentValidStartDate: this.topfor.paymentValidStartDate
          ? dayjs(this.topfor.paymentValidStartDate).format("YYYY-MM-DD")
          : this.topfor.paymentValidStartDate,
        paymentValidEndDate: this.topfor.paymentValidEndDate
          ? dayjs(this.topfor.paymentValidEndDate).format("YYYY-MM-DD")
          : this.topfor.paymentValidEndDate,
        // paymentMonths:obj.months  有待确认
        schoolId: this.topfor.address,
        expectStartGroupDate: this.topfor.startTime,
        isClassroomLessons: this.topfor.isClass,
        status: "DRAFT",
        ownershipType: this.topfor.ownershipType,
        repairUserId: this.topfor.repairUserId,
        feeType: this.topfor.feeType,
      };
      return obj;
    },
  },
  watch: {
    activeSoundList: {
      immediate: true,
      deep: true,
      handler(n) {
        let chioseSoundNum = 0;
        let PlannedCount = 0;
        let activeSoundList = this.activeSoundList;
        if (n) {
          let Count = 0;
          if (n.length > 0) {
            for (let item in n) {
              Count += parseInt(n[item]?.expectedStudentNum) || 0;
            }
          }

          chioseSoundNum = n.length;
          PlannedCount = Count;
          this.$emit("getNumber", chioseSoundNum, PlannedCount);
        }
      },
    },
  },
};
</script>
<style lang="scss" scoped>
.soundBtnWrap {
  margin-bottom: 20px;
}
/deep/.el-collapse-item__header {
  background-color: #edeef0;
}
.coreItemTitle {
  background-color: #edeef0;
  height: 46px;
  line-height: 46px;
  padding: 0 20px;
}
.coreItem {
  padding: 25px 0 0;
}
.coreItemRow {
  padding: 0 20px;
  line-height: 50px;
  display: flex;
  flex-direction: row;
  align-items: center;
  p {
    margin-right: 10px;
  }
  .title {
    width: 140px;
    text-align: right;
  }
}
.marginLeft10 {
  margin-left: 10px;
}
/deep/.el-collapse-item__header {
  border-bottom: 1px solid #fff;
}
</style>
