<template>
  <div id="keyTestSites">
    <search-box :formList="formList" @search="search" @init="init" />
    <table-list
      :tableSets="tableSet"
      :tableData="tableData"
      :navText="navText"
      @addClick="addClick"
      :loading="loading"
    >
      <template slot="btn" slot-scope="props">
        <el-button type="text" @click="infoMessage(props.scope.row)"
          >详情</el-button
        >
        <el-button type="text" @click="modify(props.scope.row)">修改</el-button>
        <el-button type="text" @click="del(props.scope.row)">删除</el-button>
      </template>
    </table-list>
    <pagination
      :total="total"
      :pageSize="pageSize"
      :currentPage="currentPage"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    />
    <el-dialog
      :visible.sync="dialogBox"
      width="920px"
      :show-close="false"
      :destroy-on-close="true"
      :fullscreen="fullscreen"
      :close-on-click-modal="false"
    >
      <div slot="title" class="hearders">
        <div class="leftTitle">
          {{ statusPop === 1 ? "添加" : statusPop === 0 ? "修改" : "详情" }}
        </div>
        <div class="rightBoxs">
          <img
            src="@/assets/images/Max@2x.png"
            alt=""
            @click="fullscreen = !fullscreen"
          />
          <img src="@/assets/images/Close@2x.png" alt="" @click="closeBefore" />
        </div>
      </div>
      <el-row class="contentBox" :span="24">
        <el-col :span="24">
          <el-col :span="12">
            <el-col :span="24">
              <header>重点考点分类</header>
              <el-cascader
                style="width: 100%"
                v-model="poppleData.categoryId"
                :options="optionsTion"
                :size="'medium'"
                :disabled="statusPop === 2"
                clearable
                :props="{
                  label: 'categoryName',
                  value: 'categoryId',
                  checkStrictly: true,
                  emitPath: false,
                }"
              ></el-cascader>
            </el-col>
            <el-col :span="24">
              <header>重点考点名称：</header>
              <el-input
                :disabled="statusPop === 2"
                placeholder="请输入重点考点名称："
                v-model="poppleData.name"
              />
            </el-col>
            <el-col :span="24">
              <header>主讲名师</header>
              <el-select
                :disabled="statusPop === 2"
                style="width: 100%"
                multiple
                v-model="poppleData.teacherIds"
                placeholder="请选择主讲名师："
                @change="changeTeacherlist"
              >
                <el-option
                  v-for="item in optionsTeach"
                  :key="item.teacherId"
                  :label="item.teacherName"
                  :value="item.teacherId"
                >
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="24">
              <header>价格：</header>
              <el-input
                placeholder="请输入价格："
                :disabled="statusPop === 2"
                v-model="poppleData.price"
              >
                <template slot="append">元</template>
              </el-input>
            </el-col>
            <el-col :span="12">
              <header>排序：</header>
              <el-input-number
                style="width: 150px"
                placeholder="请输入排序："
                :disabled="statusPop === 2"
                v-model="poppleData.sort"
                controls-position="right"
                :min="0"
                :max="999"
              ></el-input-number>
            </el-col>
            <el-col :span="12">
              <header>是否启用：</header>
              <el-radio-group
                v-model="poppleData.status"
                :disabled="statusPop === 2"
              >
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-col>
          </el-col>
          <el-col :span="12">
            <el-col :span="24">
              <header>重点考点封面：</header>
              <div class="imgBox">
                <label class="imgLabel" for="inputs">
                  <div class="msPhoto" v-if="poppleData.coverUrl">
                    <img
                      :src="$methodsTools.splitImgHost(poppleData.coverUrl)"
                      alt="图片加载失败"
                    />
                  </div>
                  <div class="imgbbx" v-else>
                    <p style="margin-top: 49px">
                      点击添加或将图片拖拽到这里上传
                    </p>
                    <i class="el-icon-plus"></i>
                    <p style="margin-bottom: 37px">
                      图片格式：.jpg/.png/jpeg/bmp
                    </p>
                  </div>
                  <input
                    :disabled="statusPop === 2"
                    id="inputs"
                    type="file"
                    ref="file"
                    style="display: none"
                    @change="getImgFile"
                  />
                </label>
                <p style="color: #999999">请上传比例为16:9且小于2m的图片</p>
              </div>
            </el-col>
            <el-col :span="24">
              <header>重点考点文件：</header>
              <div class="imgBox">
                <label
                  class="imgLabel"
                  for="inputsFile"
                  style="margin-bottom: 5px"
                >
                  <div class="msPhoto" v-if="poppleData.fileUrls">
                    <img
                      style="width: 150px; height: 150px"
                      src="http://iconfont.alicdn.com/t/657bb17a-f0f1-4dc2-9727-45df2b1ac4d9.png"
                      alt="文件加载失败"
                    />
                  </div>
                  <div class="imgbbx" v-else>
                    <p style="margin-top: 49px">
                      点击添加或将文件拖拽到这里上传
                    </p>
                    <i class="el-icon-plus"></i>
                    <p style="margin-bottom: 37px">支持扩展名：pdf</p>
                  </div>
                  <input
                    :disabled="statusPop === 2"
                    id="inputsFile"
                    type="file"
                    ref="filePdf"
                    style="display: none"
                    @change="getImgFilePDF"
                  />
                </label>
                <p
                  style="color: #999999"
                  v-if="statusPop === 2 && poppleData.fileUrls"
                >
                  <el-button type="success" size="mini"
                    ><a
                      style="color: #fff"
                      :href="poppleData.fileUrls"
                      target="_blank"
                      >预览PDF</a
                    ></el-button
                  >
                </p>
              </div>
            </el-col>
          </el-col>
          <el-col :span="24">
            <el-col :span="24">
              <header>重点考点简介：</header>
              <div
                style="
                  max-height: 300px;
                  overflow-y: auto;
                  border: 1px solid #e2e2e2;
                  border-radius: 8px;
                  padding: 13px;
                "
                v-if="statusPop === 2"
                v-html="poppleData.introduction"
              ></div>
              <editor
                v-else
                v-model="poppleData.introduction"
                :min-height="100"
                :max-height="300"
                :uploadStatus="uploadStatus"
              /> </el-col
          ></el-col>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeBefore">取 消</el-button>
        <el-button type="primary" @click="submitTabel">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import searchBox from "@/components/searchBox";
