<template>
  <div>
    <!-- <p class="title">已选择{{ multipleSelection.length }}名学员</p> -->
    <el-form :model="memberForm" label-width="110px" ref="memberForm">
      <el-form-item label="学练宝版本" prop="memberRankId" :rules="[
          { required: true, message: '请选择学练宝版本', trigger: 'blur' }
        ]">
          <el-cascader
            v-model.trim="memberForm.memberRankId"
            style="width: 100% !important"  
            :options="memberRankList"
            :props="{ value: 'id', label: 'name',  }"
            :show-all-levels="false"
            collapse-tags
            clearable
            @change="getMemberList"
            placeholder="请选择学练宝版本"
          ></el-cascader>
          <!-- <el-select
            placeholder="请选择学练宝版本"
            clearable
            v-model.trim="memberForm.memberRankId"
            @change="getMemberList"
            style="width: 100% !important"
          >
            <el-option v-for="(item, index) in memberFeeSettingList" :key="index" :label="item.rankName" :value="item.id"></el-option>
          </el-select> -->
        </el-form-item>
      <el-form-item
        label="学练宝周期"
        prop="period"
        :rules="[
          { required: true, message: '请选择学练宝周期', trigger: 'blur' }
        ]"
      >
        <el-select
          placeholder="学练宝周期"
          clearable
          v-model.trim="memberForm.period"
          @change="getMemberList"
          style="width: 100% !important"
        >
          <el-option label="月度" value="MONTH"></el-option>
          <!-- <el-option label="季度" value="QUARTERLY"></el-option> -->
          <el-option label="半年" value="YEAR_HALF"></el-option>
          <el-option label="年度" value="YEAR"></el-option>
          <!-- <el-option label="固定天数" value="DAY"></el-option> -->
        </el-select>
      </el-form-item>
      <el-form-item
        label="学练宝周期数"
        prop="memberNum"
        :rules="[
          { required: true, message: '请输入学练宝周期数', trigger: 'blur' }
        ]"
      >
        <el-input
          type="number"
          @input="getMemberList"
          onKeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))"
          v-model="memberForm.memberNum"
          placeholder="请输入学练宝周期数"
        >
        </el-input>
      </el-form-item>
      <el-form-item
        label="缴费金额"
        prop="actualAmount"
        :rules="[
          { required: true, message: '请输入缴费金额', trigger: 'blur' },
          { validator: validateMember, trigger: 'blur' }
        ]"
      >
        <!-- onKeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))" -->
        <el-input
          type="number"
          @keyup.native="keyupEvent($event)"
          v-model="memberForm.actualAmount"
          placeholder="请输入缴费金额"
        >
          <div slot="append">元/人</div>
        </el-input>
      </el-form-item>
      <p style="color: red; padding: 0 0 20px 100px">
        若修改默认金额需审核通过后生效
      </p>
      <el-form-item
        label="备注"
        prop="remark"
        :rules="[{ required: true, message: '请输入备注', trigger: 'blur' }]"
      >
        <el-input
          type="textarea"
          show-word-limit
          maxlength="100"
          :rows="3"
          v-model.trim="memberForm.remark"
          placeholder="请输入备注"
        ></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { add, update } from "../api";
