<template>
  <div class="app-container">
    <el-row>
      <el-button v-if="!editing" plain type="primary" @click="onBatchDelete">批量删除</el-button>
      <el-button v-if="editing" :disabled="!(selectIds&&selectIds.length)" type="danger" @click="onDeleteSelect">删除</el-button>
      <el-button v-if="editing" plain @click="onCancel">取消</el-button>
      <el-button plain type="primary" @click="onExport">导出</el-button>
    </el-row>

    <el-table ref="table" :data="list" border class="mt10" highlight-current-row stripe @sort-change="onSortChange" @selection-change="onTableSelectionChange" @row-click="onRowClick">
      <el-table-column v-if="editing" fixed type="selection" width="55"></el-table-column>
      <el-table-column :index="indexCompute" align="center" fixed="left" label="序号" type="index" width="60px"/>
      <el-table-column align="center" label="反馈人" prop="username" sortable="custom" width="130px"/>
      <el-table-column align="center" label="反馈内容" min-width="120px" prop="content" sortable="custom"/>
      <el-table-column align="center" label="反馈图片" min-width="130px" prop="images" sortable="custom">
        <template v-slot="scope">
          <div v-if="scope.row.images.length" class="flex justify-center">
            <el-image v-for="image in scope.row.images"
                      :key="image"
                      :preview-src-list="scope.row.images"
                      :src="image"
                      fit="contain"
                      class="mr10"
                      style="height: 40px">
            </el-image>
          </div>
        </template>
      </el-table-column>

      <el-table-column align="center" label="创建时间" prop="createTime" sortable="custom" width="160px">
        <template v-slot="scope">{{ scope.row.createTime | dateFormat }}</template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="120px">
        <template v-slot="scope">
          <el-link icon="el-icon-delete" type="primary" @click="onDelete(scope.row)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>
    <pagination :page.sync="listQuery.page" :size.sync="listQuery.size" :total="total" @change="onPageChange"/>

    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="exportVisible" title="导出" width="600px">
      <el-progress :percentage="exportProgress" :stroke-width="24" :text-inside="true" status="success"></el-progress>
      <el-button slot="footer" @click="onCancelExport">取 消</el-button>
    </el-dialog>
  </div>
</template>

<script>
import {dateFormat} from "@/utils/dateUtil"

