<template>
  <div class="cread" v-loading="loading">
    <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-button type="primary" plain small @click="save">结束编辑并保存</el-button>
        </div>
      </template>
      <template v-else>
        <h3>{{ saveName }}</h3>
        <div class="btn-box">
          <el-button small @click="editCardflag = true"><i class="el-icon-edit"></i>编辑</el-button>
          <el-button small @click="previewEvent"
            ><img src="../../assets/teacherdev/word-eyes.png" alt="" />预览</el-button
          >
        </div>
      </template>
    </div>
    <div class="content" v-if="!isPreview">
      <div v-for="(item, index) in newEditTable" :key="index">
        <writeTable
          :editCardflag="editCardflag"
          :dataConfig="writeTableData"
          :data="item"
          :pageNumber="index + 1"
          :totalNumber="newEditTable.length"
          :isPreview="isPreview"
          @handleDelItem="handleDelItem"
        />
      </div>
    </div>
    <div class="preview_dv" v-if="isPreview" :style="{ top: userID ? '0' : '' }">
      <img class="close" src="../../assets/teacherdev/creadCad-close.png" alt="" @click="closepreviewEvent" />
      <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"
            />
          </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 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,
  },
  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: true, // 是否编辑卡片
      newEditTable: [
        {
          left: {
            fileList: [],
            con: '',
          },
          right: {
            definition: '',
            collocation: '',
            exampleSent: '',
            hz_info: [],
            pinyin: [],
            audio_file: '',
          },
        },
      ],
      showLeft: true,
    };
  },
  //计算属性 类似于data概念
  computed: {},
  //监控data中数据变化
  watch: {},
  //方法集合
  methods: {
    addCard() {
      this.newEditTable.push({
        left: {
          fileList: [],
          con: '',
        },
        right: {
          definition: '',
          collocation: '',
          exampleSent: '',
          hz_info: [],
          pinyin: [],
          audio_file: '',
        },
      });
    },
    // 删除一条卡片
    handleDelItem(index) {
      this.newEditTable.splice(index, 1);
    },

    // 返回上一页
    goBack() {
      this.$router.push({
        path: '/wordcard/table',
      });
    },
    // 保存
    save() {
      if (!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('保存成功');
          })
          .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('保存成功');
          })
          .catch((res) => {
            this.loading.close();
            this.loading = false;
          });
      }
    },

    // 字句详情
    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.loading = false;
        })
        .catch((res) => {
          this.loading = false;
        });
    },
    // 预览
    previewEvent() {
      this.previewIndex = 0;
      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.showLeft = true;
      this.$forceUpdate();
    },
    changeShowLeft() {
      this.showLeft = !this.showLeft;
    },
  },
  //生命周期 - 创建完成（可以访问当前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 = [
        {
          left: {
            fileList: [],
            con: '',
          },
          right: {
            definition: '',
            collocation: '',
            exampleSent: '',
            hz_info: [],
            pinyin: [],
            audio_file: '',
          },
        },
      ];
      this.previewIndex = 0;
      this.saveShow = false;
      this.showLeft = true;
      this.editCardflag = true;
      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;
    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: 184px;
    }
    .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;
    }
  }
  .content {
    padding-top: 88px;
  }
}
.preview_dv {
  position: absolute;
  left: 0;
  top: 64px;
  width: 100%;
  min-height: 100%;
  background: #f2f2f2;
  > img {
    width: 40px;
    height: 40px;
    cursor: pointer;
    position: absolute;
    top: 24px;
    right: 31px;
  }
  .preview_main {
    padding: 24px 0;
    width: 740px;
    margin: 0 auto;
    display: flex;
    align-items: center;
    height: 100%;
    > div {
      margin: 0 24px;
    }
    img {
      width: 48px;
      height: 48px;
      cursor: pointer;
    }
  }
}
</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>
