<template>
  <div>
    <back-box>
      <template slot="title">
        <span>备题组卷</span>
      </template>
      <template slot="btns">
        <el-tooltip v-if="!code && gdClass" effect="dark" content="已归档试卷" placement="bottom">
          <el-button type="primary" icon="fa fa-archive" size="mini" plain circle @click="toArchiving"></el-button>
        </el-tooltip>
      </template>
    </back-box>
    <div class="examinationPaper-type">
      <el-button-group>
        <el-button size="large" :type="query.type == 1 ? 'primary' : 'default'" @click="changPaperType(1)">备题</el-button>
        <el-button size="large" :type="query.type == 2 ? 'primary' : 'default'" @click="changPaperType(2)">组卷</el-button>
      </el-button-group>

      <p>
        <el-button v-if="query.type == 1" type="primary" size="mini" icon="el-icon-plus" round @click="diaUp = true">
          导入课件</el-button>

        <el-dropdown v-if="query.type == 2" trigger="click" @command="handleAdd">
          <el-button type="primary" size="mini" icon="el-icon-plus" round>添加试卷</el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item :command="1">导入试卷</el-dropdown-item>
            <el-dropdown-item :command="2">手动创建</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </p>
    </div>
    <div class="answer-header">
      <div class="sel-box">
        <el-select class="sel" v-model="query.classId" placeholder="选择班级" @change="changClazz">
          <el-option v-for="item in classList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <el-select class="sel" v-model="query.subjectName" placeholder="选择科目" @change="getData(false)">
          <el-option v-for="item in subjectList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>

        <el-input placeholder="试卷名称" v-model="query.title" class="input-with-select" @keyup.enter.native="getData(true)">
          <el-button slot="append" icon="el-icon-search" @click="getData(true)"></el-button>
        </el-input>
      </div>
    </div>
    <p class="tips" v-show="archivedTotal">
      <span>回收站内已有{{ archivedTotal }}份答题卡,</span>
      <router-link to="/examinationPaperRecycle">点击查看&gt;&gt;</router-link>
    </p>
    <div class="content">
      <p class="tab-box">
        <span :class="['tab-s', query.share == 0 ? 'active' : '']" @click="changShare(0)">我自编的 ({{ totalCount.my
        }})</span>
        <span :class="['tab-s', query.share == 1 ? 'active' : '']" @click="changShare(1)">年级共享的 ({{ totalCount.share
        }})</span>
      </p>
      <ul v-if="tableData && tableData.length" v-loading="loading">
        <li class="item" v-for="item in tableData" :key="item.id">
          <div class="pic-box">
            <p class="i-box"><i class="fa fa-map-o"></i></p>
            <p class="ids">{{ item.id }}</p>
          </div>
          <div class="info">
            <p class="title">
              {{ item.title }}
              <span class="label" v-if="!!item.tag">{{ item.tag }}</span>
            </p>
            <p class="num">
              总题数：{{ item.questionNum }}
              <em class="s-line">|</em>
              预计时长：{{ item.examsDuration }}
              <em class="s-line">|</em>
              <template v-if="role != 'ROLE_PERSONAL'">
                授课端同步：
                <span class="clazz" v-for="(clazzChild, indexs) in item.classList" :key="clazzChild.classId"
                  :class="clazzChild.keepStatus == 1 ? 'active' : ''">{{
                    `${clazzChild.className}${indexs != item.classList.length - 1 ? "、" : ""
                      }`
                  }}
                  <i v-if="clazzChild.keepStatus == 1" class="el-icon-success"></i></span>
                <el-tooltip effect="dark" content="刷新同步状态" placement="right">
                  <i class="icon-refresh el-icon-refresh" @click="refreshStic"></i>
                </el-tooltip>
              </template>
            </p>
            <p class="person">
              {{ item.realName }}<em class="s-line">|</em><span class="date">{{ item.modifiedTime }}</span>
            </p>
          </div>
          <div class="btn-box">
            <el-tooltip effect="dark" content="修改答案" placement="bottom">
              <el-button class="edit" type="primary" size="mini" circle icon="el-icon-edit"
                @click="toEdit(item)"></el-button>
            </el-tooltip>
            <el-dropdown trigger="click" @command="handleDropdownClick($event, item)">
              <el-button type="info" size="mini" circle icon="el-icon-more"></el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="1"
                  v-if="userName == item.realName && role != 'ROLE_PERSONAL'">修改分享范围</el-dropdown-item>
                <el-dropdown-item v-show="query.type == 2" :command="2">复制</el-dropdown-item>
                <el-dropdown-item :command="3">放入回收站</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </li>
      </ul>
      <div class="pagination-box">
        <el-pagination small="" layout="total,prev, pager, next" :hide-on-single-page="true" :total="total"
          @current-change="changePage" :current-page="page" :page-size="size">
        </el-pagination>
      </div>
      <el-empty v-if="!loading && tableData.length == 0" content="没有更多数据" :image-size="100"></el-empty>
    </div>


    <el-dialog :close-on-click-modal="false" title="选择分享范围" :visible.sync="dialogVisible" width="400">
      <el-form :model="shareForm" :rules="shareRulesForm" label-width="160px">
        <el-form-item prop="share" label="分享范围：">
          <el-radio-group v-model="shareForm.sharingType">
            <el-radio :label="0">任课班级分享</el-radio>
            <el-radio :label="1">全年级分享</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveShare">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" title="上传word文档" :visible.sync="diaUp" width="600">
      <upload :url="url" :params="{ type: query.type }" @upSuccess="upSuccess" fileName="下载">
        <div class="down-box" slot="down">
          <p>第一步：导出菁优网试卷或
            <el-link type="danger" @click="downExcel">模板下载</el-link> 。
          </p>
          <p>第二步：上传完成编辑好的试卷。</p>
        </div>
      </upload>
      <div class="dialog-footer" slot="footer">
        <el-button @click="diaUp = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "examinationPaper",
  data() {
    return {
      code: "",
      gdClass: 0, //已归档班级数量
      loading: false,
      userName: "",
      dialogVisible: false,
      query: {
        classId: "",
        subjectName: "",
        title: "",
        type: 1, //试卷类型
        share: 0, //分享类型
      },
      classList: [],
      subjectList: [],
      archivedTotal: 0, //已归档答题卡数量
      tableData: [],
      shareForm: {
        id: "",
        sharingType: 0, //0-任课班级/1-全年级
      },
      shareRulesForm: {
        sharingType: [
          { required: true, message: "选择分享范围", trigger: "blur" },
        ],
      },
      total: 0,
      page: 1,
      size: 20,

      // v1.5
      totalCount: {//数量统计
        my: 0,
        share: 0,
      },
      diaUp: false,//上传word弹窗开关
      url: "/api_html/common/paper/upload",//上传文档地址
    };
  },
  async created() {
    this.code = localStorage.getItem("csCode") || "";
    this.role =
      this.$store.getters.info.showRole ||
      this.$store.getters.info.permissions[0].role;
    this.userName = this.$store.getters.info.name || "";
    this._QueryClassList2()
    await this._QueryClassList();
    if (!this.query.classId) {
      return;
    }
    await this._QuerySubjectList();
    this._QueryData();
    this._QueryTotal();
  },
  methods: {
    refreshStic() {
      setTimeout(function () {
        window.location.reload();
      }, 500);
    },
    toArchiving() {
      this.$router.push({
        path: "/examinationPaperArchiving",
      });
    },
    //去备题
    toAdd(query) {
      if (!this.query.classId) {
        this.$message.warning("没有任课班级，请先设置。");
        return;
      }
      let routerItem = {
        path: "/examinationPaperAdd",
      };
      query ? (routerItem["query"] = { ...query }) : "";
      this.$router.push(routerItem);
    },
    //去组卷
    toAddAsk(query) {
      if (!this.query.classId) {
        this.$message.warning("没有任课班级，请先设置。");
        return;
      }
      let routerItem = {
        path: "/examinationPaperAddAsk",
      };
      query ? (routerItem["query"] = { ...query }) : "";
      this.$router.push(routerItem);
    },
    toEdit(item) {
      this.$router.push({
        path: "/examinationPaperEdit",
        query: {
          paperId: item.id,
        },
      });
    },
    handleDropdownClick(value, item) {//更多
      const that = this;
      switch (value) {
        case 1:
          //修改分享范围
          that.shareForm.id = item.id;
          that.shareForm.sharingType = item.sharingType;
          that.dialogVisible = true;
          break;
        case 2:
          //复制
          that.toAdd({ type: 2, paperId: item.id });
          break;
        case 3:
          //归档
          that.recovery(item);
          break;
      }
    },
    changPaperType(type) {
      this.query.type = type
      this.changShare(1)
    },
    changePage(page) {
      this.page = page;
      this._QueryData(this.query.title);
    },
    //修改分享范围
    async saveShare() {
      const { data, status, info } = await this.$request.modifyPaper({
        paperId: this.shareForm.id,
        sharingType: this.shareForm.sharingType,
      });
      if (status === 0) {
        this.shareForm.id = "";
        this.shareForm.sharingType = 1;
        this.dialogVisible = false;
        this.$message.success(info);
        this._QueryData(this.query.title == "");
      } else {
        this.$message.error(info);
      }
    },
    //归档
    async recovery(item) {
      let modifyPaper =
        this.role == "ROLE_PERSONAL"
          ? this.$request.pModifyPaper
          : this.$request.modifyPaper;
      const { data, status, info } = await modifyPaper({
        paperId: item.id,
        status: 2,
      });
      if (status === 0) {
        let type = this.query.title ? true : false;
        this.page = 1;
        this._QueryData(type);
      } else {
        this.$message.error(info);
      }
    },
    //根据试卷名称查找
    async getData(bool) {
      this.page = 1;
      this._QueryData(bool);
      this._QueryTotal();
    },
    //切换班级
    async changClazz() {
      this.page = 1;
      await this._QuerySubjectList();
      this._QueryData(false);
      this._QueryTotal();
    },
    //切换类型
    async changShare(share) {
      this.query.share = share
      this.page = 1;
      this._QueryData(false);
    },
    // 查找班级
    async _QueryClassList2() {
      this.loading = true;
      let fetchClassList =
        this.role == "ROLE_PERSONAL"
          ? this.$request.pClassList
          : this.$request.fetchClassList;

      const { data, status, info } = await fetchClassList({ status: 1 });
      if (status === 0) {
        this.gdClass = data?.list?.length || 0;
      } else {
        this.$message.error(info);
      }
    },
    // 查找班级
    async _QueryClassList() {
      this.loading = true;
      let fetchClassList =
        this.role == "ROLE_PERSONAL"
          ? this.$request.pClassList
          : this.$request.fetchClassList;

      const { data, status, info } = await fetchClassList();
      if (status === 0) {
        if (!!data.list) {
          this.classList =
            data.list?.map((item) => {
              return {
                value: this.role == "ROLE_PERSONAL" ? item.id : item.classId,
                label: item.className,
              };
            }) || [];
          this.query.classId = this.classList[0]?.value;
        }
      } else {
        this.$message.error(info);
      }
    },
    // 查找科目
    async _QuerySubjectList() {
      if (!this.query.classId) return;
      let fetchSubjectList =
        this.role == "ROLE_PERSONAL"
          ? this.$request.pSubjectList
          : this.$request.fetchSubjectList;

      const { data, status, info } = await fetchSubjectList({
        classId: this.query.classId,
      });
      if (status === 0) {
        this.subjectList =
          data.subjectNames?.map((item) => {
            return {
              value: item,
              label: item,
            };
          }) || [];
        this.query.subjectName = this.subjectList[0]?.value;
      } else {
        this.$message.error(info);
      }
    },
    async _QueryData(type) {
      if (!this.query.classId) return;
      this.loading = true;
      //获取答题卡列表
      let query = {};
      if (!type) {
        this.query.title = "";
      }
      query = { ...this.query };
      for (let key in query) {
        if (!query[key] && query[key] !== 0) {
          delete query[key]
        }
      }
      if (!query.classId) {
        this.total = 0;
        this.tableData = [];
        this.loading = false;
        return;
      }
      this.loading = true;
      let fetchPaperList =
        this.role == "ROLE_PERSONAL"
          ? this.$request.pPaperList
          : this.$request.fetchPaperList;

      const { data, status, info } = await fetchPaperList({
        ...query,
        status: 1,
        page: this.page,
        size: this.size,
      });
      this.loading = false;
      if (status === 0) {
        this.archivedTotal = data.archivedTotal;
        this.total = data.total;
        this.tableData = (data.list && [...data.list]) || [];
      } else {
        this.$message.error(info);
      }
    },
    async _QueryTotal() {
      //获取答题卡列表
      let query = { ...this.query };
      for (let key in query) {
        if (!query[key]) {
          delete query[key]
        }
      }
      const { data, status, info } = await this.$request.paperShareCount({
        ...query,
      });
      if (status === 0) {
        this.totalCount.my = data?.myCount || 0;
        this.totalCount.share = data?.grade || 0;
      } else {
        this.$message.error(info);
      }
    },


    //v1.5
    upSuccess(res) {
      if (res.status == 0) {
        //导入成功
        this.$message.closeAll();
        this.$message({
          showClose: true,
          message: `${res.info}`,
          type: "success",
          duration: 2000,
        });
        this.diaUp = false;
        let params = JSON.stringify(res.data)
        if (this.query.type == 2) {
          this.toAdd({ params, isUpload: 1 })
        } else {
          this.toAddAsk({ params })
        }
      }
    },
    handleAdd(value) {
      if (value == 2) {
        this.toAdd()
      } else {
        this.diaUp = true
      }
    },


    async downExcel() {
      let data = await this.$request.teacherTemplate();
      if (data && !data.code) {
        let blob = new Blob([data], {
          type: "application/vnd.ms-excel;charset=utf-8",
        });
        downloadFile(`试卷模版.xlsx`, blob);
      } else {
        this.$message.error(data.info);
      }
    },
  },
};
</script>

