<template>
  <div class="app-container">
    <el-row type="flex" justify="space-between" ref="listQueryContainer" class="query-container">
      <el-col>
        <el-form :inline="true" style="flex-wrap: wrap" :model="listQuery" ref="listQuery" @submit.native.prevent @keyup.enter.native="onSubmit">
          <el-form-item label="任务编号" prop="number">
            <el-input v-model.trim="listQuery.number" maxlength="16" placeholder="请输入任务编号" clearable @clear="listQuery.number=undefined" @keyup.enter.native="onFilterChange">
              <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.taskName" maxlength="16" placeholder="请输入任务名称" clearable @clear="listQuery.taskName=undefined" @keyup.enter.native="onFilterChange">
              <i slot="suffix" class="el-input__icon el-icon-search" @click="onFilterChange"></i>
            </el-input>
          </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="oneself">
            <el-select v-model="listQuery.oneself" clearable placeholder="请选择" @change="onFilterChange" @clear="listQuery.oneself=undefined">
              <el-option v-for="item in oneselfList.slice(1)" :key="item.id" :label="item.label" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="楼栋名称" prop="buildingName">
            <el-input v-model.trim="listQuery.buildingName" maxlength="16" placeholder="请输入楼栋名称" clearable @clear="listQuery.buildingName=undefined" @keyup.enter.native="onFilterChange">
              <i slot="suffix" class="el-input__icon el-icon-search" @click="onFilterChange"></i>
            </el-input>
          </el-form-item>
          <el-form-item label="楼层名称" prop="floorName">
            <el-input v-model.trim="listQuery.floorName" maxlength="16" placeholder="请输入楼层名称" clearable @clear="listQuery.floorName=undefined" @keyup.enter.native="onFilterChange">
              <i slot="suffix" class="el-input__icon el-icon-search" @click="onFilterChange"></i>
            </el-input>
          </el-form-item>
          <el-form-item label="房间名称" prop="roomName">
            <el-input v-model.trim="listQuery.roomName" maxlength="16" placeholder="请输入房间名称" clearable @clear="listQuery.roomName=undefined" @keyup.enter.native="onFilterChange">
              <i slot="suffix" class="el-input__icon el-icon-search" @click="onFilterChange"></i>
            </el-input>
          </el-form-item>
          <el-form-item label="房间编号" prop="roomNumber">
            <el-input v-model.trim="listQuery.roomNumber" maxlength="16" placeholder="请输入房间编号" clearable @clear="listQuery.roomNumber=undefined" @keyup.enter.native="onFilterChange">
              <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" maxlength="16" placeholder="请输入用户名称" clearable @clear="listQuery.username=undefined" @keyup.enter.native="onFilterChange">
              <i slot="suffix" class="el-input__icon el-icon-search" @click="onFilterChange"></i>
            </el-input>
          </el-form-item>

          <el-form-item label="开始时间范围" prop="beginTimeRange">
            <el-date-picker
                v-model="listQuery.beginTimeRange"
                :picker-options="beginTime"
                format="yyyy-MM-dd HH:mm"
                value-format="timestamp"
                type="datetimerange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
                @change="onFilterChange">
            </el-date-picker>
          </el-form-item>

          <el-form-item label-width="0">
            <el-button @click="onFilterChange" type="primary">查询</el-button>
            <el-button @click="resetFields" plain type="primary">重置</el-button>
            <el-button @click="onExport" plain type="primary">导出列表</el-button>
            <el-button v-if="!selectable" @click="onExportSelectable" plain type="primary">批量预览</el-button>
            <el-button v-if="selectable" @click="onExportDetail" plain type="primary">预览</el-button>
            <el-button v-if="selectable" @click="onExportSelectableCancel" plain type="primary">取消</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <form-clear :shrinkable="shrinkable" @clear="resetFields" @change="onExpansion"/>
    </el-row>

    <el-table :data="list" border stripe highlight-current-row ref="table" class="mt10" @sort-change="onSortChange" @row-click="onRowClick" @select-all="handleSelectionChange" @select="handleSelectionChange">
      <el-table-column v-if="selectable" type="selection" width="55" align="center"></el-table-column>
      <el-table-column type="index" :index="indexCompute" label="序号" align="center" fixed="left" width="60px"/>
      <el-table-column prop="name" label="任务名称" sortable="custom" align="center" fixed="left" min-width="120px"/>
      <el-table-column prop="buildingName" label="楼栋名称" sortable="custom" align="center" min-width="105px"/>
      <el-table-column prop="floorName" label="楼层名称" sortable="custom" align="center" min-width="105px"/>
      <el-table-column prop="roomName" label="房间名称" sortable="custom" align="center" min-width="105px"/>
      <el-table-column prop="roomNumber" label="房间编号" sortable="custom" align="center" min-width="105px"/>
      <el-table-column prop="username" label="用户名称" sortable="custom" align="center" min-width="120px"/>
      <el-table-column align="center" label="类型" width="75px" prop="type" sortable="custom">
        <template v-slot="scope">
          {{ typeList.find(item => item.id === scope.row.type).label }}
        </template>
      </el-table-column>
      <el-table-column prop="completed" label="状态" align="center" sortable="custom" width="100px">
        <template v-slot="scope">
          <text-label v-if="!scope.row.completed" type="danger">未巡检</text-label>
          <text-label v-else-if="scope.row.qualified" type="success">合格</text-label>
          <text-label v-else type="warning">不合格</text-label>
        </template>
      </el-table-column>
      <el-table-column align="center" label="本人完成" width="105px" prop="oneself" sortable="custom">
        <template v-slot="scope">
          {{ oneselfList.find(item => item.id === scope.row.oneself).label }}
        </template>
      </el-table-column>
      <el-table-column prop="beginTime" label="开始时间" sortable="custom" align="center" width="160px">
        <template v-slot="scope">{{ scope.row.beginTime | dateFormat }}</template>
      </el-table-column>
      <el-table-column prop="endTime" label="结束时间" sortable="custom" align="center" width="160px">
        <template v-slot="scope">{{ scope.row.endTime | dateFormat }}</template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="90px">
        <template v-slot="scope">
          <el-link type="primary" icon="el-icon-view">详情</el-link>
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="total" :page.sync="listQuery.page" :size.sync="listQuery.size" @change="onPageChange"/>

    <el-dialog title="导出" :visible.sync="exportVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="600px">
      <el-progress :text-inside="true" :stroke-width="24" :percentage="exportProgress" 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: "PatrolTaskRecord",
  data() {
    return {
      shrinkable: false, // 查询条件是否可以展开
      listQuery: { // 查询对象
        number: undefined, // 任务编号
        taskName: undefined, // 任务名称
        type: undefined, // 类型
        oneself: undefined, // 是否是本人完成
        buildingName: undefined, // 楼栋名称
        floorName: undefined, // 楼层名称
        roomName: undefined, // 房间名称
        roomNumber: undefined, // 房间编号
        username: undefined, // 执行用户名
        beginTimeRange: [], // 任务开始时间
        beginTimeStart: undefined,
        beginTimeEnd: undefined,
        order: undefined,
        page: 1,
        size: 10
      },
      beginTime: {
        shortcuts: [{
          text: '昨天',
          onClick(picker) {
            const start = new Date(dateFormat("yyyy/MM/dd 00:00", new Date() - 3600 * 1000 * 24)).getTime();
            const end = new Date(dateFormat("yyyy/MM/dd 23:59", new Date() - 3600 * 1000 * 24)).getTime();
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '今天',
          onClick(picker) {
            const start = new Date(dateFormat("yyyy/MM/dd 00:00", new Date())).getTime();
            const end = new Date(dateFormat("yyyy/MM/dd 23:59", new Date())).getTime();
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '明天',
          onClick(picker) {
            const start = new Date(dateFormat("yyyy/MM/dd 00:00", Date.now() + 3600 * 1000 * 24)).getTime();
            const end = new Date(dateFormat("yyyy/MM/dd 23:59", Date.now() + 3600 * 1000 * 24)).getTime();
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '后天',
          onClick(picker) {
            const start = new Date(dateFormat("yyyy/MM/dd 00:00", Date.now() + 3600 * 1000 * 24 * 2)).getTime();
            const end = new Date(dateFormat("yyyy/MM/dd 23:59", Date.now() + 3600 * 1000 * 24 * 2)).getTime();
            picker.$emit('pick', [start, end]);
          }
        }],
      },
      list: [], // 结果列表
      total: 0, // 总结果数量

      exportVisible: false, // 是否显示导出对话框
      exportData: [], // 导出数据
      exportPagination: { // 导出分页
        page: 1,
        size: 500,
      },
      exportProgress: 0, // 导出进度
      exportCancel: false, // 是否取消导出
      selectItem: undefined, // 选中的单条记录
      itemTypeList: [{id: 1, label: "选择"}, {id: 2, label: "数字"}, {id: 3, label: "文本"}, {id: 4, label: "拍照"}],
      typeList: [{id: 1, label: "日任务"}, {id: 2, label: "周任务"}, {id: 3, label: "月任务"}, {id: 4, label: "季任务"}, {id: 5, label: "半年任务"}, {id: 6, label: "年任务"}], // 任务类型列表
      oneselfList: [{id: null, label: "/"}, {id: false, label: "否"}, {id: true, label: "是"}],

      selectable: false, // 列表可选择
      selectItems: new Map() // 选中的多条记录
    }
  },

  watch: {
    'listQuery.beginTimeRange'(value) {
      if (value) {
        this.listQuery.beginTimeStart = value[0];
        this.listQuery.beginTimeEnd = value[1];
      } else {
        this.listQuery.beginTimeStart = undefined;
        this.listQuery.beginTimeEnd = undefined;
      }
    },
  },

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

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

  // keep-alive 显示界面时调用
  activated() {
    this.$refs["table"].doLayout();
    let number = this.$route.params.number
    if (number) {
      this.listQuery.number = number;
      this.getList();
    }
  },

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

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

    // 初始化查询条件
    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;
      })
    },

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

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

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

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

    // 排序改变
    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);
      this.selectItem = row;
      this.$router.push({path: '/patrol/task-record/detail', query: {taskId: this.selectItem.id, roomId: this.selectItem.roomId, userId: this.selectItem.userId}});
    },

    // 条件改变
    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/patrol/task/record/list/room", {params: this.listQuery, timeout: 0}).then(data => {
        this.list = data.list;
        this.total = data.total;
        this.$refs["table"].doLayout();

        if (this.selectable) {
          this.$nextTick(() => {
            this.list.forEach(item => {
              if (this.selectItems.has(`${item.id}-${item.roomId}-${item.userId}`)) {
                this.$refs["table"].toggleRowSelection(item, true);
              }
            });
          })
        }
      });
    },

    // 用户选中改变
    handleSelectionChange(selectList) {
      this.list.forEach(item => {
        const itemKey = `${item.id}-${item.roomId}-${item.userId}`;
        if (selectList.map(select => `${select.id}-${select.roomId}-${select.userId}`).includes(itemKey)) {
          this.selectItems.set(itemKey, item);
        } else {
          this.selectItems.delete(itemKey);
        }
      })
    },

    // 导出选择
    onExportSelectable() {
      this.selectable = true;
    },

    // 取消导出选择
    onExportSelectableCancel() {
      this.$refs["table"].clearSelection();
      this.selectable = false;
    },

    // 导出记录详情
    onExportDetail() {
      if (this.selectItems.size > 0) {
        const list = [];
        this.selectItems.forEach(value => {
          list.push({id: value.id, roomId: value.roomId, userId: value.userId})
        })
        this.$storage.setData("detail-list", list);
        this.$router.push({name: 'PatrolTaskRecordDetailList'});
      } else {
        this.$message.warning("至少选择一条记录");
      }
    },

    // 导出数据
    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/patrol/task/record/list/room", {params: {...this.listQuery, ...this.exportPagination}},false).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",
              "name",
              "buildingName",
              "floorName",
              "roomName",
              "roomNumber",
              "username",
              "type",
              "completed",
              "oneself",
              "qualified",
              "beginTime",
              "endTime"
            ];
            let data = this.exportData.map((value, index) => filterVal.map((key) => {
              if (key === "index") {
                return index + 1;
              } else if (key === "beginTime") {
                return dateFormat("yyyy-MM-dd HH:mm:ss", value[key]);
              } else if (key === "endTime") {
                return dateFormat("yyyy-MM-dd HH:mm:ss", value[key]);
              } else if (key === "type") {
                return this.typeList.find(item => item.id === value[key]).label;
              } else if (key === "oneself") {
                return this.oneselfList.find(item => item.id === value[key]).label;
              } else if (key === "completed") {
                return value[key] ? '已巡检' : '未巡检';
              } else if (key === "qualified") {
                return 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 {
  ::v-deep .el-checkbox__inner {
    border: 1px solid #000;
  }
}
</style>