export default {
  name: "TemporaryTaskFeedback",
  data() {
    return {
      shrinkable: false, // 查询条件是否可以展开
      listQuery: { // 查询对象
        taskId: undefined, // 任务id
        order: undefined,
        page: 1,
        size: 10
      },

      list: [], // 结果列表
      total: 0, // 总结果数量

      exportVisible: false, // 是否显示导出对话框
      exportData: [], // 导出数据
      exportPagination: { // 导出分页
        page: 1,
        size: 500,
      },
      exportProgress: 0, // 导出进度
      exportCancel: false, // 是否取消导出

      editing: false, // 表格编辑中

      selectItem: undefined, // 选中的单条记录
      selectIds: undefined, // 选中多条记录的id
    }
  },

  watch: {},

  // 页面创建
  created() {
    this.initData();
  },

  // 页面挂载
  mounted() {
    this.initView();
    this.initQuery();
    this.getList();
  },

  // keep-alive 显示界面时调用
  activated() {
    this.$refs["table"].doLayout();
  },

  // keep-alive 页面隐藏
  deactivated() {
  },

  methods: {
    // 初始化数据
    initData() {
      if (this.$route.query.taskId) {
        this.listQuery.taskId = this.$route.query.taskId;
        this.getList();
      }
    },

    // 初始化查询条件
    initQuery() {
      if (this.$store.state.app.paramCache) {
        let query = this.$storage.getData(this.$options.name);
        if (Object.keys(query).length > 0) {
          this.listQuery = query;
          if (query.order) {
            this.$refs.table.sort(query.order.substring(1), query.order.substring(0, 1) === "+" ? "ascending" : "descending");
          } else {
            this.$refs.table.clearSort();
          }
        }
      }
    },

    // 初始化视图
    initView() {
      this.$nextTick(() => {
        this.shrinkable = this.$store.state.app.filterShrink && this.$refs['listQuery'].$el.offsetHeight > 51;
      })
    },

    // 表格索引
    indexCompute(index) {
      return index + 1 + (this.listQuery.page - 1) * this.listQuery.size;
    },

    // 编辑
    onBatchDelete() {
      this.editing = true;
    },

    // 删除选中
    onDeleteSelect() {
      this.$confirm('此操作将永久删除选中的记录, 是否继续?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.$axios.delete("/v1/temporary/task/feedback/delete", {params: {ids: this.selectIds,taskId: this.listQuery.taskId}}).then((data) => {
          if (this.list.length <= this.selectIds.length && this.listQuery.page > 1) {
            this.listQuery.page -= 1;
          }
          this.selectIds = undefined;
          if (data) {
            this.$message.success("删除成功");
          } else {
            this.$message.warning("删除失败");
          }
          this.getList();
        });
      });
    },

    // 取消编辑
    onCancel() {
      this.$refs['table'].clearSelection();
      this.editing = false;
    },

    // 删除
    onDelete(item) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.$axios.delete(`/v1/temporary/task/feedback/delete/${item.id}`,{params: {taskId: this.listQuery.taskId}}).then((data) => {
          if (this.list.length === 1 && this.listQuery.page > 1) {
            this.listQuery.page -= 1;
          }
          if (data > 0) {
            this.$message.success("删除成功");
          } else {
            this.$message.warning("删除失败");
          }
          this.getList();
        });
      });
    },

    // 数据选择
    onTableSelectionChange(val) {
      this.selectIds = val.map(item => item.id);
    },

    // 排序改变
    onSortChange({prop, order}) {
      if (order === "ascending") {
        this.listQuery.order = "+" + prop;
      } else if (order === "descending") {
        this.listQuery.order = "-" + prop;
      } else {
        this.listQuery.order = undefined;
      }
      this.onFilterChange();
    },

    // 行点击
    onRowClick(row, column, event) {
      this.$refs["table"].setCurrentRow(row);
      if (this.editing) {
        this.$refs["table"].toggleRowSelection(row);
      }
    },

    // 条件改变
    onFilterChange() {
      this.listQuery.page = 1;
      this.$nextTick(this.getList);
    },

    // 页码改变
    onPageChange() {
      this.getList();
    },

    // 加载列表
    getList() {
      // 缓存参数
      if (this.$store.state.app.paramCache) {
        this.$storage.setData(this.$options.name, this.listQuery);
      }

      this.$axios.get("/v1/temporary/task/feedback/list", {params: this.listQuery}).then(data => {
        this.list = data.list.map(item => {
          item.images = item.images.split(",").filter(item => item.trim() !== '');
          return item;
        });
        this.total = data.total;
        this.$refs["table"].doLayout();
      });
    },

    // 导出数据
    onExport() {
      if (this.total > 0) {
        this.exportPagination.page = 1;
        this.exportData = [];
        this.exportVisible = true;
        this.getExportData();
      }
    },

    // 取消导出
    onCancelExport() {
      this.exportVisible = false;
      this.exportCancel = true;
    },

    // 获取数据并导出
    getExportData() {
      if (!this.exportCancel) {
        this.$axios.get("/v1/temporary/task/feedback/list", {params: {...this.listQuery, ...this.exportPagination}}).then(data => {
          this.exportPagination.page++;
          this.exportData = this.exportData.concat(data.list);
          this.exportProgress = Math.round(this.exportData.length * 100 / this.total);
          if (this.exportData.length < this.total && data.list.length > 0) {
            this.getExportData();
          } else {
            this.exportVisible = false;

            let tHeader = ["序号",
              "反馈id",
              "反馈人",
              "反馈内容",
              "反馈图片",
              "反馈创建时间",
            ];
            let filterVal = ["index",
              "id",
              "username",
              "content",
              "images",
              "createTime",
            ];
            let data = this.exportData.map((value, index) => filterVal.map((key) => {
              if (key === "index") {
                return index + 1;
              } else if (key === "createTime") {
                return dateFormat("yyyy-MM-dd HH:mm:ss", value[key]);
              } else {
                return value[key];
              }
            }));
            import('@/utils/Export2Excel').then(excel => {
              excel.export_json_to_excel({
                header: tHeader, // 表头 必填
                data, // 具体数据 必填
                filename: '临时任务反馈', // 非必填
                autoWidth: true, // 非必填
                bookType: 'xlsx' // 非必填
              })
            })
          }
        });
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {

}
</style>