<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="pointNo">
            <el-input v-model.trim="listQuery.pointNo" maxlength="16" placeholder="请输入点编号" clearable @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="pointName">
            <el-input v-model.trim="listQuery.pointName" maxlength="16" placeholder="请输入点名称" clearable @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="taskStatus">
            <el-select v-model="listQuery.taskStatus" placeholder="请选择巡检状态" clearable @change="onFilterChange">
              <el-option
                  v-for="item in taskStatusList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否合格" prop="isQualified">
            <el-select v-model="listQuery.isQualified" placeholder="请选择是否合格" clearable @change="onFilterChange">
              <el-option
                  v-for="item in qualifiedList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="我的记录" prop="isMySelf">
            <el-select v-model="listQuery.isMySelf" placeholder="仅显示我的记录" clearable @change="onFilterChange">
              <el-option
                  v-for="item in whetherList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="巡检计划" prop="planId">
            <el-select v-model="listQuery.planId" placeholder="请选择巡检计划" clearable @change="onFilterChange">
              <el-option
                  v-for="item in planList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="检查路线" prop="routeId">
            <el-select v-model="listQuery.routeId" placeholder="请选择检查路线" clearable @change="onFilterChange">
              <el-option
                  v-for="item in routeList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="部门" prop="deptId">
            <el-select v-model="listQuery.deptId" placeholder="请选择部门" clearable @change="onFilterChange">
              <el-option
                  v-for="item in deptList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围" prop="dateRange">
            <el-date-picker
                v-model="listQuery.dateRange"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="daterange"
                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-form-item>
        </el-form>
      </el-col>
      <form-clear :shrinkable="shrinkable" @clear="resetFields" @change="onExpansion"/>
    </el-row>
    <el-row v-if="false">
      <el-button @click="onAdd" type="primary">添加</el-button>
      <el-button v-if="!editing" @click="onEdit" plain type="primary">编辑</el-button>
      <el-button v-if="editing" @click="onDeleteSelect" type="danger">删除</el-button>
      <el-button v-if="editing" @click="onCancel" plain>取消</el-button>
    </el-row>
    <el-table :data="list" border stripe highlight-current-row ref="table" class="mt10" @sort-change="onSortChange" @selection-change="onTableSelectionChange" @row-click="onRowClick">
      <el-table-column v-if="editing" type="selection" width="55" fixed></el-table-column>
      <el-table-column type="index" :index="indexCompute" label="序号" align="center" fixed="left" width="60px"/>
      <el-table-column prop="recordNo" label="记录单编号" sortable="custom" align="center" width="170px"/>
      <el-table-column prop="planNo" label="计划编号" sortable="custom" align="center" width="170px"/>
      <el-table-column prop="planName" label="计划名称" sortable="custom" align="center" min-width="130px"/>
      <el-table-column prop="routeName" label="检查路线名称" sortable="custom" align="center" min-width="130px"/>
      <el-table-column prop="pointNo" label="点编号" sortable="custom" align="center" width="170px"/>
      <el-table-column prop="pointName" label="点名称" sortable="custom" align="center" min-width="170px"/>
      <el-table-column prop="planStartTime" label="计划开始时间" sortable="custom" align="center" width="160px"></el-table-column>
      <el-table-column prop="planEndTime" label="计划结束时间" sortable="custom" align="center" width="160px"></el-table-column>
      <el-table-column prop="patrolTime" label="实际巡检时间" sortable="custom" align="center" width="160px"></el-table-column>
      <el-table-column prop="finishStatus" label="执行状态" sortable="custom" align="center" width="102px">
         <template v-slot="scope">
          {{ taskStatusList.find(status => status.id === Number(scope.row.finishStatus)).label }}
        </template>
      </el-table-column>
      <el-table-column prop="deptName" label="部门名称" sortable="custom" align="center" min-width="130px"/>
      <el-table-column prop="userName" label="人员名称" sortable="custom" align="center" min-width="130px"/>
      <el-table-column label="操作" align="center" width="90px">
         <template v-slot="scope">
          <el-link type="primary" icon="el-icon-view" @click="onDetail(scope.row)">详情</el-link>
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="total" :page.sync="listQuery.curPage" :size.sync="listQuery.pageSize" @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>

    <!--    <dialog-edit v-if="editDialogVisible" :visible.sync="editDialogVisible" :data="selectItem" @add="onAddComplete" @update="onUpdateComplete"/>-->
    <!--    <dialog-detail v-if="detailDialogVisible" :visible.sync="detailDialogVisible" :data="selectItem"/>-->
  </div>