import { getmemberRankOrganizationFeeMapper, getAllMemberFindByOrganIds } from "@/views/categroyManager/productSystem/api";
import { sysConfigList } from "@/api/generalSettings"; // 平台的修改和查
export default {
  props: ["multipleSelection", "type"],
  data() {
    return {
      memberForm: {
        memberRankId: [],
        memberNum: null,
        actualAmount: null,
        period: null,
        remark: null
      },
      userIds: [],
      memberRankList: [],
      organId: null,
      rulesForm: null, // 范围
      memberFeeSettingList: [],
      memberFeeSetting: null
    };
  },
 async mounted() {
    if (this.type == "update") {
      const {
        memberNum,
        actualAmount,
        memberRankSettingId,
        period,
        remark,
        organId,
        id
      } = this.multipleSelection;
      this.organId = organId;
      // const memberInfo = await getAllMemberFindByOrganIds([organId])
      // this.memberRankList = memberInfo.data || []
      this.memberForm = {
        memberNum,
        memberRankId: memberRankSettingId,  // this.formatParentId(memberRankSettingId, this.memberRankList),
        period,
        actualAmount,
        remark,
        id
      };
      
    } else {
      this.userIds = this.multipleSelection.map(stu => {
        return stu.userId;
      });
      this.organId = this.multipleSelection[0].organId; //
      // const memberInfo = await getAllMemberFindByOrganIds([this.organId])
      // this.memberRankList = memberInfo.data || []
    }
   
    this.__init();
  },
  methods: {
    formatParentId(id, list, ids = []) {
      for (const item of list) {
        if (item.children) {
          const cIds = this.formatParentId(
            id,
            item.children,
            [...ids, item.id]
          );
          if (cIds.includes(id)) {
            return cIds;
          }
        }
        if (item.id === id) {
          return [...ids, id];
        }
      }
      return ids;
    },
    async __init() {
      try {
        const res = await sysConfigList({ group: "DEFAULT" });
        const paramName = "cloud_price_range";
        res.data.forEach(item => {
          if (item.paramName == paramName) {
            const itemValue = item.paranValue
              ? JSON.parse(item.paranValue)
              : null;
            if (itemValue) {
              this.rulesForm = itemValue;
            }
          }
        });

        // const rankInfo = await getmemberRankOrganizationFeeMapper({
        //   page: 1,
        //   rows: 10,
        //   organId: this.organId
        // });
        // const { rows } = rankInfo.data;
        // this.memberFeeSettingList = rows || [];
        // if (this.memberFeeSettingList.length <= 0) {
        //   this.$bus.$emit("showguide", ["memberList"]);
        // }

        const rankInfo = await getAllMemberFindByOrganIds([this.organId], true)
        this.memberRankList = rankInfo.data || []
        if (this.type == "update") {
          const { memberRankSettingId } = this.multipleSelection;
          this.memberForm.memberRankId = this.formatParentId(memberRankSettingId, this.memberRankList);
          this.$forceUpdate()
        }
      } catch (e) {}
    },
    getMemberList() {
      let money = 0;
      const memberForm = this.memberForm;
      let memberFeeSetting = null
      const memberRankId = this.memberForm.memberRankId || []
      this.memberRankList.forEach(item => {
        if(item.id === memberRankId[0]) {
          item.children.forEach(child => {
            if(child.id === memberRankId[1]) {
              memberFeeSetting = child.memberFeeSetting
            }
          })
        }
      })
      if (memberFeeSetting) {
        switch (memberForm?.period) {
          case "MONTH": {
            money = Number(
              memberFeeSetting.groupPurchaseMonthFee * memberForm.memberNum
            );
            break;
          }
          case "QUARTERLY": {
            money = Number(
              memberFeeSetting.groupPurchaseQuarterlyFee * memberForm.memberNum
            );
            break;
          }
          case "YEAR_HALF": {
            money = Number(
              memberFeeSetting.groupPurchaseHalfYearFee * memberForm.memberNum
            );
            break;
          }
          case "YEAR": {
            money = Number(
              memberFeeSetting.groupPurchaseYearFee * memberForm.memberNum
            );
            break;
          }
        }
      }
      if (memberForm.memberNum && memberForm.period) {
        this.memberForm.actualAmount = money;
      }
    },
    submit() {
      this.$refs.memberForm.validate(async res => {
        console.log(res, this.type, "res");
        if (res) {
          try {
            let rankId = null
            if(this.memberForm.memberRankId && this.memberForm.memberRankId.length > 0) {
              rankId = this.memberForm.memberRankId[this.memberForm.memberRankId.length - 1]
            }
            if (this.type == "update") {
              await update({
                ...this.memberForm,
                memberRankSettingId: rankId,
                organId: this.organId
              });
              this.$message.success("创建学练宝成功");
            } else {
              await add({
                ...this.memberForm,
                memberRankSettingId: rankId,
                userIds: this.userIds,
                organId: this.organId
              });
              this.$message.success("创建学练宝成功");
            }
            this.$emit("close");
            this.$emit("submited");
          } catch (e) {
            console.log(e);
          }
        }
      });
    },
    validateMember(rule, value, callback) {
      const one = Number(value);
      let min = 0;
      let max = 0;
      switch (this.memberForm?.period) {
        case "MONTH": {
          min = Number(this.rulesForm.minMonthFee) * this.memberForm.memberNum;
          max = Number(this.rulesForm.maxMonthFee) * this.memberForm.memberNum;
          break;
        }
        case "QUARTERLY": {
          min =
            Number(this.rulesForm.minQuarterlyFee) * this.memberForm.memberNum;
          max =
            Number(this.rulesForm.maxQuarterlyFee) * this.memberForm.memberNum;
          break;
        }
        case "YEAR_HALF": {
          min =
            Number(this.rulesForm.minHalfYearFee) * this.memberForm.memberNum;
          max =
            Number(this.rulesForm.maxHalfYearFee) * this.memberForm.memberNum;
          break;
        }
        case "YEAR": {
          min = Number(this.rulesForm.minYearFee) * this.memberForm.memberNum;
          max = Number(this.rulesForm.maxYearFee) * this.memberForm.memberNum;
          break;
        }
      }

      if (one >= min && one <= max) {
        return callback();
      }
      return callback(new Error(`定价应在${min}-${max}之间`));
    }
  }
};
</script>
<style lang="scss" scoped>
.title {
  margin-bottom: 30px;
  font-size: 16px;
  color: #000;
}
</style>
