<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="patrolTypeId">
            <el-select v-model="listQuery.patrolTypeId" placeholder="请选择巡检分类" clearable @change="onFilterChange">
              <el-option v-for="item in classifyList" :key="item.id" :label="item.typeName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="项目名称" prop="itemName">
            <el-input v-model.trim="listQuery.itemName" 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="isScore">
            <el-select v-model="listQuery.isScore" 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-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>
      <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" @row-dblclick="onUpdate">
      <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="itemNo" label="编号" sortable="custom" align="center" fixed="left" width="170px"/>
      <el-table-column prop="itemName" label="项目名称" sortable="custom" align="center" fixed="left" min-width="200px"/>
      <el-table-column prop="isRequired" label="是否必填" sortable="custom" align="center" width="106px">
         <template v-slot="scope">
          {{ whetherList.find(item => item.id === scope.row.isRequired).label }}
        </template>
      </el-table-column>
      <el-table-column prop="defaultValue" label="默认值" sortable="custom" align="center" min-width="120px"/>
      <el-table-column prop="isScore" label="是否参与评分" sortable="custom" align="center" width="136px">
         <template v-slot="scope">
          {{ whetherList.find(item => item.id === scope.row.isScore).label }}
        </template>
      </el-table-column>
      <el-table-column prop="patrolTypeName" label="类别名称" sortable="custom" align="center" width="130px"/>
      <!--      <el-table-column prop="deptName" label="部门名称" sortable="custom" align="center" width="130px"/>-->
      <!--      <el-table-column prop="username" label="人员名称" sortable="custom" align="center" width="130px"/>-->
      <el-table-column prop="remark" label="备注说明" sortable="custom" align="center" min-width="130px"/>
      <el-table-column label="操作" align="center" width="140px" fixed="right">
         <template v-slot="scope">
          <el-link type="primary" icon="el-icon-edit" @click="onUpdate(scope.row)">编辑</el-link>
          <el-link type="danger" icon="el-icon-delete" @click="onDelete(scope.row)" class="ml20">删除</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 FormClear from "@/components/FormClear";

export default {
  name: "inspectionPhoto",
  components: {FormClear},

  data() {
    return {
      shrinkable: false, // 查询条件是否可以展开
      listQuery: { // 查询对象
        itemName: undefined, // 检查项目名称，模糊匹配
        itemType: 4, // 检查项类别 1选择、2数字、3文本、4拍照
        isScore: undefined, // 是否参与评分 1是、2否
        patrolTypeId: undefined, // 巡检类别id
        order: undefined,
        page: 1,
        size: 10
      },

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

      classifyList: [], // 巡检类别列表

      whetherList: [{id: true, label: "是"}, {id: false, label: "否"}],
      itemTypeList: [{id: 1, label: "选择"}, {id: 2, label: "数字"}, {id: 3, label: "文本"}, {id: 4, label: "拍照"}],

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

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

      editing: false, // 表格编辑中

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

  watch: {},

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

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

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

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

  methods: {
    // 初始化数据
    initData() {
      this.$axios.get("/v1/check/item/type/list", {params: {size: 100}}, false).then(data => {
        this.classifyList = data.list;
      });
    },

    // 初始化事件
    initEvent() {
      this.$eventBus.$on("inspectionPhotoAdd", this.onAddComplete);
      this.$eventBus.$on("inspectionPhotoUpdate", this.onUpdateComplete);
    },

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

    // 初始化视图
    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();
    },

    // 添加
    onAdd() {
      this.onCancel();
      this.$router.push({path: '/inspection/photo/add'})
    },

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

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

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

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

    // 更新
    onUpdate(item) {
      this.$router.push({path: '/inspection/photo/edit', query: {id: item.id}});
    },

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

    // 删除
    onDelete(item) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.$axios.delete(`/v1/check/item/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/check/item/list", {params: this.listQuery}).then(data => {
        this.list = data.list;
        this.total = data.total;
        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/check/item/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",
              "itemNo",
              "itemName",
              "itemType",
              "isRequired",
              "defaultValue",
              "isScore",
              "patrolTypeName",
              "deptName",
              "username",
              "remark"
            ];
            let data = this.exportData.map((value, index) => filterVal.map((key) => {
              if (key === "index") {
                return index + 1;
              } else if (key === "itemType") {
                return this.itemTypeList.find(item => item.id === Number(value[key])).label;
              } else if (key === "isRequired" || key === "isScore") {
                return this.whetherList.find(item => item.id === 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>
