<template>
  <div id="buy-course-modal">
    <el-dialog
      width="800px"
      class="select-class"
      :visible.sync="selectClassModal"
    >
      <div class="select-class__content">
        <div
          class="selection"
          v-if="
            goodsDetail.templateType == 'class' && goodsDetail.goodsType == 1
          "
        >
          <el-select
            class="select"
            v-model="gradeId"
            placeholder="请选择班级"
            size="small"
            @click.native="selectClick(goodsDetail, 'class')"
          >
            <el-option
              v-for="item in gradeList"
              :key="item.gradeId"
              :disabled="
                item.studentNum > 0 && item.studentNum == item.studentUpper
              "
              :label="
                item.classEndTime
                  ? `${item.className} 有效期至：${$tools.timestampToTime(
                      item.classEndTime
                    )}，本班还剩${$tools.GetRTime(
                      item.classEndTime
                    )}天将结束学习`
                  : `${item.className}`
              "
              :value="item.gradeId"
            >
            </el-option>
          </el-select>
        </div>

        <div
          class="selection"
          v-if="
            goodsDetail.templateType == 'apply' && goodsDetail.goodsType == 1
          "
        >
          <el-select
            v-model="educationId"
            placeholder="请选择考期"
            size="small"
            @click.native="selectClick(goodsDetail, 'exam')"
          >
            <el-option
              v-for="item in examineList"
              :key="item.educationId"
              :label="item.examineName"
              :value="item.educationId"
            >
            </el-option>
          </el-select>
          <el-cascader
            size="small"
            :props="props"
            ref="cascader"
            :options="provinceList"
            v-model="examArea"
            @change="areaChange(goodsDetail)"
            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";
export default {
  name: "BuyCourseModal",
  computed: {
    ...mapGetters(["userInfo"]),
  },
  data() {
    return {
      selectClassModal: false,
      goodsDetail: {},
      provinceList: [],
      gradeList: [],
      gradeId: "",
      examineList: [],
      examArea: [],
      educationId: "",
      props: {
        lazy: true,
        lazyLoad: this.lazyLoad,
      },
    };
  },
  mounted() {},
  methods: {
    showModal(item) {
      this.gradeId = ''
      this.gradeList = []
      this.selectClassModal = true;
      this.goodsDetail = item;
    },
    selectClick(goodsDetail, type) {
      if (type == "class") {
        //选择班级
        if (!this.gradeList.length) {
          this.$request
            .goodsGradeList({ goodsId: goodsDetail.goodsId })
            .then((res) => {
              this.gradeList = res.rows;
              if (this.gradeList.length == 0) {
                let item = {
                  className: "系统分班",
                  gradeId: 0,
                };
                this.gradeList.push(item);
              } else {
                let isGradeFull = this.gradeList.every(
                  (item) =>
                    item.studentNum > 0 && item.studentNum == item.studentUpper
                );
                //所有班级都满了
                if (isGradeFull) {
                  let item = {
                    className: "系统分班",
                    gradeId: 0,
                  };
                  this.gradeList.unshift(item);
                }
              }
            });
        }
      } else if (type == "apply") {
        //选择考试地点
      } else if (type == "exam") {
        //选择考期
        this.$request
          .getExamineList({ projectId: goodsDetail.projectId })
          .then((res) => {
            this.examineList = res.rows;
          });
      }
    },
    pay() {
      if (
        this.goodsDetail.templateType == "class" &&
        this.goodsDetail.goodsType == 1
      ) {
        if (!this.gradeId && this.gradeId !== 0) {
          this.$message({
            message: "请选择班级",
            type: "warning",
          });
          return;
        }
      }

      if (
        this.goodsDetail.templateType == "apply" &&
        this.goodsDetail.goodsType == 1
      ) {
        // if (!item.applyAreas.areaName) {
        // 	uni.showModal({
        // 		title: '提示',
        // 		content: '请选择报考地区',
        // 		showCancel: false
        // 	});
        // 	return false;
        // }
        if (!this.educationId) {
          this.$message({
            message: "请选择考期",
            type: "warning",
          });
          return false;
        }
      }

      let selectGoodsList = JSON.parse(JSON.stringify([this.goodsDetail]));
      selectGoodsList.forEach((item) => {
        if (item.goodsType == 1) {
          if (item.templateType == "class") {
            let goodsInputData = {
              type: "class",
              gradeId: this.gradeId,
              gradeJson: JSON.stringify(
                this.gradeList.find((grade) => grade.gradeId == this.gradeId)
              ),
            };
            item.goodsInputData = goodsInputData;
          }
          if (item.templateType == "apply") {
            let goodsInputData = {
              type: "apply",
              applyAreasJson: JSON.stringify(this.applyAreas),
              examDateJson: JSON.stringify(
                this.examineList.find(
                  (exam) => exam.educationId == this.educationId
                )
              ),
            };
            item.goodsInputData = goodsInputData;
          }
        }
      });

      localStorage.setItem("checkGoodsList", JSON.stringify(selectGoodsList));

      this.$router.push({
        path: "/payment",
      });
    },
    /**
     * 获取所有省份
     */
    getProvinceList() {
      this.$request.getProvinceList().then((res) => {
        this.provinceList = res.rows.map((item) => ({
          value: item.areaId,
          label: `${item.areaName}`,
          leaf: false,
        }));
      });
    },
    areaChange() {
      let node = this.$refs["cascader"].getCheckedNodes()[0]; //选中的根节点
      console.log(node);
      this.applyAreas = {
        areaName: node.parent.label,
        areaId: node.parent.value,
        cityId: node.value,
        cityName: node.label,
      };
    },
  },
};
</script>

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