<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' || form.leixing === '2' || paymentType == '0'" />
    <template>
      <el-alert title="缴费设置"
                :closable="false"
                class="alert"
                type="info">
      </el-alert>
      <el-form ref="payment" :model="payment">
        <el-form-item
          label-width="160px"
          label="缴费方式"
          prop="paymentPattern"
          :rules="[{required: true, message: '请选择缴费方式', trigger: 'change'}]"
        >
          <el-select style="width: 100%!important;" v-model="payment.paymentPattern" placeholder="请选择缴费方式">
            <el-option
              v-for="item in paymentPatternTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template v-if="isMulticycle">
        <el-collapse :value="collapse" @change="collapseChange" >
          <el-collapse-item
            v-for="(item, index) in cycles"
            :key="index"
            :name="index"
          >
            <template slot="title">
              <div class="collapse-title">
                <span>缴费周期 {{index + 1}}</span>
                <i v-if="cycles.length > 1" class="el-icon-circle-close" @click.stop="removeCycle(index)"></i>
              </div>
            </template>
            <paymentCycle
              ref="cycles"
              :form="item"
              :hidePaymentPattern="true"
              :isCommon="isCommon"
              :isUserType="isUserType"
              :isDisabled="form.leixing === '1' || form.leixing === '2' || paymentType == '0'"
            />
          </el-collapse-item>
        </el-collapse>
        <el-button
          icon="el-icon-circle-plus-outline"
          plain
          type="info"
          size="small"
          style="width: 100%;margin: 20px 0;"
          @click="addCycle"
        >新增缴费周期</el-button>
      </template>
      <paymentCycle
        ref="cycle"
        :form.sync="cycle"
        :isCommon="isCommon"
        :hidePaymentPattern="true"
        :isUserType="isUserType"
        :isDisabled="form.leixing === '1' || form.leixing === '2' || paymentType == '0'"
        v-else
      />
    </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,
  musicGroupPaymentCalenderView,
} from "../api";
import { paymentPatternType } from '@/constant'
import { getTimes, objectToOptions } 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'
import numeral from 'numeral'

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: [0],
      nextVisible: false,
      typeList: [],
      charges: [],
      studentIds: '',
      payment: {
        paymentPattern: null,
      },
      viewDetail: null,
      organizationCourseUnitPriceSettingsByType: {},
      paymentPatternTypeOptions: objectToOptions(paymentPatternType),
    };
  },
  computed: {
    musicGroup() {
      return this.baseInfo?.musicGroup
    },
    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;
    },
    paymentAmountDisabled() {
      return (this.isUserType || (this.isCommon && this.isUserType)) && this.isDisabled
    },
    isMulticycle() {
      let editMulticycle = false
      let paymentType = ''
      if (this.viewDetail) {
        const { musicGroupPaymentCalenders, auditDto } = this.viewDetail
        paymentType = musicGroupPaymentCalenders[0]?.paymentType
        editMulticycle = (musicGroupPaymentCalenders.length > 1 || paymentType != 'ADD_COURSE')
        if (editMulticycle) {
          this.cycles = musicGroupPaymentCalenders.map(item => ({
            paymentAmount: item.paymentAmount,
            paymentDate: [item?.startPaymentDate, item?.deadlinePaymentDate],
            paymentValid: [item?.paymentValidStartDate, item?.paymentValidEndDate]
          }))
        }
      }
      return (this.payment.paymentPattern == 0 && this.form.leixing !== '2' && paymentType !== 'ADD_COURSE') || (this.payment.paymentPattern == 0 && editMulticycle)
    }
  },
  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) {
      if (val) {
        try {
          const res = await queryByMusicGroupOrganizationCourseSettingsId({
            id: val
          })
          this.eclass = res.data.filter(item => {
            return !item.isStudentOptional || this.paymentType !== undefined
          }) || [{}];

          this.syncAllMoney();
        } catch (error) { }
      }
    },
    'payment.paymentPattern'() {
      this.syncAllMoney()
    },
  },
  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);
        try {
          const res = await musicGroupPaymentCalenderView({
            musicGroupId: this.musicGroupId,
            batchNo: this.rowDetail.batchNo,
          })
          this.viewDetail = res.data
          this.eclass = (res.data.musicGroupPaymentCalenderCourseSettings || []).filter(item => {
            return !item.isStudentOptional || this.paymentType !== undefined
          })
          const firstPayment = res.data.musicGroupPaymentCalenders[0] || {}
          this.$set(this.payment, 'paymentPattern', String(this.viewDetail.auditDto?.paymentPattern))
          if (this.$refs.cycle) {
            this.$set(
              this.cycle,
              "paymentPattern",
              firstPayment.paymentPattern + ""
            );
            let arr = [
              firstPayment.paymentValidStartDate,
              firstPayment.paymentValidEndDate,
            ];
            // paymentDate startPaymentDate deadlinePaymentDate
            this.$set(this.cycle, "paymentDate", [firstPayment.startPaymentDate, firstPayment.deadlinePaymentDate]);
            this.$set(this.cycle, "paymentValid", arr);
          }
          this.studentIds = firstPayment.studentIds
          this.$set(this.form, 'musicGroupOrganizationCourseSettingId', res.data.auditDto?.musicGroupOrganizationCourseSettingsId)
          this.syncAllMoney()
        } catch (error) {}
      }
    },
    formatCourse() {
      const organId = this.musicGroup?.organId
      const chargeTypeId = this.musicGroup?.chargeTypeId
      const _ = {}
      const list = (this.organizationCourseUnitPriceSettings || [])
        .filter(item => organId && organId == item.organId && chargeTypeId && chargeTypeId == item.chargeTypeId)
      for (const item of list) {
        _[item.courseType] = item
      }
      this.organizationCourseUnitPriceSettingsByType = _
      return _
    },
    priceChange (item, index) {
      const _ = [...this.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.eclass = [..._]
      this.syncAllMoney()
    },
    syncAllMoney () {
      let money = 0;
      let first = 0
      let other = 0
      for (const item of this.eclass) {
        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
            console.log(remainder)
            first += floorMoney + remainder
            other += floorMoney
          }
        }
      }
      console.log(first, other)
      if (this.cycles && this.cycles.length) {
        this.cycles = this.cycles.map((item, index) => {
          return {
            ...item,
            paymentAmount: (index === 0 ? first : other)
          }
        })
      }
      // if (!money) {
        // this.$set(this.cycle, "paymentAmount", undefined);
      // } else {
        this.$set(this.cycle, "paymentAmount", money);
      // }

      return money;
    },
    async getChargeTypeList () {
      try {
        const res = await chargeTypeList({
          row: 9999,
        });
        this.typeList = res.data.rows;
      } catch (error) { }
    },
    async getCharges () {
      const organId = this.musicGroup?.organId;
      const chargeTypeId = this.musicGroup?.chargeTypeId;
      this.chargeTypeName = this.musicGroup?.chargeTypeName;
      try {
        const res = await musicGroupOrganizationCourseSettingsQueryPage({
          row: 9999,
          chargeTypeId,
          organId,
        });
        const ids = res.data.rows.map(item => item.id)
        if (!ids.includes(this.form.musicGroupOrganizationCourseSettingId)) {
          this.$set(this.form, 'musicGroupOrganizationCourseSettingId', null)
        }
        this.charges = res.data.rows;
      } 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.cycles.length - 1);
      this.syncAllMoney()
    },
    removeCycle (index) {
      this.cycles[index] = null;
      this.cycles = this.cycles.filter((item) => !!item);
      if (this.collapse.includes(index)) {
        this.collapse.splice(index, 1);
        this.collapse = this.collapse.map((item, _index) => _index - 1 >= index ? item -- : item)
      }
      this.syncAllMoney()
    },
    collapseChange (val) {
      this.collapse = val;
    },
    closeNext () {
      this.nextVisible = false;
    },
    getForms () {
      const { $refs: refs } = this;

      return [refs.base, refs.eclass, refs.cycle, ...(refs.cycles || []), refs.other, refs.payment]
        .filter((item) => !!item)
        .map((item) => item.$refs.form || item);
    },
    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 { leixing, ...rest } = {
          ...this.form,
          ...this.other,
          paymentPattern: this.payment.paymentPattern,
          musicGroupPaymentDateRangeList: [...this.cycles.map(item => {
            const { paymentDate, paymentValid, ...other } = item
            return {
              ...other,
              ...getTimes(paymentDate, ["startPaymentDate", "deadlinePaymentDate"]),
              ...getTimes(paymentValid, [
                "paymentValidStartDate",
                "paymentValidEndDate",
              ]),
            }
          })],
          musicGroupPaymentCalenderCourseSettingsList: this.eclass,
        };
        if (this.$refs.cycle) {
          const { paymentDate, paymentValid, ...other } = this.cycle
          rest.musicGroupPaymentDateRangeList = [{
              ...other,
              ...getTimes(paymentDate, ["startPaymentDate", "deadlinePaymentDate"]),
              ...getTimes(paymentValid, [
                "paymentValidStartDate",
                "paymentValidEndDate",
              ]),
          }]
        }
        const data = {
          ...rest,
          isGiveMusicNetwork: false,
          studentIds: this.studentIds,
          paymentType:
            paymentTypeFormat[
              this.paymentType == 0 ? this.paymentType : leixing
            ],
          musicGroupId: this.musicGroupId,
        };
        if (!this.rowDetail?.batchNo) {
          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.batchNo = this.rowDetail.batchNo
            // 缴费类型无法修改，按照之前覆盖
            data.paymentType = this.viewDetail.musicGroupPaymentCalenders[0]?.paymentType
            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>