</template>

<script>
import FormClear from "@/components/FormClear";
import Pagination from "@/components/Pagination"
// import DialogEdit from "./dialogEdit";
// import DialogDetail from "./dialogDetail";
import {dateFormat} from "@/utils/dateUtil"
import {toLine} from "@/utils/stringUtil";


export default {
  name: "Record",
  components: {FormClear, Pagination}, // ,DialogEdit, DialogDetail

  data() {

    const defaultStartTime = dateFormat("yyyy-MM-dd 00:00:00", new Date());
    const defaultEndTime = dateFormat("yyyy-MM-dd 23:59:59", new Date());

    return {
      shrinkable: false, // 查询条件是否可以展开
      listQuery: { // 查询对象
        pointNo: undefined, // 点编号
        pointName: undefined, // 点名称
        taskStatus: undefined, // 巡检状态 1按时完成、2尚未巡检（正常时效内未检）、3超时漏检（超过时效后未检）、4提前完成、5延时完成
        isQualified: undefined, // 是否合格 1合格、2不合格
        isMySelf: undefined, // 是否只显示自己的巡检记录 1是、2否
        planId: undefined, // 计划id
        routeId: undefined, // 路线id
        deptId: undefined, // 部门id
        dateRange: [defaultStartTime, defaultEndTime], // 时间范围
        startTime: defaultStartTime,
        endTime: defaultEndTime,
        order: undefined,
        orderField: undefined,
        curPage: 1,
        pageSize: 10
      },

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

      taskStatusList: [{id: 1, label: "按时完成"}, {id: 2, label: "尚未巡检"}, {id: 3, label: "超时漏检"}, {id: 4, label: "提前完成"}, {id: 5, label: "延时完成"}],
      qualifiedList: [{id: 1, label: "合格"}, {id: 2, label: "不合格"}],
      whetherList: [{id: 1, label: "是"}, {id: 2, label: "否"}],
      planList: [],
      routeList: [],
      deptList: [],
      defaultStartTime,
      defaultEndTime,

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

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

      editing: false, // 表格编辑中

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

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

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

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

  // keep-alive 显示界面时调用
  activated() {
  },

  // 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.orderField) {
            this.$refs.table.sort(query.orderField, query.order === "asc" ? "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.curPage - 1) * this.listQuery.pageSize;
    },

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

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

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

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

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

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

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

    // 详情
    onDetail(item) {
      this.selectItem = item;
      this.detailDialogVisible = true;
    },

    // 更新
    onUpdate(item) {
      this.selectItem = item;
      this.editDialogVisible = true;
    },

    // 更新完成
    onUpdateComplete() {
      this.onFilterChange();
    },

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

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

    // 排序改变
    onSortChange({prop, order}) {
      if (order === "ascending") {
        this.listQuery.orderField = toLine(prop);
        this.listQuery.order = "asc";
      } else if (order === "descending") {
        this.listQuery.orderField = toLine(prop);
        this.listQuery.order = "desc";
      } else {
        this.listQuery.orderField = undefined;
        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.curPage = 1;
      this.getList();
    },

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

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

      this.$axios.get("/check/patrolRecord/list", {params: this.listQuery}).then(data => {
        this.list = data.list;
        this.total = data.totalCount;
        this.onCancel();
      });
    },

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

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

    // 获取数据并导出
    getExportData() {
      if (!this.exportCancel) {
        this.$axios.get("/check/patrolRecord/list", {params: {...this.listQuery, ...this.exportPagination}}).then(data => {
          this.exportPagination.curPage++;
          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",
              "recordNo",
              "planNo",
              "planName",
              "routeName",
              "pointNo",
              "pointName",
              "planStartTime",
              "planEndTime",
              "patrolTime",
              "finishStatus",
              "deptName",
              "userName",
            ];
            let data = this.exportData.map((value, index) => filterVal.map((key) => {
              if (key === "index") {
                return index + 1;
              } else if (key === "finishStatus") {
                return this.taskStatusList.find(status => status.id === Number(value[key])).label;
              } else {
                return value[key];
              }
            }));
            import('@/utils/Export2Excel').then(excel => {
              excel.export_json_to_excel({
                header: tHeader, // 表头 必填
                data, // 具体数据 必填
                filename: '巡检记录列表', // 非必填
                autoWidth: true, // 非必填
                bookType: 'xlsx' // 非必填
              })
            })
          }
        });
      }
    }
  }
}
</script>

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

}
</style>
