<template>
  <div class="app-container">
    <el-row ref="listQueryContainer" class="query-container" justify="space-between" type="flex">
      <el-col>
        <el-form ref="listQuery" :inline="true" :model="listQuery" style="flex-wrap: wrap" @submit.native.prevent @keyup.enter.native="onSubmit">
          <el-form-item label="任务状态" prop="status">
            <el-select v-model="listQuery.status" clearable placeholder="请选择任务状态" @change="onFilterChange">
              <el-option v-for="item in statusList" :key="item.id" :label="item.label" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="审核状态" prop="auditStatus">
            <el-select v-model="listQuery.auditStatus" clearable placeholder="请选择审核状态" @change="onFilterChange">
              <el-option v-for="item in auditStatusList" :key="item.id" :label="item.label" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="任务分类" prop="type">
            <el-select v-model="listQuery.type" clearable placeholder="请选择任务分类" @change="onFilterChange" @clear="listQuery.type=undefined">
              <el-option v-for="item in typeList" :key="item.id" :label="item.label" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="任务名称" prop="title">
            <el-input v-model.trim="listQuery.title" clearable maxlength="16" placeholder="请输入任务名称" @keyup.enter.native="onSubmit">
              <i slot="suffix" class="el-input__icon el-icon-search" @click="onFilterChange"></i>
            </el-input>
          </el-form-item>
          <el-form-item label="任务内容" prop="content">
            <el-input v-model.trim="listQuery.content" clearable maxlength="16" placeholder="请输入任务内容" @keyup.enter.native="onSubmit">
              <i slot="suffix" class="el-input__icon el-icon-search" @click="onFilterChange"></i>
            </el-input>
          </el-form-item>
          <el-form-item label="执行人" prop="executor">
            <el-input v-model.trim="listQuery.executor" clearable maxlength="16" placeholder="请输入执行人" @keyup.enter.native="onSubmit">
              <i slot="suffix" class="el-input__icon el-icon-search" @click="onFilterChange"></i>
            </el-input>
          </el-form-item>
          <el-form-item label="发起人" prop="username">
            <el-input v-model.trim="listQuery.username" clearable maxlength="16" placeholder="请输入发起人" @keyup.enter.native="onSubmit">
              <i slot="suffix" class="el-input__icon el-icon-search" @click="onFilterChange"></i>
            </el-input>
          </el-form-item>
          <!-- 日期选择-->
          <el-form-item label="时间范围" prop="dateRange">
            <el-date-picker
                v-model="listQuery.dateRange"
                :default-time="['00:00:00', '23:59:59']"
                end-placeholder="结束日期"
                range-separator="-"
                start-placeholder="开始日期"
                type="daterange"
                value-format="yyyy-MM-dd HH:mm:ss"
                @change="onFilterChange">
            </el-date-picker>
          </el-form-item>
          <el-form-item label-width="0">
            <el-button type="primary" @click="onFilterChange">查询</el-button>
            <el-button plain type="primary" @click="resetFields">重置</el-button>
            <el-button plain type="primary" @click="onExport">导出</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <form-clear :shrinkable="shrinkable" @change="onExpansion" @clear="resetFields"/>
    </el-row>
    <el-row>
      <el-button type="primary" @click="onAdd">添加</el-button>
      <el-button v-if="!editing" plain type="primary" @click="onEdit">批量删除</el-button>
      <el-button v-if="editing" type="danger" @click="onDeleteSelect">删除</el-button>
      <el-button v-if="editing" plain @click="onCancel">取消</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" fixed="left" label="任务名称" min-width="120px" prop="title" sortable="custom"/>
      <el-table-column align="center" label="任务类型" prop="type" sortable="custom" width="110px">
        <template v-slot="scope">
          {{ typeList.find(item => item.id === Number(scope.row.type)).label }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="任务内容" min-width="120px" prop="content"/>
      <el-table-column align="center" label="房间" sortable="custom" min-width="120px" prop="roomName"/>
      <el-table-column align="center" label="所属系统" sortable="custom" width="140px" prop="belongSystem" show-overflow-tooltip/>
      <el-table-column align="center" label="执行人" min-width="120px" prop="executor" show-overflow-tooltip>
        <template v-slot="scope">
          {{ scope.row.executors.join("、") }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="发起人" prop="username" sortable="custom" width="120px"></el-table-column>
      <el-table-column align="center" label="任务状态" prop="status" sortable="custom" width="110px">
        <template v-slot="scope">
          <text-label v-if="scope.row.status===1" type="primary">{{ statusList.find(item => item.id === scope.row.status).label }}</text-label>
          <text-label v-if="scope.row.status===2" type="success">{{ statusList.find(item => item.id === scope.row.status).label }}</text-label>
          <text-label v-if="scope.row.status===3" type="warning">{{ statusList.find(item => item.id === scope.row.status).label }}</text-label>
          <text-label v-if="scope.row.status===4" type="danger">{{ statusList.find(item => item.id === scope.row.status).label }}</text-label>
        </template>
      </el-table-column>
      <el-table-column align="center" label="审核状态" prop="auditStatus" sortable="custom" width="110px">
        <template v-slot="scope">
          <template v-if="scope.row.status===1 || scope.row.status===4">
            <text-label v-if="scope.row.auditStatus===1" type="warning">{{ auditStatusList.find(item => item.id === scope.row.auditStatus).label }}</text-label>
            <text-label v-if="scope.row.auditStatus===2" type="primary">{{ auditStatusList.find(item => item.id === scope.row.auditStatus).label }}</text-label>
            <text-label v-if="scope.row.auditStatus===3" type="danger">{{ auditStatusList.find(item => item.id === scope.row.auditStatus).label }}</text-label>
          </template>
          <template v-else>/</template>
        </template>
      </el-table-column>
      <el-table-column align="center" label="备注" prop="remark" sortable="custom" width="120px" show-overflow-tooltip>
        <template v-slot="scope">
          <template v-if="(scope.row.status===1 || scope.row.status===4) && scope.row.auditStatus===3">{{ scope.row.remark }}</template>
          <template v-else>/</template>
        </template>
      </el-table-column>
      <el-table-column align="center" label="发布时间" prop="publishTime" sortable="custom" width="160px">
        <template v-slot="scope">
          {{ scope.row.publishTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="完成时间" prop="finishTime" sortable="custom" width="160px">
        <template v-slot="scope">
          {{ scope.row.finishTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="反馈次数" prop="feedbackTotal" sortable="custom" width="110px" fixed="right">
        <template v-slot="scope">
          <router-link :to="{path:'/temporary-task/temporary-task/feedback',query:{taskId:scope.row.id}}">
            <el-link type="primary">{{ scope.row.feedbackTotal }}</el-link>
          </router-link>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="300px" fixed="right">
        <template v-slot="scope">
          <el-link :disabled="scope.row.status===2||scope.row.status===3" icon="el-icon-check" type="success" @click="onTaskPass(scope.row)">通过</el-link>
          <el-link :disabled="scope.row.status===2||scope.row.status===3" class="ml20" icon="el-icon-check" type="warning" @click="onTaskFail(scope.row)">不通过</el-link>
          <el-link :disabled="scope.row.status===2||scope.row.status===3" class="ml20" icon="el-icon-close" type="primary" @click="onTaskCancel(scope.row)">取消</el-link>
          <el-link class="ml20" icon="el-icon-delete" type="danger" @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>

    <dialog-edit v-if="editDialogVisible" :visible.sync="editDialogVisible" @add="onAddComplete"/>
  </div>
</template>

<script>
import DialogEdit from "./dialogEdit";
import {dateFormat} from "@/utils/dateUtil";

export default {
  name: "TemporaryTask",
  components: {DialogEdit},
  data() {
    return {
      shrinkable: false, // 查询条件是否可以展开
      listQuery: { // 查询对象
        type: undefined, // 任务类型 1:一般任务 2:较急任务 3:紧急任务
        status: undefined, // 任务状态 1:正在处理 2:已经完成 3:已经取消 4:超时任务
        auditStatus: undefined, // 审核状态 1:未提交 2:待审核 3:不通过
        title: undefined, // 任务标题
        content: undefined, // 任务内容
        username: undefined, // 发起人名称
        executor: undefined, // 执行人名称
        dateRange: [], // 时间范围
        startTime: undefined,
        endTime: undefined,
        order: undefined, // 排序方式

        page: 1,
        size: 10
      },

      statusList: [{id: 1, label: "正在处理"}, {id: 2, label: "已经完成"}, {id: 3, label: "已经取消"}, {id: 4, label: "超时任务"}], // 任务状态列表
      auditStatusList: [{id: 1, label: "未提交"}, {id: 2, label: "待审核"}, {id: 3, label: "不通过"}], // 审核状态列表
      typeList: [{id: 1, label: "一般任务"}, {id: 2, label: "较急任务"}, {id: 3, label: "紧急任务"}], // 任务分类列表

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

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

      editDialogVisible: false, // 编辑对话框是否可见

      editing: false, // 表格编辑中

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

  watch: {
    // 监听日期范围变化
    'listQuery.dateRange'(value) {
      if (value) {
        this.listQuery.startTime = value[0];
        this.listQuery.endTime = value[1];
      } else {
        this.listQuery.startTime = undefined;
        this.listQuery.endTime = undefined;
      }
    }
  },

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

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

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

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

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

    // 初始化查询条件
    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, query.order === "asc" ? "ascending" : "descending");
          } else {
            this.$refs.table.clearSort();
          }
        }
      }
    },

    // 初始化数据
    initData() {
    },

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

    // 展开/收起查询条件
    onExpansion(show) {
      this.$refs['listQueryContainer'].$el.style.height = show ? "auto" : "51px";
    },

    // 表单提交
    onSubmit() {
      this.onFilterChange();
    },

    // 表单清除
    resetFields() {
      this.$refs['listQuery'].resetFields();
      this.listQuery.order = undefined;
      this.$refs.table.clearSort();
      this.onFilterChange();
    },

    // 添加
    onAdd() {
      this.onCancel();
      this.editDialogVisible = true;
    },

    // 添加完成
    onAddComplete() {
      this.onFilterChange();
    },

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

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

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

    // 任务取消
    onTaskCancel(item) {
      this.$axios.put("/v1/temporary/task/update", {id: item.id, status: 2}).then(() => {
        this.getList();
      });
    },

    // 任务办结
    onTaskPass(item) {
      this.$axios.put("/v1/temporary/task/update", {id: item.id, status: 1}).then(() => {
        this.getList();
      });
    },

    // 任务审核不通过
    onTaskFail(item) {
      this.$prompt('请输入备注', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({value}) => {
        this.$axios.put("/v1/temporary/task/update", {id: item.id, status: 3, remake: value}).then(() => {
          this.getList();
        });
      });
    },

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

    // 数据选择
    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/list", {params: this.listQuery}).then(data => {
        this.list = data.list;
        this.total = data.total;
        this.$refs["table"].doLayout();
        this.onCancel();
      });
    },

    // 导出数据
    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/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 = ["序号", "房间名称", "所属系统", "任务名称", "任务类型", "任务内容", "执行人", "发起人", "任务状态", "审核状态", "审核备注", "发布时间", "完成时间", "执行反馈次数"];
            let filterVal = ["index", "roomName", "belongSystem", "title", "type", "content", "executors", "username", "status", "auditStatus", "remark", "publishTime", "finishTime", "feedbackTotal"];
            let data = this.exportData.map((value, index) => filterVal.map((key) => {
              if (key === "index") {
                return index + 1;
              } else if (key === "executors") {
                return value[key].map(item => item.executor).join("、");
              } else if (key === "type") {
                return this.typeList.find(item => item.id === Number(value[key])).label;
              } else if (key === "status") {
                return this.statusList.find(item => item.id === Number(value[key])).label;
              } else if (key === "auditStatus") {
                return this.auditStatusList.find(item => item.id === Number(value[key])).label;
              } else if (key === "publishTime") {
                return dateFormat("yyyy-MM-dd HH:mm:ss", new Date(value[key]));
              } else if (key === "finishTime") {
                return dateFormat("yyyy-MM-dd HH:mm:ss", new Date(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>
