<template>
  <div class="cread" v-loading="loading">
    <template v-if="!showCard">
      <Header v-if="!userID" />
      <div class="go-back-box" :class="[userID ? 'go-back-box-user' : '']" v-if="!isPreview">
        <a v-if="!userID" class="go-back" :class="[editCardflag ? '' : 'go-back-preview']" @click="goBack">
          <i class="el-icon-arrow-left"></i>
          返回
        </a>
        <template v-if="editCardflag">
          <div class="name-box">
            <label>卡片名称</label>
            <el-input v-model="saveName"></el-input>
          </div>
          <div class="btn-box">
            <el-button small @click="addCard"><i class="el-icon-plus"></i>增加卡片</el-button>
            <el-upload
              ref="upload"
              :action="url"
              accept=".xlsx,.xls"
              :limit="9999"
              :on-exceed="handleExceed"
              :on-success="handleSuccess"
              :show-file-list="false"
              class="btn"
              style="margin: 0 8px"
            >
              <el-button>通过模版导入</el-button>
            </el-upload>
            <el-button type="primary" plain small @click="save">结束编辑并保存</el-button>
          </div>
        </template>
        <template v-else>
          <h3>{{ saveName }}</h3>
          <div class="btn-box">
            <span class="checked-number" v-if="filtCardflag && filtTable.length > 0">已选{{ filtTable.length }}张</span>
            <!-- <el-button @click="changeRowLength">{{ showRoeText[showRowLength] }}</el-button> -->
            <el-button small @click="handleSureFilt" v-if="filtCardflag">类举</el-button>
            <el-button
              small
              @click="
                filtCardflag = true;
                showRowLength = newEditTable.length > 4 ? 6 : newEditTable.length;
              "
              v-else
              >筛选</el-button
            >
            <el-button small @click="editCardflag = true"><i class="el-icon-edit"></i>编辑</el-button>
            <el-button small @click="download2"
              ><img src="../../assets/teacherdev/word-eyes.png" alt="" />打印</el-button
            >
          </div>
        </template>
      </div>
      <div
        class="content"
        :class="[editCardflag ? '' : 'content-flex content-flex-' + showRowLength]"
        :style="{ minHeight: innerHeight - 220 + 'px' }"
      >
        <div
          v-for="(item, index) in filtCardflag ? newEditTable : filtTableShow"
          :key="index"
          :class="[editCardflag ? '' : 'item-flex']"
        >
          <writeTable
            :editCardflag="editCardflag"
            :dataConfig="writeTableData"
            :data="item"
            :pageNumber="index + 1"
            :totalNumber="showRowLength"
            :isPreview="true"
            @handleDelItem="handleDelItem"
            :filtCardflag="filtCardflag"
            :filtId="filtId"
            :filtTable="filtTable"
            @zoomInCard="zoomInCard"
          />
        </div>
      </div>
      <el-pagination
        background
        :current-page="currentPage"
        :page-size="showRowLength"
        :page-sizes="[1, 2, 3, 4, 6]"
        :total="filtTable.length"
        layout="total, prev, pager, next, sizes, jumper"
        @size-change="(val) => handleSizeChange(val, 'showRowLength', 'currentPage')"
        @current-change="(val) => handleCurrentChange(val, 'currentPage')"
        v-if="!filtCardflag"
      />
    </template>
    <el-dialog title="" :visible.sync="showCard" width="100%" class="wordCard-dialog" top="0">
      <i class="el-icon-arrow-left" :class="[showIndex === 0 ? 'disabled' : '']" @click="changeShowIndex('-')"></i>
      <writeTableZoom
        :editCardflag="false"
        :dataConfig="writeTableData"
        :data="filtTable[showIndex]"
        :pageNumber="showIndex"
        :totalNumber="0"
        :isPreview="true"
        :filtCardflag="false"
        ref="writeTableZoom"
      />
      <p style="width: 100%; text-align: center; font-size: 20px; color: #fff">
        {{ showIndex + 1 }} / {{ filtTable.length }}
      </p>
      <i
        class="el-icon-arrow-right"
        :class="[showIndex === filtTable.length - 1 ? 'disabled' : '']"
        @click="changeShowIndex('+')"
      ></i>
    </el-dialog>
    <!-- <div class="preview_dv" v-if="isPreview" :style="{ top: userID ? '0' : '' }">
      <img class="close" src="../../assets/teacherdev/creadCad-close.png" alt="" @click="closepreviewEvent" />
      <el-button type="primary" class="print-btn" small @click="download2">打印</el-button>
      <div class="preview_main">
        <img
          class="left"
          src="../../assets/teacherdev/creadCad-left.png"
          alt=""
          @click="changepreviewIndex('remove')"
        />
        <div class="word_main">
          <div class="word_main_table">
            <writeTable
              :type="typeIndex"
              :dataConfig="newEditTable"
              :data="newEditTable[previewIndex]"
              :pageNumber="previewIndex + 1"
              :totalNumber="newEditTable.length"
              :isPreview="true"
              :showLeft="showLeft"
              @changeShowLeft="changeShowLeft"
              ref="writeTable"
            />
          </div>
        </div>
        <img class="right" src="../../assets/teacherdev/creadCad-right.png" alt="" @click="changepreviewIndex('add')" />
      </div>
    </div> -->
  </div>
