<template>
  <div>
    <el-alert title="课程信息设置"
              :closable="false"
              class="alert"
              type="info">
    </el-alert>
    <userBaseinfo :form.sync="form"
                  :isCommon="isCommon"
                  :isUserType="isUserType"
                  @getCharges="getCharges"
                  @changeActive="changeActive"
                  :typeList="typeList"
                  :charges="charges"
                  :rowDetail="rowDetail"
                  :chargeTypeName="chargeTypeName"
                  :paymentType="paymentType"
                  ref="base" />
    <template v-if="!isCommon">
      <el-alert title="加课信息设置"
                :closable="false"
                class="alert"
                type="info">
      </el-alert>
      <extraClass :form.sync="eclass"
                  ref="eclass"
                  @create="addExtraClass"
                  @remove="removeExtraClass"
                  :isUserType="isUserType"
                  :courseUnitPriceSettingsByType="organizationCourseUnitPriceSettingsByType"
                  @priceChange="priceChange"
                  :clearable="true"
                  @moneyChange="syncAllMoney" />
    </template>
    <extraClass v-else-if="(!isCommon && eclass.length) || isCommon"
                :form="eclass"
                ref="eclass"
                :isCommon="isCommon"
                @create="addExtraClass"
                @remove="removeExtraClass"
                @moneyChange="syncAllMoney"
                :courseUnitPriceSettingsByType="organizationCourseUnitPriceSettingsByType"
                :isUserType="isUserType"
                :isDisabled="form.leixing === '1' || paymentType == '0'" />
    <template>
      <el-alert title="缴费设置"
                :closable="false"
                class="alert"
                type="info">
      </el-alert>
      <paymentCycle ref="cycle"
                    :isUserType="isUserType"
                    :form.sync="cycle"
                    :isCommon="isCommon"
                    :isDisabled="true" />
    </template>
    <el-alert title="其它"
              :closable="false"
              class="alert"
              type="info">
    </el-alert>
    <otherform :form="other"
               ref="other" />
    <div slot="footer"
         class="dialog-footer">
      <el-button @click="$listeners.close">取 消</el-button>
      <el-button type="primary"
                 @click="submit">确认</el-button>
    </div>
    <el-dialog :title="nextTitle"
               :visible.sync="nextVisible"
               width="600px"
               append-to-body>
      <classrooms @close="closeNext" />
    </el-dialog>
  </div>
</template>
<script>
import {
  chargeTypeList,
  musicGroupOrganizationCourseSettingsQueryPage,
} from "@/api/specialSetting";
import { getMusicGroupPaymentCalenderDetail } from '@/api/buildTeam'
import {
  musicGroupPaymentCalenderAdd,
  musicGroupPaymentCalenderDetailBatchUpdate,
  queryByMusicGroupOrganizationCourseSettingsId,
} from "../api";
import { getTimes } from "@/utils";
import userBaseinfo from "./user-baseinfo";
import paymentCycle from "./payment-cycle";
import extraClass from "./extra-class";
import classrooms from "./classrooms";
import otherform from "./other";
import baseInfoVue from '../../teamDetail/components/baseInfo.vue';
import merge from 'webpack-merge'

const paymentTypeFormat = {
  0: "MUSIC_APPLY",
  1: "MUSIC_RENEW",
  2: "ADD_COURSE",
  3: "ADD_STUDENT",
};

