<template>
  <div id="buy-course-modal">
    <el-dialog
      width="800px"
      class="select-class"
      :visible.sync="selectClassModal"
    >
      <div
        class="select-class__content"
        v-for="(it, ik) in copyDetail"
        :key="ik"
      >
        <h3>{{ it.name }}</h3>
        <div class="selection" v-if="it.specialGoods || sign">
          <el-select
            class="select"
            v-model="it.gradeId"
            placeholder="请选择班级"
            size="small"
            @click.native="selectClick(it, 'class')"
          >
            <el-option
              v-for="item in it.gradeList"
              :key="item.gradeId"
              :disabled="
                item.studentNum > 0 && item.studentNum == item.studentUpper
              "
              :label="item.className"
              :value="item.gradeId"
            >
              {{ item.className }}
              <Class-time-tip :classInfo="item"></Class-time-tip>
            </el-option>
          </el-select>
        </div>

        <div
          class="selection"
          v-if="it.templateType == 'apply' && it.goodsType == 1"
        >
          <el-select
            v-model="it.educationId"
            placeholder="请选择考期"
            size="small"
            @click.native="selectClick(it, 'exam')"
          >
            <el-option
              v-for="item in it.examineList"
              :key="item.educationId"
              :label="item.examineName"
              :value="item.educationId"
            >
            </el-option>
          </el-select>
          <el-cascader
            size="small"
            :props="props"
            :ref="'cascader' + ik"
            :options="provinceList"
            v-model="it.area"
            @change="areaChange(it, ik)"
            clearable
            placeholder="请选择报考地区"
          ></el-cascader>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="pay">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import ClassTimeTip from "@/components/common/ClassTimeTip.vue";
export default {
  name: "BuyCourseModal",
  computed: {
    ...mapGetters(["userInfo"])
  },
  data() {
    return {
      selectClassModal: false,
      copyDetail: [], //备份
      provinceList: [],
      gradeList: [],
      gradeMap: new Map(),
      gradeId: "",
      examineList: [],
      examArea: [],
      educationId: "",
      sign: 0, //是否继教七大员商品
      props: {
        lazy: true,
        lazyLoad: this.lazyLoad
      }
    };
  },
  mounted() {},
  methods: {
    showModal(item, sign) {
      this.selectClassModal = true;
      this.getProvinceList();
      if (Array.isArray(item)) {
        this.copyDetail = JSON.parse(JSON.stringify(item));
      } else {
        this.copyDetail = JSON.parse(JSON.stringify([item]));
      }
      this.sign = sign || 0;
      for (let i = 0; i < this.copyDetail.length; i++) {
        this.copyDetail[i].gradeId = "";
        this.copyDetail[i].gradeList = [];
        this.copyDetail[i].educationId = "";
        this.copyDetail[i].examineList = [];
        if (this.copyDetail[i].specialGoods || this.sign) {
          this.selectClick(this.copyDetail[i], "class", true);
        }
        if (
          this.copyDetail[i].templateType == "apply" &&
          this.copyDetail[i].goodsType == 1
        ) {
          this.selectClick(this.copyDetail[i], "exam", true);
        }
      }
    },
    selectClick(goodsDetail, type, status) {
      if (type == "class") {
        //选择班级
        if (!goodsDetail.gradeList.length) {
          this.$request
            .goodsGradeList({ goodsId: goodsDetail.goodsId })
            .then(res => {
              goodsDetail.gradeList = res.rows;
              if (goodsDetail.gradeList.length == 0) {
                let item = {
                  className: "系统分班",
                  gradeId: 0
                };
                goodsDetail.gradeList.push(item);
              } else {
                let isGradeFull = goodsDetail.gradeList.every(
                  item =>
                    item.studentNum > 0 && item.studentNum == item.studentUpper
                );
                //所有班级都满了
                if (isGradeFull) {
                  let item = {
                    className: "系统分班",
                    gradeId: 0
                  };
                  goodsDetail.gradeList.unshift(item);
                }
              }
              if (status) {
                goodsDetail.gradeId = goodsDetail.gradeList[0].gradeId;
              }
              this.$forceUpdate();
            });
        }
      } else if (type == "apply") {
        //选择考试地点
      } else if (type == "exam") {
        //选择考期
        this.$request
          .getExamineList({ projectId: goodsDetail.projectId })
          .then(res => {
            goodsDetail.examineList = res.rows;
            if (status && res.rows.length > 0) {
              goodsDetail.educationId = res.rows[0].educationId;
            }
            this.$forceUpdate();
          });
      }
    },
    async pay() {
      try {
        let itCopyDetail = JSON.parse(JSON.stringify(this.copyDetail));
        itCopyDetail.forEach(i => {
          if (
            (i.specialGoods == 1 || this.sign) &&
            !i.gradeId &&
            i.gradeId !== 0
          ) {
            throw new Error("请选择班级");
          }
          if (i.templateType == "apply" && i.goodsType == 1 && !i.educationId) {
            throw new Error("请选择考期");
          }
          if (i.goodsType == 1) {
            if (i.specialGoods == 1 || this.sign) {
              let goodsInputData = {
                type: "class",
                gradeId: i.gradeId,
                gradeJson: JSON.stringify(
                  i.gradeList.find(grade => grade.gradeId == i.gradeId)
                )
              };
              i.goodsInputData = goodsInputData;
            }
            if (i.templateType == "apply") {
              let goodsInputData = {
                type: "apply",
                applyAreasJson: JSON.stringify(i.applyAreas),
                examDateJson: JSON.stringify(
                  i.examineList.find(exam => exam.educationId == i.educationId)
                )
              };
              i.goodsInputData = goodsInputData;
            }
          }
        });
        localStorage.setItem("checkGoodsList", JSON.stringify(itCopyDetail));
        this.$router.push({
          path: "/payment"
        });
      } catch (error) {
        this.$message({
          message: error,
          type: "warning"
        });
      }
    },
    /**
     * 获取所有省份
     */
    getProvinceList() {
      this.$request.getProvinceList().then(res => {
        this.provinceList = res.rows.map(item => ({
          value: item.areaId,
          label: `${item.areaName}`,
          leaf: false
        }));
      });
    },
    areaChange(row, index) {
      let node = this.$refs["cascader" + index][0].getCheckedNodes()[0]; //选中的根节点
      console.log(node);
      row.applyAreas = {
        areaName: node.parent.label,
        areaId: node.parent.value,
        cityId: node.value,
        cityName: node.label
      };
    },
    lazyLoad(node, resolve) {
      const { level } = node;
      if (level == 0) {
        // this.$request.getProvinceList().then((res) => {
        //   const nodes = res.rows.map((item) => ({
        //     value: item.areaId,
        //     label: `${item.areaName}`,
        //     leaf: level >= 1,
        //   }));
        //   resolve(nodes);
        // });
      } else if (level == 1) {
        this.$request.getCityList({ parentId: node.value }).then(res => {
          const nodes = res.rows.map(item => ({
            value: item.areaId,
            label: `${item.areaName}`,
            leaf: level >= 1
          }));
          resolve(nodes);
        });
      }
    }
  },
  computed: {
    text() {
      let str = "";

      return str;
    }
  },
  components: {
    ClassTimeTip
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.select-class {
  &__content {
    .selection {
      .el-select {
        width: 100%;
      }
    }
  }
}
</style>