import tableList from "@/components/tableList";
import pagination from "@/components/pagination";
import Editor from "@/components/Editor";
export default {
  components: { searchBox, tableList, pagination, Editor },
  data() {
    return {
      uploadStatus: 2, //富文本组件传值
      loading: false, //当前表单加载是否加载动画
      navText: {
        title: "重点考点合计",
        index: 0,
        ch: "个",
        num: true,
        choice: true,
        backFatherBtn: {
          status: false,
          title: "未定义",
        },
      },
      tableSet: [
        {
          label: "重点考点名称",
          prop: "name",
          hidden: true,
          width: "180px",
        },
        {
          label: "类型",
          prop: "categoryName",
          hidden: true,
          width: "180px",
        },
        {
          label: "排序",
          prop: "sort",
          hidden: true,
        },
        {
          label: "启用状态",
          prop: "status",
          hidden: true,
          scope: "status",
        },
      ], //表头信息
      tableData: [], //表单数据
      total: 0, //一共多少条
      pageSize: 10, //每页多少条数据
      currentPage: 1, //当前页码
      formList: [
        {
          label: "重点考点名称",
          prop: "name",
          placeholder: "输入重点考点名称",
        },
        {
          label: "启用状态",
          prop: "status",
          scope: "select",
          placeholder: "选择启用状态",
          options: [
            {
              label: "启用",
              value: 1,
            },
            {
              label: "关闭",
              value: 0,
            },
          ],
        },
        {
          label: "重点考点类型",
          prop: "categoryId",
          scope: "cascader",
          placeholder: "选择重点考点类型",
          options: [],
          props: {
            label: "categoryName",
            value: "categoryId",
          },
        },
      ], //搜索栏
      optionsTion: [],
      optionsTeach: [],
      poppleData: {},
      fullscreen: false,
      fullscreenChild: false,
      dialogBox: false,
      innerVisible: false,
      statusPop: 0,
      beif: "", //备份数据
      beifpdf: "", //备份pdf
      int: -1,
      treeObj: {},
      priceTest: /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/,
    };
  },
  computed: {
    numTime: function () {
      return function (res) {
        return Number(res / 3600).toFixed(2);
      };
    },
  },
  mounted() {
    this.search();
    this.initCascader();
    this.initTeacherList();
  },
  methods: {
    changeTeacherlist(options) {
      console.log(this.poppleData);
    },
    // 初始化教师列表
    initTeacherList() {
      var data = {
        status: "0,1",
      };
      this.$api.inquireCourseTeacher(data).then((res) => {
        console.log(res);
        this.optionsTeach = res.rows;
      });
    },
    //级联选择器数据
    initCascader() {
      this.$api
        .inquireProfessionClassification()
        .then((res) => {
          this.arrayChangeType(res.rows);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 接口数据转换级联类型
    arrayChangeType(options) {
      let result = [];
      if (!Array.isArray(options)) {
        return result;
      }
      options.forEach((item) => {
        delete item.children;
      });
      let map = {};
      options.forEach((item) => {
        map[item.categoryId] = item;
      });
      options.forEach((item) => {
        let parent = map[item.pid];
        if (parent) {
          (parent.children || (parent.children = [])).push(item);
        } else {
          result.push(item);
        }
      });
      result = result.sort(this.sortBy("sort", true));
      result.forEach((item, index) => {
        if (item.children) {
          item.children.sort(this.sortBy("sort", true));
        }
      });
      this.formList.forEach((item, index) => {
        if (item.prop === "categoryId") {
          item.options = result;
          this.optionsTion = result;
        }
      });
      return result;
    },
    sortBy(attr, rev) {
      //第二个参数没有传递 默认升序排列
      if (rev == undefined) {
        rev = 1;
      } else {
        rev = rev ? 1 : -1;
      }

      return function (a, b) {
        a = a[attr];
        b = b[attr];
        if (a < b) {
          return rev * -1;
        }
        if (a > b) {
          return rev * 1;
        }
        return 0;
      };
    },
    getImgFile() {
      var self = this;
      var file = this.$refs.file.files[0];
      if (file === undefined) {
        self.$set(self.poppleData, "coverUrl", "");
        return;
      }
      if (file.size > 2 * 1024 * 1024) {
        this.$message.error("图片不得大于2MB");
        return;
      }
      var type = this.$refs.file.value.toLowerCase().split(".").splice(-1);
      if (
        type[0] != "jpg" &&
        type[0] != "png" &&
        type[0] != "jpeg" &&
        type[0] != "bmp"
      ) {
        this.$message.error("上传格式需为：.jpg/.png/.jpeg/bmp");
        this.$refs.file.value = "";
        return;
      }
      var reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = function (ev) {
        self.$set(self.poppleData, "coverUrl", ev.target.result);
      };
    },
    getImgFilePDF() {
      var self = this;
      var file = this.$refs.filePdf.files[0];
      if (file === undefined) {
        self.$set(self.poppleData, "fileUrls", "");
        return;
      }
      var type = this.$refs.filePdf.value.toLowerCase().split(".").splice(-1);
      if (type[0] != "pdf") {
        this.$message.error("上传格式需为：pdf");
        this.$refs.filePdf.value = "";
        return;
      }
      var reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = function (ev) {
        console.log(ev);
        self.$set(self.poppleData, "fileUrls", ev.target.result);
      };
    },
    // 详情
    infoMessage(options) {
      var data = options.fileId;
      this.$api.obtainExamNote(data).then((res) => {
        this.poppleData = res.data;
        this.beif = res.data.coverUrl;
        this.beifpdf = res.data.beifpdf;
        this.poppleData.teacherIds = res.data.teacherIds.split(",").map(Number);
      });
      this.statusPop = 2;
      this.dialogBox = true;
    },
    //确定提交
    async submitTabel() {
      if (this.statusPop === 2) {
        this.dialogBox = false;
        return;
      }
      var self = this;
      if (
        this.poppleData.categoryId === undefined ||
        this.poppleData.categoryId === null
      ) {
        this.$message.error("请选择重点考点分类");
        return;
      }
      if (!this.poppleData.name) {
        this.$message.error("请输入重点考点名称");
        return;
      }
      if (
        this.poppleData.teacherIds === undefined ||
        this.poppleData.teacherIds.length === 0
      ) {
        this.$message.error("请选择主讲名师");
        return;
      }
      if (this.poppleData.price === undefined) {
        this.$message.error("请输入价格");
        return;
      }
      if (!this.priceTest.test(this.poppleData.price)) {
        this.$message.error("请输入正确价格");
        this.poppleData.price = "";
        return;
      }
      if (this.poppleData.sort === undefined) {
        this.$message.error("请输入排序");
        return;
      }
      if (!this.poppleData.introduction) {
        this.$message.error("请输入重点考点简介");
        return;
      }
      if (this.poppleData.status === undefined) {
        this.$message.error("请选择是否启用该重点考点");
        return;
      }
      if (!this.poppleData.coverUrl || this.poppleData.coverUrl.length === 0) {
        this.$message.error("请上传重点考点封面");
        return;
      }
      if (!this.poppleData.fileUrls || this.poppleData.fileUrls.length === 0) {
        this.$message.error("请上传重点考点PDF文件");
        return;
      }
      var data = {
        categoryId: this.poppleData.categoryId,
        name: this.poppleData.name,
        introduction: this.poppleData.introduction,
        price: this.poppleData.price,
        status: this.poppleData.status,
        teacherIds: this.poppleData.teacherIds.join(","),
        sort: this.poppleData.sort,
      };
      if (this.statusPop === 1) {
        const awtimg = await this.imgUpload(2);
        data.coverUrl = this.poppleData.coverUrl;
        data.fileUrls = this.poppleData.fileUrls;
        this.$api
          .addExamNote(data)
          .then((res) => {
            this.$message.success("新增成功!");
            this.search();
            this.dialogBox = false;
          })
          .catch((err) => {
            this.$message.error(err);
          });
      } else if (this.statusPop === 0) {
        data.fileId = this.poppleData.fileId;
        if (
          this.poppleData.coverUrl === this.beif &&
          this.poppleData.coverUrl.length !== 0 &&
          this.poppleData.fileUrls === this.beifpdf &&
          this.poppleData.fileUrls.length !== 0
        ) {
          this.submitFun(data);
        } else {
          if (this.poppleData.coverUrl !== this.beif) {
            const awtimg = await this.imgUpload(2);
            data.coverUrl = this.poppleData.coverUrl;
          }
          if (this.poppleData.fileUrls !== this.beifpdf) {
            console.log(this.poppleData.fileUrls);
            console.log(this.beifpdf);

            const awtimg = await this.pdfUpload(6);
            data.fileUrls = this.poppleData.fileUrls;
          }
          this.submitFun(data);
        }
      }
    },
    submitFun(data) {
      this.$api
        .editExamNote(data)
        .then((res) => {
          this.$message.success("修改成功!");
          this.dialogBox = false;
          this.search();
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    imgUpload(int) {
      var self = this;
      return new Promise((resolve, reject) => {
        this.$upload
          .upload(this.$refs.file.files[0], int)
          .then((res) => {
            self.poppleData.coverUrl = res;
            resolve();
          })
          .catch((err) => {
            self.$message.error("图片上传错误");
          });
      });
    },
    pdfUpload(int) {
      var self = this;
      return new Promise((resolve, reject) => {
        this.$upload
          .upload(this.$refs.filePdf.files[0], int)
          .then((res) => {
            self.poppleData.fileUrls = res;
            resolve();
          })
          .catch((err) => {
            self.$message.error("文件上传错误");
          });
      });
    },
    //添加
    addClick() {
      this.poppleData = {};
      this.statusPop = 1;
      this.dialogBox = true;
    },
    // 修改
    modify(options) {
      var data = options.fileId;
      this.$api.obtainExamNote(data).then((res) => {
        this.poppleData = res.data;
        this.beif = res.data.coverUrl;
        this.beifpdf = res.data.fileUrls;
        this.poppleData.teacherIds = res.data.teacherIds.split(",").map(Number);
      });
      this.statusPop = 0;
      this.dialogBox = true;
    },
    //删除
    del(options) {
      var self = this;
      this.$confirm("此操作将删除该考试重点, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log(options);
          var data = {
            categoryId: options.categoryId,
            fileId: options.fileId,
            name: options.name,
            sort: options.sort,
            introduction: options.introduction,
            teacherIds: options.teacherIds,
            status: -1,
          };
          this.$api
            .editExamNote(data)
            .then(() => {
              this.$message.success("删除成功!");
              this.search();
            })
            .catch((err) => {
              this.$message.error("删除失败：" + err);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    sortBy(attr, rev) {
      //第二个参数没有传递 默认升序排列
      if (rev == undefined) {
        rev = 1;
      } else {
        rev = rev ? 1 : -1;
      }

      return function (a, b) {
        a = a[attr];
        b = b[attr];
        if (a < b) {
          return rev * -1;
        }
        if (a > b) {
          return rev * 1;
        }
        return 0;
      };
    },
    search(v) {
      if (v === undefined) {
        v = {
          status: "0,1",
          pageSize: this.pageSize,
          pageNum: this.currentPage,
        };
      }
      var data = {
        name: v.name,
        categoryId: v.categoryId,
        status: v.status === undefined ? "0,1" : v.status,
        pageSize: this.pageSize,
        pageNum: this.currentPage,
      };
      this.loading = true;
      this.$api
        .inquireExamNote(data)
        .then((res) => {
          res.rows.sort(this.sortBy("sort", true));
          this.tableData = res.rows;
          this.total = res.total;
          this.navText.index = res.total;
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    init() {
      this.search();
    },
    //窗口关闭
    closeBefore() {
      this.dialogBox = false;
      this.fullscreen = false;
      this.poppleData = {};
    },
    handleSizeChange(v) {
      this.pageSize = v;
      this.currentPage = 1;
      this.search();
    },
    handleCurrentChange(v) {
      this.currentPage = v;
      this.search();
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.el-button {
  border-radius: 8px;
}
/deep/.el-dialog {
  border-radius: 8px;
  .el-dialog__header {
    padding: 0;
    .hearders {
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0px 18px 0px 20px;
      border-bottom: 1px solid #e2e2e2;
      .leftTitle {
        font-size: 14px;
        font-weight: bold;
        color: #2f4378;
      }
      .rightBoxs {
        display: flex;
        align-items: center;
        img {
          width: 14px;
          height: 14px;
          margin-left: 13px;
          cursor: pointer;
        }
      }
    }
  }
  .el-dialog__body {
    padding: 0;
    .contentBox {
      padding: 20px 20px 5px;
      .el-col {
        padding: 0px 20px;
        margin-bottom: 30px;
        header {
          margin-bottom: 6px;
          color: #2f4378;
          font-size: 14px;
        }
      }
      .juscon {
        float: none;
        width: 50%;
        margin: 0 auto;
      }
    }
  }
  .el-dialog__footer {
    padding: 0;
    .dialog-footer {
      padding: 0px 40px;
      height: 70px;
      border-top: 1px solid #e2e2e2;
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
  }
}
.imgBox {
  width: 100%;
  // height: 210px;
  border: 1px solid #e2e2e2;
  border-radius: 8px;
  padding: 8px 8px 3px;
  display: flex;
  flex-direction: column;
  align-items: center;
  .imgLabel {
    flex: 1;
    width: 100%;
    border: 1px dotted #e2e2e2;
    color: #999;
    font-size: 14px;
    cursor: pointer;
    border-radius: 8px;
    .msPhoto {
      display: flex;
      justify-content: center;
      align-items: center;
      max-width: 100%;
      max-height: 270px;
      img {
        max-width: 100%;
        max-height: 270px;
      }
    }
    .imgbbx {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
      i {
        font-weight: bold;
        margin: 14px 0;
        font-size: 24px;
      }
    }
  }
  p {
    margin: 5px 0px;
  }
}
.el-radio-group {
  height: 40px;
  display: flex;
  align-items: center;
}
</style>
