<template>
  <div v-loading="loading" class="TextAnalysis">
    <HeaderPage />
    <div class="main">
      <div class="title">文本分析</div>
      <div class="input_main">
        <el-input v-model="txt" type="textarea" placeholder="请输入文本" :autosize="{ minRows: 9 }" :maxlength="maxWordCount" />
        <div class="text_btn">
          <span class="left">{{ txt.length }}/{{ maxWordCount }}</span>
          <div class="operation">
            <el-upload
              ref="upload"
              :action="url"
              accept=".txt"
              :limit="10"
              :on-exceed="handleExceed"
              :on-success="handleSuccess"
              multiple
              :show-file-list="false"
              class="btn"
            >
              <el-button>批量上传</el-button>
            </el-upload>
            <span class="btn" @click="submit">分析</span>
          </div>
        </div>
      </div>
      <div v-if="data" class="list_main">
        <div class="title">
          <span style="margin-right: 16px">文本列表：</span>
        </div>
        <div class="list">
          <div v-for="(item, i) in data.record_list" :key="`${i}one`">
            <div class="number">{{ i + 1 }}</div>
            <div class="txt" @click="handleJump(item)">
              {{ item.first_sentence }}
            </div>
            <div class="time">{{ item.create_time }}</div>
            <div class="analysis_status">{{ analysis_status_list[item.analysis_status] }}</div>
            <div
              v-if="item.analysis_status === 3 || item.analysis_status === 0"
              class="cxjx"
              @click="anewSubmit(item.id)"
            >
              {{ item.analysis_status === 3 ? '重新解析' : '解析' }}
            </div>
            <el-popconfirm title="确定删除这一条记录吗？" @confirm="deleteTextAnalyseRecord(item.id)">
              <img slot="reference" src="../../assets/teacherdev/delete-one.png" alt="删除" />
            </el-popconfirm>
          </div>
        </div>
        <el-pagination
          :current-page.sync="data.cur_page"
          :page-size="20"
          layout="prev, pager, next, jumper"
          :total="data.total_count"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
import {
  AddTextFile,
  GetTextAnalyseRecordInfo,
  PageQueryMyTextAnalyseRecordList,
  analyse,
  reparse,
  DeleteTextAnalyseRecord,
} from '@/api/api';
import { getToken } from '@/utils/auth';

import HeaderPage from '@/components/Header';

