<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="name">
            <el-input v-model.trim="listQuery.name" maxlength="16" placeholder="请输入名称" @clear="listQuery.name=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="disabled">
            <el-select v-model="listQuery.disabled" clearable placeholder="请选择" @change="onFilterChange" @clear="listQuery.disabled=undefined">
              <el-option v-for="item in disableStatusList" :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="runModel">
            <el-select v-model="listQuery.runModel" clearable placeholder="请选择" @change="onFilterChange" @clear="listQuery.runModel=undefined">
              <el-option v-for="item in runModelList" :key="item.id" :label="item.label" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="创建人" prop="username">
            <el-input v-model.trim="listQuery.username" clearable maxlength="16" placeholder="请输入创建人" @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="executor">
            <el-input v-model.trim="listQuery.executor" clearable maxlength="16" placeholder="请输入执行人" @clear="listQuery.executor=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="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="timestamp"-->
          <!--                @change="onFilterChange">-->
          <!--            </el-date-picker>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="任务执行时间范围" prop="timeRange">-->
          <!--            <el-time-picker-->
          <!--                v-model="listQuery.timeRange"-->
          <!--                :default-time="['00:00:00', '23:59:59']"-->
          <!--                end-placeholder="结束时间"-->
          <!--                range-separator="-"-->
          <!--                start-placeholder="开始时间"-->
          <!--                type="timerange"-->
          <!--                value-format="timestamp"-->
          <!--                @change="onFilterChange">-->
          <!--            </el-time-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="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-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="100px" prop="name" sortable="custom"/>
      <el-table-column align="center" label="检查路线" min-width="120px" prop="routeName" sortable="custom"/>
      <el-table-column prop="username" label="创建人" sortable="custom" align="center" width="100px"/>
      <el-table-column prop="disabled" label="是否禁用" sortable="custom" align="center" width="105px">
         <template v-slot="scope">
          <el-switch v-model="scope.row.disabled" @click.native.stop @change="onChangeEnabled(scope.row, scope.row.disabled)"></el-switch>
        </template>
      </el-table-column>
      <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 align="center" label="执行模式" width="105px" prop="runModel" sortable="custom">
         <template v-slot="scope">
          {{ runModelList.find(item => item.id === scope.row.runModel).label }}
        </template>
      </el-table-column>

      <el-table-column align="center" label="计划" min-width="100px">
         <template v-slot="scope">
          <div v-if="scope.row.type===typeList[0].id">/</div>
          <div v-if="scope.row.type===typeList[1].id">{{ JSON.parse(scope.row.weeks).map(week => weekList.find(item => item.id === week).label).join("、") }}</div>
          <div v-if="scope.row.type===typeList[2].id">{{ JSON.parse(scope.row.months).join("、") }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="执行人" min-width="80px">
         <template v-slot="scope">{{ scope.row.executors.join("、") }}</template>
      </el-table-column>
      <el-table-column align="center" label="备注" min-width="80px" prop="remark"/>
      <el-table-column align="center" label="计划执行日期" prop="beginDate" sortable="custom" width="180px">
         <template v-slot="scope">
          <div>{{ dateFormat('yyyy-MM-dd ', scope.row.beginDate, '') }}/{{ dateFormat(' yyyy-MM-dd', scope.row.endDate, '-') }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="任务执行时间" prop="beginTime" sortable="custom" width="130px">
         <template v-slot="scope">{{ dateFormat('HH:mm ', scope.row.beginTime) }}/{{ dateFormat(' HH:mm', scope.row.endTime) }}</template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="150px">
         <template v-slot="scope">
          <el-link icon="el-icon-edit" type="primary" @click="onUpdate(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>
  </div>
</template>

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

export default {
  name: "UpkeepPlan",
  data() {
    return {
      shrinkable: false, // 查询条件是否可以展开
      listQuery: { // 查询对象
        name: undefined, // 名称
        disabled: undefined, // 是否禁用
        type: undefined, // 类型
        runModel: undefined, // 执行模式
        username: undefined, // 创建人
        executor: undefined, // 执行人
        // dateRange: [undefined, undefined], // 计划执行开始日期
        // dateStart: undefined,
        // dateEnd: undefined,
        // timeRange: [undefined, undefined], // 任务执行开始时间
        // timeStart: undefined,
        // timeEnd: undefined,
        order: undefined,
        page: 1,
        size: 10
      },


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

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

      editing: false, // 表格编辑中
      selectIds: undefined, // 选中多条记录的id

      typeList: [{id: 1, label: "日计划"}, {id: 2, label: "周计划"}, {id: 3, label: "月计划"}], //计划类型列表
      runModelList: [{id: 1, label: "其中一人"}, {id: 2, label: "每人分别"}], //计划执行模式列表
      disableStatusList: [{id: false, label: "启用"}, {id: true, label: "禁用"}],
      weekList: [{id: 1, label: "周一"}, {id: 2, label: "周二"}, {id: 3, label: "周三"}, {id: 4, label: "周四"}, {id: 5, label: "周五"}, {id: 6, label: "周六"}, {id: 7, label: "周日"}], // 周计划列表
    }
  },

  watch: {
    // 'listQuery.dateRange'(value) {
    //   if (value) {
    //     this.listQuery.dateStart = value[0];
    //     this.listQuery.dateEnd = value[1];
    //   } else {
    //     this.listQuery.dateStart = undefined;
    //     this.listQuery.dateEnd = undefined;
    //   }
    // },
    // 'listQuery.timeRange'(value) {
    //   if (value) {
    //     this.listQuery.timeStart = value[0];
    //     this.listQuery.timeEnd = value[1];
    //   } else {
    //     this.listQuery.timeStart = undefined;
    //     this.listQuery.timeEnd = undefined;
    //   }
    // },
  },

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

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

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

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

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

    // 初始化事件
    initEvent() {
      this.$eventBus.$on("UpkeepPlanAdd", this.onAddComplete);
      this.$eventBus.$on("UpkeepPlanUpdate", 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.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();
    },

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

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

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

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

    // 禁用改变状态
    onChangeEnabled(data, val) {
      this.$confirm('此操作将 ' + (val ? '禁用 ' : '启用 ') + data.name + '计划, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.put("/v1/upkeep/plan/update/status", {id: data.id, disabled: data.disabled}).then(() => {
          this.$message.success("更新成功！");
        }).catch(() => {
          data.disabled = !data.disabled
        })
      }).catch(() => {
        data.disabled = !data.disabled
      })
    },

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

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

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

    // 删除
    onDelete(item) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.$axios.delete(`/v1/upkeep/plan/delete/${item.id}`).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/upkeep/plan/list", {params: this.listQuery}).then(data => {
        this.list = data.list;
        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/upkeep/plan/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",
              "routeName",
              "username",
              "number",
              "name",
              "disabled",
              "type",
              "runModel",
              "weeks",
              "months",
              "remark",
              "executors",
              "beginDate",
              "endDate",
              "beginTime",
              "endTime",
            ];
            let data = this.exportData.map((value, index) => filterVal.map((key) => {
              if (key === "index") {
                return index + 1;
              } else if (key === "disabled") {
                return this.disableStatusList.find(item => item.id === value[key]).label;
              } else if (key === "type") {
                return this.typeList.find(item => item.id === value[key]).label;
              } else if (key === "runModel") {
                return this.runModelList.find(item => item.id === value[key]).label;
              } else if (key === "weeks" && value[key]) {
                return JSON.parse(value[key]).map(week => this.weekList.find(item => item.id === week).label).join("、");
              } else if (key === "months" && value[key]) {
                return JSON.parse(value[key]).join("、");
              } else if (key === "executors") {
                return value[key].join("、");
              } else if (key === "beginDate") {
                return dateFormat("yyyy-MM-dd", value[key]);
              } else if (key === "endDate") {
                return dateFormat("yyyy-MM-dd", value[key]);
              } else if (key === "beginTime") {
                return dateFormat("HH:mm:ss", value[key]);
              } else if (key === "endTime") {
                return dateFormat("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>


