<template>
  <el-table
    class="scan-result-table"
    :data="datas"
    @cell-click="studentClickHandle"
  >
    <el-table-column type="expand" class-name="td-expand" width="22">
      <template slot-scope="scope">
        <el-table
          :data="scope.row.papers"
          :show-header="false"
          class="scan-result-expand-table"
          :row-class-name="extendRowClassName"
          @cell-click="paperClickHandle"
        >
          <el-table-column width="22" class-name="td-checkbox" align="center">
            <template slot-scope="subScope">
              <el-checkbox
                v-model="subScope.row.select"
                @change="paperSelectionChange(scope.row)"
              ></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column
            label="文件名"
            prop="filename"
            class-name="cursor-column"
          >
            <template slot-scope="subScope">
              第{{ subScope.$index + 1 }}张
            </template>
          </el-table-column>
          <el-table-column
            class-name="action-column"
            label="操作"
            align="center"
            width="50"
          >
            <template slot-scope="subScope">
              <el-button
                class="btn-danger"
                type="text"
                icon="el-icon-error"
                @click.stop="toDeletePaper(scope.row, subScope.row)"
              >
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-table-column>
    <el-table-column width="22" class-name="td-checkbox" align="center">
      <template slot-scope="scope">
        <el-checkbox
          v-model="scope.row.select"
          @change="rowSelectionChange(scope.row)"
        ></el-checkbox>
      </template>
    </el-table-column>
    <el-table-column
      prop="studentCode"
      label="学号"
      class-name="cursor-column"
      :width="isNormalTab ? 120 : undefined"
    ></el-table-column>
    <el-table-column
      v-if="isNormalTab"
      prop="studentName"
      label="姓名"
    ></el-table-column>
    <el-table-column prop="paperCount" align="center" label="张数" width="50">
      <template slot-scope="scope">
        {{ scope.row.papers.length }}
      </template>
    </el-table-column>
    <el-table-column
      class-name="action-column"
      align="center"
      label="操作"
      width="50"
    >
      <template slot-scope="scope">
        <el-button
          class="btn-danger"
          type="text"
          @click.stop="toDeleteUser(scope.row)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
import { deleteFiles } from "../../../plugins/imageOcr";

export default {
  name: "scan-result-table",
  props: {
    tableData: {
      type: Array,
      default() {
        return [];
      },
    },
    tab: {
      type: String,
      default: "normal",
    },
  },
  data() {
    return { selectList: [], datas: [] };
  },
  computed: {
    isNormalTab() {
      return this.tab === "normal";
    },
  },
  watch: {
    tableData: {
      immediate: true,
      handler(val) {
        if (val) this.datas = val;
      },
    },
    datas(val) {
      this.$emit("update:tableData", val);
    },
  },
  methods: {
    // table action
    rowSelectionChange(row) {
      row.papers.forEach((p) => (p.select = row.select));
      this.updateSelectList();
    },
    paperSelectionChange(row) {
      const paperSelected = !row.papers.some((p) => !p.select);
      row.select = paperSelected;
      this.updateSelectList();
    },
    extendRowClassName({ row }) {
      const curImageUrl = this.$parent.curPaper.url.replace("file:///", "");
      if (
        row.frontOriginImgPath === curImageUrl ||
        row.versoOriginImgPath === curImageUrl
      ) {
        return "tr-active";
      }
      return "";
    },
    updateSelectList() {
      const selectList = [];
      this.datas.forEach((row) => {
        const selectPapers = row.papers.filter((p) => p.select);
        if (selectPapers.length) {
          selectList.push({
            ...row,
            papers: selectPapers,
          });
        }
      });

      this.selectList = selectList;
      this.$emit("select-change", this.selectList);
    },
    clearSelection() {
      this.datas.forEach((row) => {
        row.select = false;
        row.papers.forEach((p) => (p.select = false));
      });
      this.selectList = [];
      this.$emit("select-change", this.selectList);
    },
    async toDeleteUser(row) {
      const res = await this.$confirm(
        `确定要删除学生【${row.studentName || row.studentCode}】所有数据吗?`,
        "警告",
        {
          type: "warning",
        }
      ).catch(() => {});
      if (res !== "confirm") return;

      const selectedFiles = row.papers
        .map((item) => [item.frontOriginImgPath, item.versoOriginImgPath])
        .flat();
      deleteFiles(selectedFiles);

      this.datas = this.datas.filter(
        (item) => item.studentCode !== row.studentCode
      );

      this.updateSelectList();
      this.$emit("delete-paper", selectedFiles);
    },
    async toDeletePaper(row, paper) {
      const res = await this.$confirm(`确定要删除当前图片吗?`, "警告", {
        type: "warning",
      }).catch(() => {});
      if (res !== "confirm") return;

      const selectedFiles = [
        paper.frontOriginImgPath,
        paper.versoOriginImgPath,
      ];
      deleteFiles(selectedFiles);

      row.papers = row.papers.filter((item) => item.id !== paper.id);
      if (!row.papers.length) {
        this.datas = this.datas.filter(
          (item) => item.studentCode !== row.studentCode
        );
      }

      this.updateSelectList();
      this.$emit("delete-paper", selectedFiles);
    },
    studentClickHandle(row, column) {
      if (column.property !== "studentCode") return;

      const curPapers = row.papers
        .map((item) => [item.frontOriginImgPath, item.versoOriginImgPath])
        .flat();
      const curPaperIndex = 0;
      this.$emit("row-click", {
        curPaperIndex,
        curPapers,
      });
    },
    paperClickHandle(paper, column) {
      if (column.property !== "filename") return;

      const row = this.datas.find((item) =>
        item.papers.some((elem) => elem.id === paper.id)
      );
      if (!row) return;

      const curPapers = row.papers
        .map((item) => [item.frontOriginImgPath, item.versoOriginImgPath])
        .flat();
      const curPaperIndex = curPapers.findIndex(
        (item) => item === paper.frontOriginImgPath
      );
      this.$emit("row-click", {
        curPaperIndex,
        curPapers,
      });
    },
  },
};
</script>