</template>

<script>
//这里可以导入其它文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》from ‘《组件路径》';
import Header from '@/components/Header';
import { getLogin, LearnWebSI, getHZChineseInfo, getContentFile } from '@/api/api';
import writeTable from './writeTableNew.vue';
import writeTableZoom from './writeTableZoom.vue';
import { getToken } from '@/utils/auth';
import html2canvas from 'html2canvas';
import { jsPDF } from 'jspdf';
import canvg from 'canvg';
import cnchar from 'cnchar';
import 'cnchar-radical';

import FileSaver from 'file-saver';
import htmlDocx from 'html-docx-js/dist/html-docx';
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {
    Header,
    writeTable,
    writeTableZoom,
  },
  props: {},
  data() {
    //这里存放数据
    return {
      saveName: '',
      typeIndex: 0,
      loading: false,
      writeTableData: null,
      isPreview: false,
      previewIndex: 0,
      saveShow: false,
      hzDetailList: null,
      userID: this.$route.query.userID ? this.$route.query.userID : '',
      editCardflag: this.$route.query.id ? false : true, // 是否编辑卡片
      newEditTable: [
        // {
        //   borderColor: '#243C97',
        //   fontColor: '#243C97',
        //   fontAlign: 'left',
        //   label: '',
        //   headerCon: '',
        //   left: {
        //     fileList: [],
        //     con: '',
        //   },
        //   right: {
        //     definition: '',
        //     collocation: '',
        //     exampleSent: '',
        //     hz_info: [],
        //     pinyin: '',
        //     audio_file: '',
        //     cixing: '',
        //   },
        // },
      ],
      showLeft: true,
      showRowLength: 1, // 一页展示几个，有一行一列，一行两列，一行三列和两行两列
      showRoeText: {
        1: '一行一列',
        2: '一行两列',
        3: '一行三列',
        4: '两行两列',
        5: '两行三列',
      },
      innerHeight: window.innerHeight,
      filtCardflag: true, // 筛选状态
      filtTable: [], // 筛选卡片
      filtTableShow: [], //分页后的筛选卡片
      filtId: [], // 筛选卡片id数组
      currentPage: 1,
      showCard: false, //卡片放大
      showIndex: null, // 卡片放大索引
    };
  },
  //计算属性 类似于data概念
  computed: {
    url() {
      let userInfo = getToken()
        ? JSON.parse(getToken())
        : sessionStorage.getItem('GCLS_Token_Tc')
        ? JSON.parse(sessionStorage.getItem('GCLS_Token_Tc'))
        : null;
      if (!userInfo) return `${process.env.VUE_APP_BASE_API}/GCLSFileServer/WebFileUpload`;
      return `${process.env.VUE_APP_BASE_API}/GCLSFileServer/WebFileUpload?AccessToken=${userInfo.access_token}&SecurityLevel=Mid"`;
    },
  },
  //监控data中数据变化
  watch: {},
  //方法集合
  methods: {
    addCard() {
      this.newEditTable.push({
        borderColor: '#243C97',
        fontColor: '#243C97',
        fontAlign: 'left',
        label: '',
        headerCon: '',
        left: {
          fileList: [],
          con: '',
        },
        right: {
          definition: '',
          collocation: '',
          exampleSent: '',
          hz_info: [],
          pinyin: '',
          audio_file: '',
          cixing: '',
          hideHanzi: false,
        },
        id: Math.random().toString(36).substring(2, 10),
      });
    },
    // 删除一条卡片
    handleDelItem(index) {
      this.newEditTable.splice(index, 1);
    },

    // 返回上一页
    goBack() {
      this.$router.push({
        path: '/wordcard/table',
      });
    },
    // 保存
    save() {
      if (!this.saveName || !this.saveName.trim()) {
        this.$message.warning('请填写卡片名称');
        return;
      }
      this.loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      let text = '';
      this.newEditTable.forEach((items) => {
        text += items.left.con.trim() + '\n';
      });
      if (this.$route.query.id) {
        // 编辑
        let Mname = 'tr_tool-wsc_manager-UpdateMyWordSentenceCard';
        LearnWebSI(Mname, {
          id: this.$route.query.id,
          name: this.saveName,
          type: this.typeIndex == 0 ? 'WORD' : 'SENTENCE',
          text: text,
          content: JSON.stringify(this.newEditTable),
          update_scope: 0,
        })
          .then((res) => {
            this.loading.close();
            this.loading = false;
            this.editCardflag = false;
            this.$message.success('保存成功');
            this.showRowLength = this.newEditTable.length > 4 ? 6 : this.newEditTable.length;
          })
          .catch((res) => {
            this.loading.close();
            this.loading = false;
          });
      } else {
        // 新建
        let Mname = 'tr_tool-wsc_manager-CreateMyWordSentenceCard';
        LearnWebSI(Mname, {
          name: this.saveName,
          type: this.typeIndex == 0 ? 'WORD' : 'SENTENCE',
          text: text,
          content: JSON.stringify(this.newEditTable),
          app_user_id: this.userID,
        })
          .then((res) => {
            this.$router.replace({
              path: '/wordcard/cread',
              query: {
                id: res.id,
                userID: this.userID,
              },
            });
            this.loading.close();
            this.loading = false;
            this.editCardflag = false;
            this.$message.success('保存成功');
            this.showRowLength = this.newEditTable.length > 4 ? 6 : this.newEditTable.length;
          })
          .catch((res) => {
            this.loading.close();
            this.loading = false;
          });
      }
      this.filtCardflag = true;
    },

    // 字句详情
    getdetai() {
      this.loading = true;
      let Mname = 'tr_tool-wsc_manager-GetWordSentenceCard';
      LearnWebSI(Mname, {
        id: this.$route.query.id,
      })
        .then((res) => {
          this.saveName = res.name;
          this.newEditTable = JSON.parse(res.content);
          this.newEditTable.forEach((item) => {
            if (!item.hasOwnProperty('id')) {
              this.$set(item, 'id', Math.random().toString(36).substring(2, 10));
            }
          });
          this.loading = false;
          this.showRowLength = this.newEditTable.length > 4 ? 6 : this.newEditTable.length;
        })
        .catch((res) => {
          this.loading = false;
        });
    },
    // 预览
    previewEvent() {
      this.previewIndex = 0;
      this.showLeft = true;
      this.isPreview = true;
    },
    // 关闭预览
    closepreviewEvent() {
      this.isPreview = false;
    },
    changepreviewIndex(type) {
      if (type == 'add') {
        if (this.previewIndex == this.newEditTable.length - 1) {
          this.$message.warning('当前已经是最后一页');
          return;
        }
        this.previewIndex++;
      } else {
        if (this.previewIndex == 0) {
          this.$message.warning('当前已经是第一页');
          return;
        }
        this.previewIndex--;
      }
      this.$refs.writeTable.changeRota();
      this.showLeft = true;

      this.$forceUpdate();
    },
    changeShowLeft() {
      this.showLeft = !this.showLeft;
    },
    download2() {
      if (this.filtTable.length === 0) {
        this.$message.warning('未选中卡片');
        return;
      }
      this.$nextTick(() => {
        if (this.filtTable) {
          let str = JSON.stringify(this.filtTable);
          localStorage.setItem('newEditTable', str);
          this.$router.replace({
            path: '/wordcard/printNew',
            query: {
              userID: this.userID,
              id: this.$route.query.id,
            },
          });
        }
      });
    },
    async handleSuccess(res, file, fileList) {
      if (res.status !== 1) {
        this.$message.error(res.message);
        return;
      }
      let file_id = file.response.file_info_list[0].file_id;
      this.loading = true;
      // 通过 fileList 的 response 判断是否已全部完成上传
      this.loading = true;
      this.$refs.upload.clearFiles();
      await LearnWebSI('tr_tool-wsc_manager-ParseWordSentenceCardImportFile', {
        file_id: file_id,
      })
        .then((res) => {
          this.loading = false;
          this.$message.success('导入成功');
          res.content_json_text.forEach((items) => {
            if (
              items.headerCon ||
              items.label ||
              items.left.con ||
              items.right.cixing ||
              items.right.collocation ||
              items.right.definition ||
              items.right.exampleSent ||
              items.right.pinyin
            ) {
              items.borderColor = '#243C97';
              items.fontAlign = 'left';
              items.fontColor = '#243C97';
              let con = items.left.con.trim();
              if (con) {
                let MethodName = 'hz_resource_manager-GetMultHZStrokesContent';
                let data = {
                  hz_str: con,
                };
                getLogin(MethodName, data)
                  .then((res) => {
                    this.loading = false;
                    for (let key in res) {
                      if (key != 'status' && key != ',' && res[key]) {
                        res[key] = JSON.parse(res[key]);
                      }
                    }
                    let hzDetailList = res;
                    let hz_list = [];
                    con.split('').forEach((items) => {
                      let res = JSON.parse(JSON.stringify(hzDetailList[items]));
                      let obj = {
                        con: items,
                        hzDetail: {
                          hz_json: res,
                        },
                      };
                      hz_list.push(obj);
                    });
                    items.right.hz_info = hz_list;
                    let MethodName = 'tool-TextToVoiceFile';
                    if (con) {
                      let datas = {
                        text: con,
                      };
                      getLogin(MethodName, datas).then((res) => {
                        if (res.status === 1) {
                          items.right.audio_file = res.file_id;
                        }
                      });
                    }
                  })
                  .catch(() => {
                    this.loading = false;
                  });
              }
              this.newEditTable.push(items);
            }
          });
        })
        .catch((res) => {
          this.loading = false;
        });
    },
    handleExceed(files) {
      this.$message.warning(`当前限制选择 9999 个文件，本次选择了 ${files.length} 个文件`);
    },
    changeRowLength() {
      if (this.showRowLength === 4) {
        this.showRowLength = 6;
      } else if (this.showRowLength === 6) {
        this.showRowLength = 1;
      } else {
        this.showRowLength++;
      }
    },
    handleSureFilt() {
      if (this.filtTable.length === 0) {
        this.$message.warning('请勾选要类举的卡片');
        return;
      }
      this.filtTable.slice().reverse();
      this.filtCardflag = false;
      this.showRowLength = this.filtTable.length > 4 ? 6 : this.filtTable.length;
      this.getList();
    },
    handleSizeChange(val, type, page) {
      this[type] = val;
      this[page] = 1;
      this.getList();
    },
    handleCurrentChange(val, type) {
      this[type] = val;
      this.getList();
    },
    getList() {
      this.filtTableShow = JSON.parse(JSON.stringify(this.filtTable)).splice(
        (this.currentPage - 1) * this.showRowLength,
        this.showRowLength,
      );
    },
    zoomInCard(index) {
      this.showIndex = index;
      this.showCard = true;
    },
    changeShowIndex(type) {
      if (type === '+') {
        if (this.showIndex !== this.filtTable.length - 1) {
          this.showIndex++;
        }
      } else {
        if (this.showIndex !== 0) {
          this.showIndex--;
        }
      }
      this.$refs.writeTableZoom.changeRota();
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  //生命周期-创建之前
  beforeCreated() {},
  //生命周期-挂载之前
  beforeMount() {},
  //生命周期-更新之前
  beforUpdate() {},
  //生命周期-更新之后
  updated() {},
  //生命周期-销毁之前
  beforeDestory() {},
  //生命周期-销毁完成
  destoryed() {},
  //如果页面有keep-alive缓存功能，这个函数会触发
  activated() {
    if (this.$route.query.cachesType == 'pop') {
      this.saveName = '';
      this.typeIndex = 0;
      this.loading = false;
      this.newEditTable = [
        // {
        //   borderColor: '#243C97', // 卡片边框颜色
        //   fontColor: '#243C97', // 字体颜色
        //   fontAlign: 'left', // 页眉对齐方式
        //   label: '', // 标签内容
        //   headerCon: '', // 页眉内容
        //   left: {
        //     fileList: [], // 上传文件
        //     con: '', // 字词卡片内容（即卡片显示的字词）
        //   },
        //   right: {
        //     definition: '', // 释义
        //     collocation: '', // 搭配
        //     exampleSent: '', // 例句
        //     hz_info: [], // 汉字笔顺等内容
        //     pinyin: '', // 拼音
        //     audio_file: '', // 字词生成的音频
        //     cixing: '', // 词性
        //   },
        // },
      ];
      this.previewIndex = 0;
      this.saveShow = false;
      this.showLeft = true;
      this.editCardflag = this.$route.query.id ? false : true;
      this.isPreview = false;
      if (this.$route.query.id) {
        // 需要请求详情接口
        this.getdetai();
      }
    }
  },
};
</script>
<style lang="scss" scoped>
/* @import url(); 引入css类 */
.cread {
  min-height: 100%;
  position: relative;
  background: #f2f2f2;
  .go-back-box {
    width: 1200px;
    display: flex;
    border-radius: 8px;
    background: #fff;
    padding: 8px;
    margin: 20px auto;
    // position: fixed;
    // top: 83px;
    // left: 50%;
    // margin-left: -610px;
    // z-index: 1000;
    border: 1px solid rgba(0, 0, 0, 0.15);
    &-user {
      top: 19px;
    }
    h3 {
      font-size: 24px;
      font-weight: 500;
      line-height: 150%;
      flex: 1;
      text-align: center;
    }
    img {
      width: 20px;
      margin-right: 6px;
    }
    .el-button {
      padding: 8px 16px;
      height: 40px;
      line-height: 24px;
    }
  }
  .go-back {
    display: flex;
    color: #333;
    font-size: 24px;
    font-weight: 500;
    line-height: 36px;
    padding: 0 16px 0 0;
    align-items: center;
    cursor: pointer;
    &-preview {
      width: 300px;
    }
    .el-icon-arrow-left {
      font-size: 16px;
      margin-right: 8px;
    }
  }
  .name-box {
    flex: 1;
    display: flex;
    align-items: center;
    label {
      color: #4e5969;
      font-size: 14px;
      font-weight: 400;
      line-height: 22px;
      margin-right: 16px;
    }
    .el-input {
      width: 227px;
      border-radius: 2px;
      background: #f2f3f5;
    }
  }
  .btn-box {
    display: flex;

    i {
      margin-right: 8px;
      font-size: 16px;
    }
    .checked-number {
      margin-right: 8px;
      font-size: 14px;
      color: red;
      line-height: 40px;
    }
  }
  .content {
    // padding-top: 88px;
    &-flex {
      display: flex;
      width: 1470px;
      margin: 0 auto;
      flex-flow: wrap;
      gap: 50px 120px;
      justify-content: center;
      align-content: center;
      padding: 10px 0;
      &-3,
      &-4 {
        gap: 50px 80px;
        .item-flex {
          width: 350px !important;
        }
      }
      &-2,
      &-4,
      &-6 {
        justify-content: start;
      }
      &-1 {
        width: 500px;
      }
      &-2 {
        width: 920px;
      }
      &-4 {
        width: 780px;
      }
      &-6 {
        width: 1120px;
        gap: 50px 80px;
        .item-flex {
          width: 320px !important;
        }
      }
    }
    .item-flex {
      width: 400px;
      flex-shrink: 0;
    }
  }
}
.preview_dv {
  position: absolute;
  left: 0;
  top: 64px;
  width: 100%;
  min-height: calc(100% - 64px);
  background: #f2f2f2;
  > img {
    width: 40px;
    height: 40px;
    cursor: pointer;
    position: absolute;
    top: 24px;
    right: 31px;
  }
  .print-btn {
    cursor: pointer;
    position: absolute;
    top: 24px;
    left: 31px;
  }
  .preview_main {
    padding: 24px 0;
    width: 740px;
    display: flex;
    align-items: center;
    height: 450px;
    position: absolute;
    top: 50%;
    margin-top: -225px;
    left: 50%;
    margin-left: -370px;
    > div {
      margin: 0 24px;
    }
    img {
      width: 48px;
      height: 48px;
      cursor: pointer;
    }
  }
}
:deep .el-pagination {
  text-align: right;
  width: 1200px;
  margin: 0 auto;
}
:deep .el-dialog {
  background: transparent;
}
:deep .el-dialog__headerbtn {
  right: 200px;
  top: 0;
}
:deep .el-dialog__headerbtn .el-dialog__close {
  color: #f2f3f5;
  font-size: 30px;
}
.wordCard-dialog {
  display: flex;
  align-items: center;
  :deep .el-dialog {
    box-shadow: none;
  }

  .el-icon-arrow-left,
  .el-icon-arrow-right {
    color: #f2f2f2;
    font-size: 40px;
    position: fixed;
    top: 50%;
    margin-top: -20px;
    left: 200px;
    cursor: pointer;
    &.disabled {
      color: darkgrey;
      cursor: not-allowed;
    }
  }
  .el-icon-arrow-right {
    left: auto;
    right: 200px;
  }
}
</style>
<style lang="scss">
.cread {
  .name-box {
    .el-input__inner {
      border-radius: 2px;
      background: #f2f3f5;
      border: none;
    }
  }
  .btn-box {
    .el-button {
      span {
        display: flex;
        align-items: center;
      }
    }
  }
}
</style>
