<template>
  <div class="teamCourseList">
    <p class="coreTitle">
      管乐AI学练宝
      <el-form-item
        label="是否展示"
        prop="isShowMemberForPay"
        v-if="allCourseCurrentPrice == 0"
        class="titleFormItem"
      >
        <el-select
          style="width: 100% !important"
          v-model="form.isShowMemberForPay"
          placeholder="请选择是否展示学练宝费用"
          size="mini"
        >
          <el-option label="是" :value="true"> </el-option>
          <el-option label="否" :value="false"> </el-option>
        </el-select>
      </el-form-item>

      <el-button
        icon="el-icon-plus"
        size="mini"
        plain
        class="addBtn"
        @click="$listeners.create"
        v-if="!isDisabled"
        >新增学练宝</el-button
      >
    </p>

    <el-table
      class="courseTable"
      :data="form.memberList"
      style="width: 100% !important; background: #f9f9f9"
      :header-cell-style="{ background: '#F9F9F9', color: '#444' }"
    >
      <el-table-column
        width="170px"
        label="学练宝版本"
        prop="memberRankSettingId"
        key="memberRankSettingId"
      >
        <template slot-scope="scope">
          <el-form-item
            :prop="'memberList.' + scope.$index + '.memberRankSettingId'"
            :rules="{
              required: true,
              message: '请选择学练宝版本',
              trigger: 'change'
            }"
          >
            <!-- <el-select
              style="width: 90% !important"
              v-model="form.memberList[scope.$index].memberRankSettingId"
              placeholder="学练宝版本"
            >
              <el-option
                :value="item.id"
                :label="item.name"
                v-for="item in memberRankList"
                :key="item.id"
              ></el-option>
            </el-select> -->
            <el-cascader
              filterable
              style="width: 90% !important"
              v-model="form.memberList[scope.$index].memberRankSettingId"
              clearable
              placeholder="请选择学练宝版本"
              :options="memberRankList"
              :props="{ value: 'id', label: 'name' }"
              @change="(val) => changeMember(val, scope.$index)"
              @visible-change="(value) => onVisibleChange(value, form.memberList[scope.$index].memberRankSettingId)"

            ></el-cascader>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column
        label="是否必选"
        prop="optionalFlag"
        key="optionalFlag"
        width="170px"
      >
        <template slot-scope="scope">
          <el-form-item
            :prop="'memberList.' + scope.$index + '.optionalFlag'"
            :rules="{
              required: true,
              message: '请选择是否必选',
              trigger: 'change'
            }"
          >
            <el-select
              style="width: 90% !important"
              v-model="form.memberList[scope.$index].optionalFlag"
              placeholder="是否必选"
              :disabled="!(form.memberList[scope.$index].memberRankSettingId && form.memberList[scope.$index].memberRankSettingId.length > 0)"
              clearable
            >
              <el-option
                v-for="(item, index) in boolOptionsOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column
        label="自动激活"
        prop="autoActivationFlag"
        key="autoActivationFlag"
        width="170px"
      >
        <template slot-scope="scope">
          <el-form-item
            :prop="'memberList.' + scope.$index + '.autoActivationFlag'"
            :rules="{
              required: true,
              message: '请选择是否自动激活',
              trigger: 'change'
            }"
          >
            <el-select
              style="width: 90% !important"
              v-model="form.memberList[scope.$index].autoActivationFlag"
              placeholder="请选择是否自动激活"
              :disabled="!(form.memberList[scope.$index].memberRankSettingId && form.memberList[scope.$index].memberRankSettingId.length > 0) || !(form.memberList[scope.$index].memberRankSettingId && showAutoActivationFlag[form.memberList[scope.$index].memberRankSettingId[form.memberList[scope.$index].memberRankSettingId.length - 1]])"
              clearable
            >
              <el-option
                v-for="(item, index) in boolOptionsOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="会员周期" prop="num" key="num" width="170px">
        <template slot-scope="scope">
          <el-form-item
            :prop="'memberList.' + scope.$index + '.num'"
            :rules="[
              {
                required: true,
                message: '请选择会员周期',
                trigger: 'blur'
              }
            ]"
          >
            <el-input-number
              style="width: 90% !important"
              class="number-input"
              v-model="form.memberList[scope.$index].num"
              :controls="false"
              :precision="0"
              :min="1"
              @change="
                changeMemberperiodEnum(form.memberList[scope.$index].period, scope.$index)
              "
              placeholder="会员周期"
              :disabled="!(form.memberList[scope.$index].memberRankSettingId && form.memberList[scope.$index].memberRankSettingId.length > 0)"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column
        label="周期单位"
        prop="period"
        key="period"
        width="170px"
      >
        <template slot-scope="scope">
          <el-form-item
            :prop="'memberList.' + scope.$index + '.period'"
            :rules="[
              {
                required: true,
                message: '请选择周期单位',
                trigger: 'blur'
              }
            ]"
          >
            <el-select
              v-model="form.memberList[scope.$index].period"
              style="width: 90% !important"
              @change="(val) => changeMemberperiodEnum(val, scope.$index)"
              :disabled="!(form.memberList[scope.$index].memberRankSettingId && form.memberList[scope.$index].memberRankSettingId.length > 0)"
            >
              <el-option
                :label="item.label"
                :value="item.value"
                v-for="item in memberEnumList"
                :key="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column
        label="售价(元)"
        prop="actualAmount"
        key="actualAmount"
        width="170px"
        v-if="form.calenderFeeType != 'TEACHER'"
      >
        <template slot="header">
          <p style="position: relative">
            售价(元)
            <el-tooltip placement="top" popper-class="mTooltip">
              <div slot="content">学生实际缴费金额</div>
              <i
                class="el-icon-question"
                style="font-size: 18px; color: #f56c6c;top:2px;position: relative"
              ></i>
            </el-tooltip>
          </p>
        </template>
        <template slot-scope="scope">
          <el-form-item
            :prop="'memberList.' + scope.$index + '.actualAmount'"
            :rules="[
              {
                required: true,
                message: '请输入售价',
                trigger: 'blur'
              },
              { validator: validateMember, index: scope.$index, trigger: 'blur' }
            ]"
          >
            <!-- $listeners.moneyChange -->
            <el-input-number
              style="width: 90% !important"
              class="number-input"
              v-model="form.memberList[scope.$index].actualAmount"
              :controls="false"
              :precision="0"
              :min="0"
              @change="change"
              :disabled="
                !form.memberList[scope.$index].period ||
                  !form.memberList[scope.$index].num
              "
              placeholder="请输入售价"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column
        label="原价(元)"
        prop="originalAmount"
        key="originalAmount"
        width="170px"
      >
        <template slot-scope="scope">
          <el-form-item
            :prop="'memberList.' + scope.$index + '.originalAmount'"
            :rules="{
              required: true,
              message: '请输入原价',
              trigger: 'blur'
            }"
          >
            <!-- $listeners.moneyChange -->
            <el-input-number
              style="width: 90% !important"
              class="number-input"
              v-model="form.memberList[scope.$index].originalAmount"
              :controls="false"
              :precision="0"
              :min="0"
              @change="change"
              :disabled="true"
              placeholder="请输入原价"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column prop="close" key="close">
        <template slot-scope="scope">

          <div
            style="color: #fa6400; cursor: pointer; display: inline-block;"
            v-if=" form.memberList.length > 1"
            @click="() => onRemove(scope.$index)"
          >
            <i class="el-icon-error"></i>
            删除
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import { courseType, boolOptions } from "@/constant";
import { objectToOptions } from "@/utils";
import { memberEnumList } from "@/utils/searchArray";
import { getMemberFee } from "../api";
export default {
  props: [
    "form",
    "memberRankList",
    "organId",
    "rulesForm",
    "showAutoActivationFlag"
  ],
  data() {
    return {
      charges: [],
      clearable: false,
      isDisabled: false,
      courseUnitPriceSettingsByType: [],
      boolOptionsOptions: objectToOptions(boolOptions),
      memberEnumList,
      memberPrice: {},
      memberPriceList: [],
      getMemberFeeFlag: true
    };
  },
  async mounted() {
    this.form.memberList.forEach(async (item, index) => {
      await this.changeMember(item.memberRankSettingId, index)
    })
  },
  methods: {
    onVisibleChange(value, id) {
      if(!value) return
      const tempId = id ? id[id.length - 1] : null
      const ids = []
      this.form.memberList.forEach(item => {
        const itemId = item.memberRankSettingId ? item.memberRankSettingId[item.memberRankSettingId.length - 1] : null
        if(itemId !== tempId) {
          ids.push(itemId)
        }
      })
      // console.log(ids, 'ids')
      // console.log(value, id, 'teachList', this.memberRankList)
      this.memberRankList.forEach((item) => {
        if(ids.includes(item.id)) {
          item.disabled = true;
        } else {
          item.disabled = false;
        }

        if(item.children && item.children.length > 0) {
          item.children.forEach(child => {
            if(ids.includes(child.id)) {
              child.disabled = true;
            } else {
              child.disabled = false;
            }
          })
        }
      })
      this.$forceUpdate();
    },
    changeMemberperiodEnum(val, index) {
      // console.log(this.memberPriceList, val, index, "changeMemberperiodEnum");
      if (val == "DAY") {
        this.$set(
          this.form.memberList[index],
          "actualAmount",
          this.memberPriceList[index].groupPurchaseDayFee * this.form.memberList[index].num
        );
        this.$set(
          this.form.memberList[index],
          "originalAmount",
          this.memberPriceList[index].originalDayFee * this.form.memberList[index].num
        );
      }
      if (val == "MONTH") {
        this.$set(
          this.form.memberList[index],
          "actualAmount",
          this.memberPriceList[index].groupPurchaseMonthFee * this.form.memberList[index].num
        );
        this.$set(
          this.form.memberList[index],
          "originalAmount",
          this.memberPriceList[index].originalMonthFee * this.form.memberList[index].num
        );
      }
      if (val == "QUARTERLY") {
        this.$set(
          this.form.memberList[index],
          "actualAmount",
          this.memberPriceList[index].groupPurchaseQuarterlyFee *
            this.form.memberList[index].num
        );
        this.$set(
          this.form.memberList[index],
          "originalAmount",
          this.memberPriceList[index].originalQuarterlyFee * this.form.memberList[index].num
        );
      }
      if (val == "YEAR_HALF") {
        this.$set(
          this.form.memberList[index],
          "actualAmount",
          this.memberPriceList[index].groupPurchaseHalfYearFee *
            this.form.memberList[index].num
        );
        this.$set(
          this.form.memberList[index],
          "originalAmount",
          this.memberPriceList[index].originalHalfYearFee * this.form.memberList[index].num
        );
      }
      if (val == "YEAR") {
        this.$set(
          this.form.memberList[index],
          "actualAmount",
          this.memberPriceList[index].groupPurchaseYearFee * this.form.memberList[index].num
        );
        this.$set(
          this.form.memberList[index],
          "originalAmount",
          this.memberPriceList[index].originalYearFee * this.form.memberList[index].num
        );
      }
    },
    async changeMember(val, index) {
      if (val && val.length > 0) {
        if (this.getMemberFeeFlag) {
          this.getMemberFeeFlag = false;
          try {
            const res = await getMemberFee({
              rankId: val[val.length - 1],
              organId: this.organId
            });
            this.memberPriceList[index] = res.data
            this.getMemberFeeFlag = true;
            if (!res.data) {
              this.$bus.$emit("showguide", ["memberList"]);
              return;
            }
          } catch (e) {
            console.log(e);
            this.getMemberFeeFlag = true;
          }
        }
      }
    },
    validateMember(rule, value, callback) {
      const one = Number(value);
      let min = 0;
      let max = 0;
      switch (this.form.memberList[rule.index]?.period) {
        case "MONTH": {
          min =
            Number(this.rulesForm.minMonthFee) * this.form.memberList[rule.index].num;
          max =
            Number(this.rulesForm.maxMonthFee) * this.form.memberList[rule.index].num;
          break;
        }
        case "QUARTERLY": {
          min =
            Number(this.rulesForm.minQuarterlyFee) *
            this.form.memberList[rule.index].num;
          max =
            Number(this.rulesForm.maxQuarterlyFee) *
            this.form.memberList[rule.index].num;
          // console.log(
          //   this.form.memberList[rule.index]?.period,
          //   min,
          //   max,
          //   this.rulesForm
          // );
          break;
        }
        case "YEAR_HALF": {
          min =
            Number(this.rulesForm.minHalfYearFee) * this.form.memberList[rule.index].num;
          max =
            Number(this.rulesForm.maxHalfYearFee) * this.form.memberList[rule.index].num;
          break;
        }
        case "YEAR": {
          min = Number(this.rulesForm.minYearFee) * this.form.memberList[rule.index].num;
          max = Number(this.rulesForm.maxYearFee) * this.form.memberList[rule.index].num;
          break;
        }
      }

      if (one >= min && one <= max) {
        return callback();
      }
      return callback(new Error(`定价应在${min}-${max}之间`));
    },
    onRemove(index) {
      this.memberPriceList.splice(index, 1)
      this.$forceUpdate();
      this.$listeners.remove && this.$listeners.remove(index)
    }
  },
  computed: {
    allCourseCurrentPrice() {
      let price = 0;
      this.form.memberList.forEach(element => {
        price += element.actualAmount;
      });
      if (price > 0) {
        this.form.isShowMemberForPay = true;
      }
      return price;
    }
  }
};
</script>
<style lang="scss" scoped>
@import "~@/views/resetTeaming/modals/pay.scss";
</style>