<style scoped lang="scss">
.tips {
  display: flex;
  padding-left: 30px;
  line-height: 16px;
  font-size: 14px;
  color: #999;
  margin-bottom: 10px;
}

.content {
  margin: 0 20px;
  background: #f8f8f8;
  padding: 12px;
  border-radius: 20px;

  .item {
    display: flex;
    align-items: center;
    width: 100%;
    overflow: hidden;
    box-sizing: border-box;
    padding: 12px;
    border-radius: 20px;
    background: #fff;
    margin-bottom: 12px;

    &:last-of-type {
      margin-bottom: 0;
    }

    .pic-box {
      width: 80px;
      height: 80px;
      border-radius: 10px;
      margin-right: 10px;
      flex-shrink: 0;
      background: #667ffd;
      text-align: center;
      color: #fff;
      font-weight: 500;

      .i-box {
        padding-top: 10px;
        font-size: 32px;
        margin-bottom: 3px;
      }
    }

    .info {
      min-height: 80px;
      flex: 1;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .s-line {
        padding: 0 5px;
        color: #e2e2e2;
      }

      .title {
        font-size: 16px;
        color: #222;
        font-weight: 500;

        .label {
          display: inline-block;
          font-size: 12px;
          color: #2e9afe;
          line-height: 16px;
          padding: 0 10px;
          border: 1px solid #2e9afe;
          border-radius: 10px;
          transform: translateY(-2px);
        }
      }

      .person {
        color: #666;
      }
    }

    .clazz {
      font-size: 14px;
      font-weight: 500;
      position: relative;
      position: relative;

      &.active {
        color: #667ffd;
      }

      .el-icon-success {
        position: absolute;
        right: 0;
        top: -5px;
        color: #667ffd;
      }

      &:last-of-type {
        .el-icon-success {
          right: -18px;
        }
      }
    }

    .btn-box {
      flex-shrink: 0;

      .edit {
        margin-right: 12px;
      }
    }

    .icon-refresh {
      margin-left: 20px;
      cursor: pointer;

      &:hover {
        color: #2e9afe;
      }
    }
  }
}

.answer-header {
  .sel-box {
    .sel {
      min-width: 160px;
    }

    :deep(.el-cascader__tags) {
      flex-wrap: nowrap;
    }
  }
}

.dialog-footer {
  text-align: center;

  :deep(.el-button) {
    border-radius: 20px;
    padding: 8px 20px 7px;
    margin: 0 12px;
  }
}

// v1.5
.examinationPaper-type {
  padding: 16px 40px 0 20px;
  width: 100%;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
}

.content {
  .tab-box {
    padding-bottom: 10px;

    .tab-s {
      margin: 0 10px;
      font-size: 17px;
      line-height: 24px;
      font-weight: 500;
      cursor: pointer;

      &:hover {
        color: #667ffd;
      }

      &.active {
        color: #667ffd;
        border-bottom: 1px solid #667ffd
      }
    }
  }
}
</style>