<template>
  <div id="handoutListEdit">
    <div class="boxWidth">
      <el-form
        label-position="right"
        label-width="120px"
        :model="listData"
        :rules="rules"
        ref="listData"
      >
        <el-form-item label="适用业务层级">
          <el-select
            v-model="eduType"
            placeholder="请选择教育类型"
            @change="changeEduType"
          >
            <el-option
              v-for="(item, index) in eduTypeOptions"
              :key="index"
              :label="item.educationName"
              :value="item.id"
            >
            </el-option>
          </el-select>
          <el-select
            v-model="courType"
            placeholder="请选择业务层次"
            @change="changecourseType"
          >
            <el-option
              v-for="(item, index) in newCourTypeOptions"
              :key="index"
              :label="item.businessName"
              :value="item.id"
            >
            </el-option>
          </el-select>
          <el-popover
            ref="popovers"
            placement="bottom"
            trigger="click"
            @show="showHandle"
            @hide="hideHandle"
            :disabled="courType ? false : true"
          >
            <el-checkbox-group v-model="sujectArray" class="checkboxSty">
              <el-checkbox
                v-for="(item, index) in newSujectOption"
                :label="item.newId"
                :key="index"
                >{{ item.subjectName }}</el-checkbox
              >
            </el-checkbox-group>
            <div style="display: block; text-align: center; margin-top: 10px">
              <el-button size="mini" type="primary" @click="submitSujectArray"
                >确定</el-button
              >
            </div>
            <el-button slot="reference" style="margin-left: 12px"
              >请选择科目</el-button
            >
          </el-popover>
        </el-form-item>
        <el-form-item label="已选业务层级">
          <div :class="changeHeight ? 'ach' : 'clh'">
            <div
              v-for="(item, index) in newSujectApis"
              :key="index"
              class="listBoxStys"
            >
              {{
                item.educationName +
                " - " +
                item.projectName +
                " - " +
                item.businessName +
                " - " +
                item.subjectName
              }}
              <i class="el-icon-error closeIcons" @click="closeType(index)"></i>
            </div>
          </div>
          <el-button
            size="mini"
            v-if="newSujectApis.length > 1"
            @click="changeType"
            >{{ changeHeight ? "展开" : "关闭" }}</el-button
          >
          <span v-if="newSujectApis.length === 0">未选项目类型</span>
        </el-form-item>
        <el-form-item label="讲义标题" prop="handoutsName">
          <el-input v-model="listData.handoutsName"></el-input>
        </el-form-item>
        <el-form-item label="讲义文件">
          <div class="imgBoxins">
            <div v-if="handoutsUrlLive" class="dis_stsy">
              <a
                :href="
                  blob ? blob : $methodsTools.splitImgHost(listData.handoutsUrl)
                "
                target="_blank"
              >
                <img src="@/assets/images/pdf@3x.png" alt="" />
              </a>
              <p>{{ listData.urlName }}</p>
              <el-button
                type="danger"
                size="mini"
                class="margin-top: 20px;"
                @click="clearImgs"
                >删除</el-button
              >
            </div>
            <div class="posimg" v-else>
              <label for="uplose">
                <i class="el-icon-circle-plus-outline iconStsz"></i
              ></label>
              <input
                ref="file"
                type="file"
                style="display: none"
                id="uplose"
                @change="getImgFile"
              />
              <p>注：只能上传PDF文件，且不超过20MB</p>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="是否发布" prop="status">
          <el-radio-group v-model="listData.status">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button @click="backPage">取消</el-button>
          <el-button type="primary" @click="submit('listData')">确定</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      blob: "", //pdf本地路径
      handoutsUrlLive: false, //是否存在PDF
      changeHeight: true,
      //   弹窗数据
      listData: {
        handoutsUrl: undefined,
        urlName: undefined,
      },
      bfImg: "",
      eduTypeOptions: [], //教育类型数据
      projectTypeOptions: [], //项目类型数据
      courTypeOptions: [], //业务层次数据
      newCourTypeOptions: [], //当前业务层次数据
      sujectOption: [], //科目数据
      newSujectOption: [], //当前科目数据数据
      eduType: "", //当前选中教育类型
      courType: "", //当前选中业务层次
      sujectApis: [], //当前存在的科目
      newSujectApis: [],
      sujectArray: [], //选中的科目
      //表单验证
      rules: {
        handoutsName: [
          { required: true, message: "请输入讲义标题", trigger: "blur" },
        ],
        status: [
          { required: true, message: "请选择是否发布", trigger: "change" },
        ],
      },
    };
  },
  watch: {
    sujectApis: {
      immediate: true,
      handler(newName, oldName) {
        this.changeTypes();
      },
    },
    "listData.handoutsUrl": {
      handler(newValue, oldValue) {
        if (newValue) {
          this.handoutsUrlLive = true;
        } else {
          this.handoutsUrlLive = false;
        }
      },
    },
  },
  mounted() {
    this.getDict();
    this.search();
  },
  methods: {
    search() {
      this.$api.obtainCourseHandouts(this.$route.query.id).then((res) => {
        this.bfImg = res.data.handoutsUrl;
        this.listData = res.data;
        if (res.data.courseHandoutsBusinessVo) {
          var arrays = [];
          res.data.courseHandoutsBusinessVo.map((item) => {
            arrays.push(item.businessId + "-" + item.subjectId);
          });
          this.sujectApis = arrays;
        }
      });
    },
    clearImgs() {
      this.listData.handoutsUrl = undefined;
      this.listData.urlName = undefined;
    },
    changeTypes() {
      var self = this;
      var arrays = [];
      this.sujectApis.map((item, index) => {
        this.courTypeOptions.map((items) => {
          if (items.id === item.split("-").map(Number)[0]) {
            var obj = {
              educationId: items.educationId,
              educationName: items.educationName,
              projectId: items.projectId,
              projectName: items.projectName,
              businessId: items.id,
              businessName: items.businessName,
            };
            self.sujectOption.map((i) => {
              if (
                i.id === item.split("-").map(Number)[1] &&
                i.courseArrays.indexOf(items.projectId) !== -1
              ) {
                obj.subjectName = i.subjectName;
                obj.subjectId = i.id;
              }
            });
            arrays.push(obj);
          }
        });
      });
      this.newSujectApis = arrays;
    },
    changeType() {
      this.changeHeight = !this.changeHeight;
    },
    submitSujectArray() {
      var self = this;
      this.sujectApis = this.sujectApis.filter((item, index) => {
        return item.split("-").map(Number)[0] !== Number(self.courType);
      });
      for (let i = 0; i < this.sujectArray.length; i++) {
        this.sujectApis.push(this.sujectArray[i]);
      }
      this.$refs.popovers.doClose();
    },
    showHandle() {
      var array = [];
      for (let i = 0; i < this.sujectApis.length; i++) {
        if (
          this.sujectApis[i].split("-").map(Number)[0] === Number(this.courType)
        ) {
          array.push(this.sujectApis[i]);
        }
      }
      this.sujectArray = array;
      this.newSujectOption.map((item) => {
        item.newId = this.courType + "-" + item.id;
      });
    },
    hideHandle() {},
    getDict() {
      this.$api.inquireCourseEducationType({ status: 1 }).then((res) => {
        this.eduTypeOptions = res.rows;
      });
      this.$api.inquireCourseProjectType({ status: 1 }).then((res) => {
        this.projectTypeOptions = res.rows;
      });
      this.$api.inquirebusinessList({ status: 1 }).then((res) => {
        this.courTypeOptions = res.rows;
        this.newCourTypeOptions = res.rows;
      });
      this.$api.inquireCourseSubject({ status: 1 }).then((res) => {
        res.rows.map((item, index) => {
          var array = [];
          item.courseProjectTypes.map((items, indexs) => {
            array.push(items.id);
          });
          item.courseArrays = array;
        });
        this.sujectOption = res.rows;
      });
      this.$api.inquireCourseStreaming({ status: 1 }).then((res) => {
        var arrays = [];
        var newarrays1 = [];
        var newarrays2 = [];
        res.rows.map((item) => {
          if (item.streamingType === 1) {
            arrays.push(item);
          }
          if (item.streamingType === 2) {
            newarrays1.push(item);
          }
          if (item.streamingType === 3) {
            newarrays2.push(item);
          }
        });
        this.newLiveUrl = arrays;
        this.newSteamUrl1 = newarrays1;
        this.newSteamUrl2 = newarrays2;
      });
    },
    changeEduType() {
      if (!(this.courType === undefined || this.courType === "")) {
        this.courType = "";
      }
      var arrays = [];
      this.courTypeOptions.map((item) => {
        if (item.educationId === this.eduType) {
          arrays.push(item);
        }
      });
      this.newCourTypeOptions = arrays;
    },
    changecourseType() {
      this.newCourTypeOptions.map((item, index) => {
        if (item.id === this.courType) {
          this.eduType = item.educationId;
          var array = [];
          this.sujectOption.map((items, indexs) => {
            if (items.courseArrays.indexOf(item.projectId) !== -1) {
              array.push(items);
            }
          });
          this.newSujectOption = array;
        }
      });
      var arrays = [];
      this.courTypeOptions.map((item) => {
        if (item.educationId === this.eduType) {
          arrays.push(item);
        }
      });
      this.newCourTypeOptions = arrays;
      this.$refs.popovers.doClose();
    },
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.rulesTableSumbit();
        } else {
          return false;
        }
      });
    },
    async rulesTableSumbit() {
      var dataInfos = {
        handoutsId: this.$route.query.id,
        courseHandoutsBusinessAddBos: this.newSujectApis,
        handoutsName: this.listData.handoutsName,
        status: this.listData.status,
      };
      if (this.listData.handoutsUrl !== this.bfImg) {
        if (this.listData.handoutsUrl) {
          const urls = await this.$upload.upload(this.listData.handoutsUrl, 6);
          dataInfos.handoutsUrl = urls;
          dataInfos.urlName = this.listData.urlName;
        } else {
          dataInfos.handoutsUrl = "";
          dataInfos.urlName = "";
        }
      }
      this.$api.editCourseHandouts(dataInfos).then((res) => {
        this.$message.success("修改成功");
        setTimeout(() => {
          this.$router.go(-1);
        }, 500);
      });
    },
    backPage() {
      this.$router.go(-1);
    },
    closeType(index) {
      this.sujectApis.splice(index, 1);
    },
    getImgFile() {
      var self = this;
      var file = self.$refs.file.files[0];
      if (file === undefined) {
        self.$set(self.listData, "handoutsUrl", "");
        return;
      }
      if (file.size > 20 * 1024 * 1024) {
        self.$message.error("pdf文件不得大于20MB");
        return;
      }
      var type = self.$refs.file.value.toLowerCase().split(".").splice(-1);
      if (type[0] != "pdf") {
        self.$message.error("上传格式需为：.pdf");
        self.$refs.file.value = "";
        return;
      }
      const imgURL = window.URL.createObjectURL(file);
      self.blob = imgURL;
      self.listData.handoutsUrl = file;
      self.listData.urlName = file.name;
    },
  },
};
</script>

<style lang="less" scoped>
.boxWidth {
  width: 700px;
}
.numInputs {
  width: 150px;
}
.checkboxSty {
  max-height: 210px;
  overflow: auto;
  display: flex;
  flex-direction: column;
}
.listBoxStys {
  flex-shrink: 0;
  padding: 0px 10px;
  border-radius: 8px;
  border: 1px solid #eee;
  margin-right: 10px;
  margin-bottom: 6px;
}
.closeIcons {
  color: red;
  cursor: pointer;
  margin-left: 6px;
}
.ach {
  display: flex;
  align-items: center;
  overflow: hidden;
}
.clh {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
.imgBoxins {
  width: 375px;
  text-align: center;
  img {
    height: 100%;
    width: 60px;
    cursor: pointer;
    transition: all 0.3s;
    &:hover {
      transform: scale(1.05);
    }
  }
  .dis_stsy {
    display: flex;
    align-items: flex-end;
  }
}
.iconStsz {
  font-size: 40px;
  color: #67c23a;
  cursor: pointer;
}
</style>