export default {
  props: ["type", "musicGroupId", "baseInfo", "paymentType", "rowDetail", 'organizationCourseUnitPriceSettings'],
  components: {
    userBaseinfo,
    paymentCycle,
    extraClass,
    classrooms,
    otherform,
  },
  data () {
    return {
      options: [],
      form: {
        payUserType: this.type === "user" ? "STUDENT" : "SCHOOL",
        leixing: "1",
        musicGroupOrganizationCourseSettingId: null,
      },
      chargeTypeName: '',
      other: {},
      cycles: [{}],
      cycle: {},
      eclass: [],
      collapse: [],
      nextVisible: false,
      typeList: [],
      charges: [],
      organizationCourseUnitPriceSettingsByType: {},
    };
  },
  computed: {
    isCommon () {
      return this.form.leixing === "1";
    },
    isDisabled () {
      return this.form.leixing === "1" || String(this.paymentType) === "0";
    },
    isUserType () {
      return this.type === "user";
    },
    nextTitle () {
      return this.isCommon ? "乐团课程-班级选择" : "临时加课-班级选择";
    },
    chargesById () {
      const data = {};
      for (const item of this.charges) {
        data[item.id] = item;
      }
      return data;
    },
  },
  watch: {
    type () {
      this.$set(
        this.form,
        "payUserType",
        this.type === "user" ? "STUDENT" : "SCHOOL"
      );
    },
    baseInfo (val) {
      this.formatCourse()
      this.getCharges();
    },
    organizationCourseUnitPriceSettings() {
      this.formatCourse()
    },
    "form.leixing" (val) {
      this.cycles = [{}];
      this.collapse = [0];
      this.cycle = {};
      this.$set(this.form, "musicGroupOrganizationCourseSettingId", undefined);
      this.$set(this.cycle, "paymentAmount", undefined);
      if (val === "1") {
        this.eclass = [];
      } else if (val === "2") {
        this.eclass = [];
      }
    },
    async "form.musicGroupOrganizationCourseSettingId" (val) {
      try {
        const res = await queryByMusicGroupOrganizationCourseSettingsId({
          id: val
        })
        this.eclass = res.data.filter(item => {
          return !item.isStudentOptional || this.paymentType !== undefined
        }) || [{}];

        this.syncAllMoney();
      } catch (error) { }
    },
  },
  mounted () {
    this.formatCourse()
    this.init();
  },
  activated () {
    this.formatCourse()
    this.init();
  },
  methods: {
    async init () {
      this.getCharges();
      if (this.rowDetail) {
        for (const key in paymentTypeFormat) {
          if (paymentTypeFormat.hasOwnProperty(key)) {
            const item = paymentTypeFormat[key];
            if (item === this.rowDetail.paymentType) {
              this.paymentType = key
            }
          }
        }
        this.$set(
          this.other,
          "isGiveMusicNetwork",
          this.rowDetail.isGiveMusicNetwork
        );
        this.$set(this.other, "memo", this.rowDetail.memo);
        if (this.rowDetail.musicGroupOrganizationCourseSettingId) {
          this.form.musicGroupOrganizationCourseSettingId = this.rowDetail.musicGroupOrganizationCourseSettingId;
        } else {
          try {
            const res = await getMusicGroupPaymentCalenderDetail({
              id: this.rowDetail.id
            })
            this.eclass = res.data.musicGroupPaymentCalenderCourseSettings
            this.syncAllMoney()
          } catch (error) {}
        }
      }
    },
    formatCourse() {
      const organId = this.baseInfo?.musicGroup?.organId
      const chargeTypeId = this.baseInfo?.musicGroup?.chargeTypeId
      const _ = {}
      const list = (this.organizationCourseUnitPriceSettings || [])
        .filter(item => organId && organId == item.organId && chargeTypeId && chargeTypeId == item.chargeTypeId)
      for (const item of list) {
        _[item.courseType] = item
      }
      this.organizationCourseUnitPriceSettingsByType = _
      return _
    },
    priceChange (item, index) {
      const _ = [...this.eclass]
      const active = this.organizationCourseUnitPriceSettingsByType[item.courseType] || {}
      const price = Math.ceil((item.courseTotalMinuties || 1) * (active.unitPrice || 1))
      item.courseCurrentPrice = price
      item.courseOriginalPrice = price
      _[index] = item
      this.eclass = [..._]
      this.syncAllMoney()
    },
    syncAllMoney () {
      let money = 0;
      for (const item of this.eclass) {
        money += item.courseCurrentPrice;
      }
      if (!money) {
        this.$set(this.cycle, "paymentAmount", undefined);
      } else {
        this.$set(this.cycle, "paymentAmount", money);
      }
      if (this.rowDetail) {
        this.$set(
          this.cycle,
          "paymentPattern",
          this.rowDetail?.paymentPattern + ""
        );
        let arr = [
          this.rowDetail?.paymentValidStartDate,
          this.rowDetail?.paymentValidEndDate,
        ];
        // paymentDate startPaymentDate deadlinePaymentDate
        this.$set(this.cycle, "paymentDate", [this.rowDetail?.startPaymentDate, this.rowDetail?.deadlinePaymentDate]);
        this.$set(this.cycle, "paymentValid", arr);
      }

      return money;
    },
    async getChargeTypeList () {
      try {
        const res = await chargeTypeList({
          row: 9999,
        });
        this.typeList = res.data.rows;
      } catch (error) { }
    },
    async getCharges () {
      const organId = this.baseInfo?.musicGroup?.organId;
      const chargeTypeId = this.baseInfo?.musicGroup?.chargeTypeId;
      this.chargeTypeName = this.baseInfo?.musicGroup?.chargeTypeName;
      try {
        const res = await musicGroupOrganizationCourseSettingsQueryPage({
          row: 9999,
          chargeTypeId,
          organId,
        });
        const ids = res.data.rows.map(item => item.id)
        if (!ids.includes(this.form.musicGroupOrganizationCourseSettingId)) {
          this.$set(this.form, 'musicGroupOrganizationCourseSettingId', null)
        }
        this.charges = res.data.rows;
      } catch (error) { }
    },
    addExtraClass () {
      this.eclass.push({});
    },
    removeExtraClass (index) {
      this.eclass[index] = null;
      this.eclass = this.eclass.filter((item) => !!item);
    },
    addCycle () {
      this.cycles.push({});
      this.collapse.push(this.collapse.length);
    },
    removeCycle (index) {
      this.cycles[index] = null;
      this.cycles = this.cycles.filter((item) => !!item);
      this.collapse.pop();
    },
    collapseChange (val) {
      this.collapse = val;
    },
    closeNext () {
      this.nextVisible = false;
    },
    getForms () {
      const { $refs: refs } = this;
      return [refs.base, refs.eclass, refs.cycle, refs.other]
        .filter((item) => !!item)
        .map((item) => item.$refs.form);
    },
    changeActive(val) {
      if (this.$listeners.changeActive) {
        this.$listeners.changeActive(val)
      }
    },
    async submit() {
      const forms = this.getForms();
      const valided = [];
      for (const form of forms) {
        form.validate((valid) => {
          if (valid) {
            valided.push(form);
          }
        });
      }
      if (this.eclass.length < 1) {
        return this.$message.error('请至少选择一条加课信息')
      }
      if (valided.length === forms.length) {
        const { paymentDate, paymentValid, leixing, ...rest } = {
          ...this.form,
          ...this.other,
          ...this.cycle,
          musicGroupPaymentCalenderCourseSettingsList: this.eclass,
        };
        const data = {
          ...rest,
          isGiveMusicNetwork: false,
          paymentType:
            paymentTypeFormat[
            this.paymentType == 0 ? this.paymentType : leixing
            ],
          musicGroupId: this.musicGroupId,
          ...getTimes(paymentDate, ["startPaymentDate", "deadlinePaymentDate"]),
          ...getTimes(paymentValid, [
            "paymentValidStartDate",
            "paymentValidEndDate",
          ]),
        };
        if (!this.rowDetail?.id) {
          try {
            const res = await musicGroupPaymentCalenderAdd(data);
            this.$listeners.close();
            this.$listeners.submited(res.data);
            // 在这里
            if (this.$route.query.type == "teamDraft") {
              this.$router.push({
                query: merge(this.$route.query, { 'type': 'feeAudit' })
              });
            }
          } catch (error) { }
        } else {
          try {
            data.id = this.rowDetail.id
            const res = await musicGroupPaymentCalenderDetailBatchUpdate(data);
            this.$listeners.close();
            this.$listeners.submited(res.data);
            if (this.$route.query.type == "teamDraft") {
              this.$router.push({
                query: merge(this.$route.query, { 'type': 'feeAudit' })
              });

            }
          } catch (error) { }
        }
      }
    },
  },
};
</script>
<style lang="less" scoped>
.dialog-footer {
  margin-top: 20px;
  display: block;
  text-align: right;
}
.alert {
  margin-bottom: 10px;
}
.collapse-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  .el-icon-circle-close {
    font-size: 16px;
    margin-right: 10px;
  }
}
/deep/ .el-collapse-item__wrap {
  padding-top: 20px;
}
</style>