export default {
  name: 'TextAnalysis',
  components: {
    HeaderPage,
  },
  data() {
    return {
      txt: '',
      maxWordCount: 3000,
      loading: false,
      token: null,
      pageSize: 20,
      data: null,
      file_id_list: [],
      analysis_status_list: {
        0: '未解析',
        1: '解析中',
        2: '解析成功',
        3: '解析失败',
      },
    };
  },
  computed: {
    url() {
      let userInfo = JSON.parse(getToken());
      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"`;
    },
  },
  created() {
    let data = getToken();
    this.token = JSON.parse(data);
    this.pageQueryMyTextAnalyseRecordList();
  },
  // 方法集合
  methods: {
    // 批量上传
    handleSuccess(res, file, fileList) {
      if (res.status !== 1) {
        this.$message.error(res.message);
        return;
      }
      this.file_id_list.push(...file.response.file_info_list.map(({ file_id }) => file_id));
      // 通过 fileList 的 response 判断是否已全部完成上传
      if (fileList.every(({ response }) => response?.status)) {
        this.loading = true;
        this.$refs.upload.clearFiles();
        AddTextFile({
          file_id_list: this.file_id_list,
        })
          .then(() => {
            this.$message.success('上传成功');
            this.pageQueryMyTextAnalyseRecordList(true);
          })
          .catch((res) => {
            this.$message.error(res.message);
          })
          .finally(() => {
            this.file_id_list = [];
            this.loading = false;
          });
      }
    },
    handleExceed(files) {
      this.$message.warning(`当前限制选择 10 个文件，本次选择了 ${files.length} 个文件`);
    },

    handleJump(item) {
      if (item.analysis_status === 0) return this.anewSubmit(item.id);
      if (item.analysis_status === 1) return this.$message.warning('当前数据正在解析，请稍后');
      if (item.analysis_status === 2) {
        return this.getTextAnalyseRecordInfo(item.id).then((record) => {
          this.jumpResult(record);
        });
      }
      if (item.analysis_status === 3) return this.anewSubmit(item.id);
    },

    /**
     * 跳转分析结果页
     * @param {object} item
     */
    jumpResult(item) {
      if (item.analysis_status !== 2) {
        return this.$message.warning('当前数据解析失败，请重新解析');
      }
      window.open(
        this.$router.resolve({
          path: '/textanalysis/Result',
          query: {
            partition_key: item.partition_key,
            subject_words: item.subject_words,
            word_text_count: item.word_text_count,
            word_count: item.word_count,
            vocabulary_text_count: item.vocabulary_text_count,
            vocabulary_count: item.vocabulary_count,
            pinyin_count: item.pinyin_count,
            pinyin_text_count: item.pinyin_text_count,
            pinyin_difficulty: item.pinyin_difficulty,
            word_difficulty: item.word_difficulty,
            vocabulary_difficulty: item.vocabulary_difficulty,
            type: '文本分析',
          },
        }).href,
        '_blank',
      );
    },
    /**
     * 删除一条记录
     * @param {string} id
     */
    deleteTextAnalyseRecord(id) {
      this.loading = true;
      DeleteTextAnalyseRecord({ id })
        .then(() => {
          this.pageQueryMyTextAnalyseRecordList();
          this.$message.success('删除成功');
          this.loading = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /**
     * 重新解析
     * @param {string} analyse_record_id
     */
    anewSubmit(analyse_record_id) {
      this.loading = true;
      reparse({ analyse_record_id })
        .then(({ record }) => {
          this.jumpResult(record);
          this.pageQueryMyTextAnalyseRecordList(true);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /**
     * 分析
     */
    submit() {
      if (this.txt === '') {
        return this.$message.warning('请先输入内容');
      }
      if (this.txt.length > this.maxWordCount) {
        return this.$message.warning('超出字数限制');
      }
      this.loading = true;
      analyse({
        text: this.txt,
      })
        .then(({ record }) => {
          this.txt = '';
          this.jumpResult(record);
          this.pageQueryMyTextAnalyseRecordList(true);
        })
        .finally(() => {
          this.loading = false;
        });
    },

    /**
     * 获取单条文本分析记录信息
     * @param {string} id
     */
    getTextAnalyseRecordInfo(id) {
      return GetTextAnalyseRecordInfo({ id }).then(({ record }) => {
        return record;
      });
    },

    /**
     * 获取列表
     * @param {boolean} bol 是否提示
     */
    pageQueryMyTextAnalyseRecordList(bol) {
      this.loading = true;
      PageQueryMyTextAnalyseRecordList({ page_capacity: this.pageSize, cur_page: this.data?.cur_page ?? 1 })
        .then((data) => {
          this.data = data;
          if (bol) {
            this.$message.success('获取列表成功');
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleCurrentChange(val) {
      this.data.cur_page = val;
      this.pageQueryMyTextAnalyseRecordList();
    },
  },
};
</script>

<style lang="scss" scoped>
.TextAnalysis {
  min-height: 100%;

  .main {
    min-height: calc(100vh - 64px - 54px - 24px);
    padding-top: 54px;
    padding-bottom: 24px;
    background: #f6f6f6;

    > div {
      width: 1200px;
      margin: 0 auto;
    }

    > .title {
      font-size: 30px;
      font-weight: 700;
      line-height: 43px;
      color: #2c2c2c;
    }

    .input_main {
      width: 1168px;
      min-height: 295px;
      padding: 16px;
      margin-top: 17px;
      background: #fff;
      border-radius: 4px;

      .text_btn {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: 16px;

        .left {
          font-size: 14px;
          font-weight: 400;
          line-height: 26px;
          color: #000;
        }

        .operation {
          display: flex;

          .btn {
            width: 124px;
            height: 40px;
            font-size: 16px;
            font-weight: 500;
            line-height: 40px;
            color: #000;
            text-align: center;
            cursor: pointer;
            background: #ffc600;
            border: 1px solid rgba(0, 0, 0, 15%);
            border-radius: 4px;
            box-shadow: 0 2px 0 rgba(0, 0, 0, 4%);
            overflow: hidden;
            .el-button {
              color: #000;
              background-color: #ffc600;
              border-color: #ffc600;
              font-size: 16px;
              &:hover {
                color: #000;
              }
            }

            & + .btn {
              margin-left: 16px;
            }
          }
        }
      }
    }

    .list_main {
      margin-top: 37px;

      .title {
        font-size: 16px;
        font-weight: 400;
        line-height: 24px;
        color: #000;
      }

      .list {
        margin: 16px 0 22px;

        > div {
          display: flex;
          column-gap: 24px;
          align-items: center;
          height: 48px;
          padding: 0 16px;
          font-size: 16px;
          font-weight: 400;
          color: #000;
          background: #fff;
          border-bottom: 1px solid rgba(0, 0, 0, 8%);

          .number {
            width: 20px;
            text-align: right;
          }

          .txt {
            width: 740px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            cursor: pointer;
          }

          .time {
            width: 135px;
          }

          .cxjx {
            cursor: pointer;
          }

          .analysis_status {
            flex: 1;
          }

          img {
            width: 24px;
            height: 24px;
            cursor: pointer;
          }
        }
      }
    }
  }
}
</style>
