<template>
  <div v-loading="loading" class="WordTable">
    <div class="wheader" v-if="!userID">
      <HeaderPage />
    </div>
    <div class="main">
      <a class="go-back" @click="$router.go(-1)">
        <i class="el-icon-arrow-left"></i>
        返回
      </a>
      <div class="top">
        <div class="left">
          <div class="type_dv">
            <div class="sele">
              <span :class="[typeIndex == 0 ? 'sele' : '']" @click="cutType(0)">音节</span>
              <span :class="[typeIndex == 1 ? 'sele' : '']" @click="cutType(1)">汉字</span>
              <span :class="[typeIndex == 2 ? 'sele' : '']" @click="cutType(2)">词汇</span>
            </div>
            <div class="down" @click="download">
              <img src="../../assets/teacherdev/dowload-text.png" alt="" /><span>下载</span>
            </div>
          </div>
          <!-- <el-radio-group v-model="headText">
            <el-radio :label="1">词头</el-radio>
            <el-radio :label="2">文本</el-radio>
          </el-radio-group> -->
        </div>
        <div class="right">
          <!-- <el-cascader
            v-model="level"
            :options="levelList"
            :props="props"
            style="width: 140px; margin-right: 24px"
            @change="page1getdata"
          >
            <template slot-scope="{ data }">
                <span>{{ data.name }}</span>
            </template>
          </el-cascader> -->
          <el-select
            v-model="level"
            multiple
            collapse-tags
            style="width: 180px; margin-right: 24px"
            placeholder="请选择"
            @change="page1getdata"
          >
            <el-checkbox
              class="checkAllCheckbox"
              :indeterminate="isIndeterminate"
              v-model="checkAll"
              @change="handleCheckAllChange"
              >全部</el-checkbox
            >
            <el-option v-for="item in levelList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
          <div class="seek">
            <img src="../../assets/teacherdev/search-icon.png" alt="" />
            <input v-model="keyword" type="text" />
          </div>
          <div class="seekBtn" @click="page1getdata">搜索</div>
        </div>
      </div>
      <div class="table">
        <table border="0" cellspacing="0" cellpadding="0">
          <tr>
            <template v-for="(item, i) in tableHeader">
              <th
                v-if="(item.name === '拼音' && typeIndex !== 0) || item.name !== '拼音'"
                :key="i"
                :style="{ width: item.width }"
                :class="[i === tableHeader.length - 1 ? 'bz' : '']"
              >
                <div>
                  <span>
                    {{ item.name == '音节' ? (typeIndex === 0 ? '音节' : '汉字') : item.name }}
                  </span>
                  <template v-if="item.sortShow">
                    <div :class="['sort']">
                      <div>
                        <img
                          :src="
                            item.sort === 'up'
                              ? require('../../assets/teacherdev/sort-sele-up.png')
                              : require('../../assets/teacherdev/sort-up.png')
                          "
                          alt="排序"
                          @click="SortEvent('up', item.name, item.sortName)"
                        />
                      </div>
                      <div>
                        <img
                          :src="
                            item.sort == 'down'
                              ? require('../../assets/teacherdev/sort-sele-down.png')
                              : require('../../assets/teacherdev/sort-down.png')
                          "
                          alt="排序"
                          @click="SortEvent('down', item.name, item.sortName)"
                        />
                      </div>
                    </div>
                  </template>
                </div>
              </th>
            </template>
          </tr>
          <tr v-for="(item, index) in dataList.word_list" :key="index + 'td'">
            <td class="sort-td" style="text-align: center">{{ item.number }}</td>
            <td :class="['sort-td', typeIndex === 0 ? 'pinyin' : 'hanzi']">
              <span
                :style="{
                  fontFamily: typeIndex !== 0 ? '楷体' : '',
                  fontWeight: '400',
                  fontSize: '18px',
                  color: item.level_id && levelMap[item.level_id] ? levelMap[item.level_id].color : '',
                  cursor: typeIndex !== 0 ? 'pointer' : '',
                }"
                @click="backHighlight(item, levelMap[item.level_id].color, 'all', index, typeIndex)"
                >{{ item.word }}</span
              >
            </td>
            <td v-if="typeIndex !== 0" class="sort-td" style="font-family: 'League'">
              {{ item.pinyin }}
            </td>
            <td class="sort-td">
              <span
                :style="{
                  fontFamily: '楷体',
                  fontSize: '16px',
                  color: item.grade_id && levelMap[item.grade_id] ? levelMap[item.grade_id].color : '',
                }"
                >{{ item.grade_name }}</span
              >
            </td>
            <td class="sort-td">
              <span
                :style="{
                  fontFamily: '楷体',
                  fontSize: '16px',
                  color: item.level_id && levelMap[item.level_id] ? levelMap[item.level_id].color : '',
                }"
                >{{ item.level_name }}</span
              >
            </td>
            <td
              class="sort-td"
              style="font-size: 16px; cursor: pointer"
              @click="backHighlight(item, levelMap[item.level_id].color, 'all', index)"
            >
              {{ item.freq }}
            </td>
            <td class="sort-td">{{ item.text_ratio }}%</td>
            <td>
              <div style="display: flex; flex-wrap: wrap">
                <span
                  v-for="(items, i) in item.remarks"
                  :key="i"
                  class="beizhu"
                  :style="{
                    marginRight: '10px',
                    cursor: 'pointer',
                    borderColor: items.levelId && levelMap[items.levelId] ? levelMap[items.levelId].color + '16' : '',
                    background: items.levelId && levelMap[items.levelId] ? levelMap[items.levelId].color + '50' : '',
                  }"
                  @click="backHighlight(items, levelMap[items.levelId].color, 'one', index)"
                >
                  <span style="font-family: '楷体'" v-html="items.word"> </span>
                  <span
                    :style="{
                      fontFamily: '楷体',
                      color: items.levelId && levelMap[items.levelId] ? levelMap[items.levelId].color : '',
                    }"
                  >
                    {{ items.levelName }}
                  </span>
                  <span>
                    {{ items.freq }}
                  </span>
                </span>
              </div>
            </td>
          </tr>
        </table>
        <template v-if="dataList.word_list.length == 0">
          <div class="no_data">暂无数据</div>
        </template>

        <!-- <el-table
          :data="dataList.list"
          style="width: 100%"
          @sort-change="sort_change"
          ref="table"
          :sort-orders="['levelName']"
          sortable="custom"
        >
          <el-table-column prop="number" label="序号" width="48" align="center">
          </el-table-column>
          <el-table-column
            prop="word"
            :label="typeIndex == 0 ? '音节' : '汉字'"
            width="93"
            sortable
          >
            <template slot-scope="item">
              <span
                :style="{
                  color:
                    item.row.levelName && levelMap[item.row.levelName]
                      ? levelMap[item.row.levelName].color
                      : '',
                }"
                >{{ item.row.word }}</span
              >
            </template>
          </el-table-column>
          <template v-if="typeIndex != 0">
            <el-table-column prop="pinYin" label="拼音" width="95" sortable>
            </el-table-column>
          </template>
          <el-table-column prop="gradeName" label="等次" width="95" sortable>
            <template slot-scope="item">
              <span
                :style="{
                  color:
                    item.row.gradeName && levelMap[item.row.gradeName]
                      ? levelMap[item.row.gradeName].color
                      : '',
                }"
                >{{ item.row.gradeName }}</span
              >
            </template>
          </el-table-column>
          <el-table-column prop="levelName" label="级别" width="106" sortable>
            <template slot-scope="item">
              <span
                :style="{
                  color:
                    item.row.levelName && levelMap[item.row.levelName]
                      ? levelMap[item.row.levelName].color
                      : '',
                }"
                >{{ item.row.levelName }}</span
              >
            </template>
          </el-table-column>
          <el-table-column prop="freq" label="频数" width="108" sortable>
          </el-table-column>
          <el-table-column prop="textRatio" label="比例" width="110" sortable>
          </el-table-column>
          <el-table-column prop="" label="备注">
            <template slot-scope="item">
              <div style="display: flex">
                <span
                  v-for="(items, i) in item.row.remarks"
                  :key=""
                  class="beizhu"
                  style="margin-right: 10px"
                >
                  <span
                    style="font-size: 18px; font-weight: 400"
                    v-html="items.word"
                  >
                  </span>
                  <span
                    :style="{
                      color:
                        items.levelName && levelMap[items.levelName]
                          ? levelMap[items.levelName].color
                          : '',
                    }"
                  >
                    {{ items.levelName }}
                  </span>
                  <span>
                    {{ items.freq }}
                  </span>
                </span>
              </div>
            </template>
          </el-table-column>
        </el-table> -->
      </div>
      <div v-if="dataList.word_list.length > 0" class="page">
        <el-pagination
          background
          :current-page="page"
          :page-size="pageSize"
          layout="prev, pager, next, jumper"
          :total="dataList.total_count"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
import HeaderPage from '@/components/Header.vue';
import { postapi, publicMethods } from '@/api/api';
import { levelMap } from '../../common/data';
import { json2excel } from '@/utils/setMethods';

export default {
  components: {
    HeaderPage,
  },
  data() {
    return {
      props: { multiple: true },
      typeIndex: 0,
      headText: 1,
      keyword: '',
      level: [],
      checkAll: false,
      isIndeterminate: true,
      levelList: [
        {
          value: null,
          label: '全部',
        },
        {
          value: 1,
          label: '初等',
          children: [
            { value: '100,101,102', label: '全部' },
            { value: '100', label: '1级' },
            { value: '101', label: '2级' },
            { value: '102', label: '3级' },
          ],
        },
        {
          value: 2,
          label: '中等',
          children: [
            { value: '103,104,105', label: '全部' },
            { value: '103', label: '4级' },
            { value: '104', label: '5级' },
            { value: '105', label: '6级' },
          ],
        },
        {
          value: 3,
          label: '高等',
          children: [{ value: '106', label: '7-9级' }],
        },
        {
          value: 107,
          label: '超纲',
          children: [{ value: '107', label: '超纲' }],
        },
        {
          value: 108,
          label: '专有',
          children: [{ value: '108', label: '专有' }],
        },
        {
          value: 109,
          label: '其它',
          children: [{ value: '109', label: '其它' }],
        },
      ],

      tableHeader: [
        {
          name: '序号',
          sortShow: false,
          width: '48px',
        },
        {
          name: '音节',
          sortShow: true,
          sort: '',
          width: '93px',
          sortName: 'word',
        },
        {
          name: '拼音',
          sortShow: true,
          sort: '',
          width: '95px',
          sortName: 'pin_yin',
        },
        {
          name: '等次',
          sortShow: true,
          sort: '',
          width: '95px',
          sortName: 'grade_id',
        },
        {
          name: '级别',
          sortShow: true,
          sort: 'down',
          width: '150px',
          sortName: 'level_id',
        },
        {
          name: '频数',
          sortShow: true,
          sort: '',
          width: '88px',
          sortName: 'freq',
        },
        {
          name: '比例',
          sortShow: true,
          sort: '',
          width: '90px',
          sortName: 'word_ratio',
        },
        {
          name: '备注',
          sortShow: false,
          sort: '',
          width: '',
          sortName: '',
        },
      ],
      dataList: {
        word_list: [],
      },
      page: 1,
      pageSize: 10,
      partition_key: null,
      searchType: null,
      levelMap,
      loading: false,
      sortType: 0,
      sortField: 'level_id',
      routerData: null,
      alldata: null,
      id: '',
      allLevels: [],
      userID: this.$route.query.userID,
    };
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.routerData = JSON.parse(JSON.stringify(this.$route.query));

    this.partition_key = Number(this.$route.query.partition_key);
    this.id = this.routerData.id;
    this.getLevelList();
    this.getlist();
  },
  methods: {
    // 下载
    download() {
      let data = JSON.parse(JSON.stringify(this.alldata));
      data.forEach((item, index) => {
        item.text_ratio += '%';
        let str = '';
        // 处理备注
        item.remarks.forEach((items) => {
          let node = document.createElement('span');
          node.innerHTML = items.word;
          str += `${node.innerText} ${items.levelName} ${items.freq}      `;
        });
        item.remarksTxt = str;
        item.number = index + 1;
      });
      let tHeader = [];
      let filterVal = [];
      this.tableHeader.forEach((item) => {
        tHeader.push(item.name);
      });
      if (this.typeIndex === 0) {
        tHeader.splice(2, 1);
        filterVal = ['number', 'word', 'grade_name', 'level_name', 'freq', 'text_ratio', 'remarksTxt'];
      } else {
        tHeader[1] = '汉字';
        filterVal = ['number', 'word', 'pinyin', 'grade_name', 'level_name', 'freq', 'text_ratio', 'remarksTxt'];
      }
      let excelDatas = [
        {
          tHeader,
          filterVal, // 表一的数据字段
          tableDatas: data, // 表一的整体json数据
          sheetName: 'sheet1', // 表一的sheet名字
        },
      ];
      // 引入的函数
      json2excel(excelDatas, '词表', true, 'xlsx');
    },
    // 返回并高亮对应数据
    backHighlight(item, color, type, index, typeIndex) {
      if (typeIndex === 0) {
        return;
      }
      let data = JSON.parse(JSON.stringify(this.routerData));
      let arr = [];
      if (type === 'all') {
        if (this.typeIndex === 0) {
          item.remarks.forEach((items) => {
            arr.push(items.word);
          });
        } else {
          arr.push(this.dataList.word_list[index].word);
        }
      } else if (this.typeIndex === 0) {
        arr.push(item.word);
      } else {
        let matchStr = item.word.replace(/<span style='color:red;'>/g, '').replace(/<\/span>/g, '');
        arr.push(matchStr);
      }
      data.remarks = JSON.stringify(arr);
      data.color = color;
      data.leftNavIndex = this.typeIndex;
      data.userID = this.userID;
      sessionStorage.setItem('tablehighlight', true);
      this.$router.replace({
        path: '/textanalysis/Result',
        query: data,
      });
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getlist();
    },
    // 获取等级列表
    getLevelList() {
      this.allLevels = [];
      // this.levelList = [{
      //     value: '',
      //     id: '',
      //     name: '全部',
      //     label: '全部'
      // }]
      this.levelList = [];
      publicMethods('/TeachingServer/TextAnalyser/GetLevelList', {}).then((res) => {
        if (res.status === 1) {
          res.level_list.forEach((item) => {
            item.value = item.id;
            item.label = item.name;
            this.allLevels.push(item.id);
          });
          this.levelList = this.levelList.concat(res.level_list);
        }
      });
    },
    getlist() {
      this.loading = true;
      let order_column_list = [];
      if (this.sortType === 1) {
        order_column_list = [this.sortField + ':desc'];
      } else if (this.sortType === 0) {
        // 升序不传值
        order_column_list = [this.sortField];
      }
      let data = {
        cur_page: this.page,
        page_capacity: this.pageSize,
        type: this.typeIndex,
        word: this.keyword,
        order_column_list: order_column_list,
        level_id_list: this.level,
        analyse_record_id: this.id,
      };
      publicMethods('/TeachingServer/TextAnalyser/PageQueryWordList', data)
        //   postapi({
        //     url: '/GCLSTCServer/tools/TS/glossary/list',
        //     data: {
        //       pageIndex: this.page,
        //       pageSize: this.pageSize,
        //       partitionKey: this.partition_key,
        //       searchType: this.typeIndex,
        //       word: this.keyword,
        //       sortField: this.sortField,
        //       sortType: this.sortType,
        //       levels: this.level ? this.level[1] : null,
        //     },
        //   })
        .then((res) => {
          let num = this.page * this.pageSize - this.pageSize + 1;
          res.word_list.forEach((item) => {
            item.remarks = JSON.parse(item.remarks);
            item.number = num;
            num += 1;
          });
          this.dataList = res;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
      publicMethods('/TeachingServer/TextAnalyser/PageQueryWordList', {
        cur_page: 1,
        page_capacity: 9999,
        type: this.typeIndex,
        word: this.keyword,
        order_column_list: order_column_list,
        level_id_list: this.level,
        analyse_record_id: this.id,
      })
        //   postapi({
        //     url: '/GCLSTCServer/tools/TS/glossary/list',
        //     data: {
        //       pageIndex: 1,
        //       pageSize: 9999,
        //       partitionKey: this.partition_key,
        //       searchType: this.typeIndex,
        //       word: this.keyword,
        //       sortField: this.sortField,
        //       sortType: this.sortType,
        //       levels: this.level ? this.level[1] : null,
        //     },
        //   })
        .then((res) => {
          let num = 0;
          res.word_list.forEach((item) => {
            item.remarks = JSON.parse(item.remarks);
            item.number = num;
            num += 1;
          });
          this.alldata = res.word_list;
        });
    },
    page1getdata(value) {
      if (value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.levelList.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.levelList.length;
      }
      this.loading = true;
      this.page = 1;
      this.getlist();
    },
    SortEvent(type, name, sortName) {
      let sort = '';
      this.tableHeader.forEach((item) => {
        if (item.name === name) {
          if (!item.sort || item.sort === 'up') {
            item.sort = 'down';
            sort = 'down';
          } else if (item.sort === 'down') {
            item.sort = 'up';
            sort = 'up';
          }
        } else {
          item.sort = '';
        }
      });
      this.sortType = sort === 'down' ? 1 : 0;
      this.sortField = sortName;
      this.getlist();
    },
    // sort_change(column, prop, order) {
    //   if (this.$refs.table) this.$refs.table.clearSort();
    //   column.column.order = column.order;
    //   if (column.prop === 'pinyin') {
    //     this.sortField = 'pin_yin';
    //   } else if (column.prop === 'gradeName') {
    //     this.sortField = 'grade_id';
    //   } else if (column.prop === 'levelName') {
    //     this.sortField = 'level_id';
    //   } else if (column.prop === 'textRatio') {
    //     this.sortField = 'text_ratio';
    //   } else {
    //     this.sortField = column.prop;
    //   }
    //   if (column.order === 'descending') {
    //     this.sortType = 1;
    //   } else {
    //     this.sortType = 0;
    //   }
    //   this.getlist();
    // },
    cutType(index) {
      this.typeIndex = index;
      this.page1getdata();
    },
    handleCheckAllChange(val) {
      this.level = val ? this.allLevels : [];
      this.isIndeterminate = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.WordTable {
  min-height: 100%;
  background: #f6f6f6;

  .wheader {
    background: #fff;
  }

  .main {
    width: 1200px;
    margin: 0 auto;
    padding: 23px 0;
    .go-back {
      border-radius: 4px;
      border: 1px solid #d9d9d9;
      background: #fff;
      box-shadow: 0px 2px 0px 0px rgba(0, 0, 0, 0.02);
      display: flex;
      width: 60px;
      color: #333;
      font-size: 14px;
      font-weight: 400;
      line-height: 22px;
      padding: 9px 8px;
      align-items: center;
      cursor: pointer;
      margin-bottom: 16px;
      .el-icon-arrow-left {
        font-size: 16px;
        margin-right: 8px;
      }
    }
    .top {
      display: flex;
      justify-content: space-between;

      .left {
        display: flex;
        align-items: center;

        .type_dv {
          display: flex;
          margin-right: 40px;

          > .sele {
            display: flex;
            align-items: center;
            height: 40px;
            padding: 0 2px;
            background: #eee;
            border-radius: 4px;

            span {
              display: inline-block;
              width: 56px;
              height: 36px;
              font-size: 14px;
              font-weight: 400;
              line-height: 40px;
              color: #888;
              text-align: center;
              cursor: pointer;
            }

            .sele {
              color: #000;
              background: #fff;
              box-shadow: 0 2px 2px rgba(0, 0, 0, 8%);
            }
          }

          > .down {
            display: flex;
            align-items: center;
            margin-left: 24px;
            font-size: 14px;
            font-weight: 400;
            line-height: 22px;
            color: #000;
            cursor: pointer;

            img {
              width: 24px;
              height: 24px;
              margin-right: 4px;
            }
          }
        }
      }

      .right {
        display: flex;
        align-items: center;

        .seek {
          display: flex;
          width: 264px;
          height: 40px;
          background: #fff;
          border: 1px solid #ddd;
          border-radius: 2px 0 0 2px;

          img {
            width: 16px;
            height: 16px;
            margin: 12px 4px 12px 12px;
          }

          input {
            flex: 1;
            height: 40px;
            background: none;
            border: none;
            outline: none;
          }
        }

        .seekBtn {
          width: 56px;
          height: 40px;
          font-size: 16px;
          font-weight: 400;
          line-height: 40px;
          color: #fff;
          text-align: center;
          cursor: pointer;
          background: #ffa800;
          border: 1px solid #ffa800;
          border-radius: 0 2px 2px 0;
        }
      }
    }

    .table {
      margin-top: 21px;

      .no_data {
        height: 60px;
        line-height: 60px;
        color: #909399;
        text-align: center;
        background: #fff;
      }

      table {
        width: 100%;
        border-collapse: collapse;
        background: #fff;

        .pinyin {
          font-family: 'League';
          text-align: left !important;
        }

        .hanzi {
          text-align: left !important;
        }

        .jb {
          > div {
            justify-content: flex-end !important;

            .sort {
              margin-left: 10px;
            }
          }
        }

        th {
          background: #fff;

          .bz {
            flex: 1;
          }

          > div {
            display: flex;
            align-items: center;
            // justify-content: space-between;
            height: 48px;
            padding: 0 8px;

            .sort {
              cursor: pointer;
              margin-left: 4px;

              > div {
                // height: 11px;
                font-size: 0;
                img {
                  width: 11px;
                  height: 11px;
                }
              }

              > :nth-child(1) {
                > img {
                  position: relative;
                  top: 0px;
                }
              }

              > :nth-child(2) {
                > img {
                  position: relative;
                  bottom: 0px;
                }
              }
            }
          }
        }

        td {
          height: 40px;
          font-size: 14px;
          font-weight: 400;
          line-height: 40px;
          text-align: left;
          border-bottom: 1px solid #eee;
        }

        .sort-td {
          padding: 0 9px;
        }
      }
    }

    .page {
      margin-top: 24px;
    }

    .beizhu {
      display: flex;
      align-items: center;
      height: 28px;
      padding-right: 7px;
      padding-left: 4px;
      margin-top: 8px;
      margin-bottom: 8px;
      font-size: 16px;
      font-weight: 500;
      border: 1px solid;
      border-radius: 4px;

      > :not(:nth-last-child(1)) {
        margin-right: 8px;
      }
    }
  }
}
</style>

<style lang="scss">
.WordTable {
  .table {
    .el-table th {
      padding: 7px 0;
      background: #fff;
    }

    .el-table th > .cell {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      font-weight: 700;
      color: #333;
    }

    .el-table td {
      padding: 8px 0;
    }

    .el-table td > .cell {
      font-size: 14px;
      font-weight: 600;
      line-height: 22px;
      color: #333;
    }
  }

  .el-radio__input.is-checked + .el-radio__label {
    color: #000;
  }

  .el-radio__input.is-checked .el-radio__inner {
    background: #1e1e1e;
    border: 2px solid #c8c8c8;
  }

  .el-radio__inner::after {
    background: none;
  }

  .el-radio__inner {
    background: #c8c8c8;
    border: none;
  }

  .el-pagination.is-background .el-pager li:not(.disabled).active {
    color: rgba(0, 0, 0, 85%);
    background: #fff !important;
    border: 1px solid #333;
  }

  .el-pager {
    .number {
      background: #fff !important;
      border: 1px solid #d9d9d9;
      border-radius: 2px;
    }
  }

  .btn-prev,
  .btn-next {
    background: #fff !important;
    border: 1px solid #d9d9d9;
    border-radius: 2px;
  }
}
.checkAllCheckbox {
  width: 100%;
  padding: 0 20px;
  height: 34px;
  line-height: 34px;
  &:hover {
    background-color: #f5f7fa;
  }
  .el-checkbox__input {
    display: none;
  }
  .el-checkbox__label {
    padding: 0;
  }
}
</style>
