<template>
  <basic-container>
    <avue-crud :option="option" v-model:search="search" v-model:page="page" v-model="form" :table-loading="loading"
      :data="data" :permission="permissionList" :before-open="beforeOpen" ref="crud" @row-update="rowUpdate"
      @row-save="rowSave" @row-del="rowDel" @search-change="searchChange" @search-reset="searchReset"
      @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange"
      @refresh-change="refreshChange" @on-load="onLoad">

      <template #capitalName="{ row }">
        {{ row.powerStation.capitalName }}
      </template>
      <template #omProviderName="{ row }">
        {{ row.powerStation.omProviderName }}
      </template>
      <template #ownerName="{ row }">
        {{ row.powerStation.ownerName }}
      </template>
      <template #stationCode="{ row }">
        {{ row.powerStation.stationCode }}
      </template>
      <template #deviceBrand="{ row }">
        {{ row.device.brand==0?'锦浪':(row.device.brand==1?"爱思维":"固德威") }}
      </template>

      <template #deviceName="{ row }">
        <el-button
          type="primary"
          text
          @click.stop="toDevicePage(row)"
          >查看设备
        </el-button>
      </template>

      <template #menu-left>
        <el-form :model="search" label-width="auto">
          <el-form-item label="告警类型："  style="margin-bottom:0">
            <el-checkbox-group v-model="search.type">
              <el-checkbox value="1" name="type">
                故障
              </el-checkbox>
              <el-checkbox value="2" name="type">
                告警
              </el-checkbox>
              <el-checkbox value="3" name="type">
                提示
              </el-checkbox>
              <el-checkbox value="4" name="type">
                建议
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="处理状态：" style="margin-bottom:0">
            <el-checkbox-group v-model="search.status">
              <el-checkbox value="1" name="type">
                未确认
              </el-checkbox>
              <el-checkbox value="2" name="type">
                待处理
              </el-checkbox>
              <el-checkbox value="3" name="type">
                处理中
              </el-checkbox>
              <el-checkbox value="4" name="type">
                已处理
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </template>

      <template #menu-right style="vertical-align: bottom;">
        <el-button type="default" @click="handleClose">批量关闭
        </el-button>
        <el-button type="primary" @click="handleApplyError">申报故障
        </el-button>
        <el-button type="primary" @click="handleOperation" :disabled="selectionList.length != 1">转运维
        </el-button>
        <el-button type="primary" icon="el-icon-download" @click="handleExport">导 出
        </el-button>
      </template>

      <template #menu="scope">
        <el-button
          type="primary"
          text
          @click.stop="rowClose(scope.row)"
          >关闭
        </el-button>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove, batchClose,batchApplyError,turnMaintenance } from "@/api/nh/alarmInfo";
import option from "@/option/nh/alarmInfo";
import { mapGetters } from "vuex";
import { exportBlob } from "@/api/common";
import { getToken } from '@/utils/auth';
import { downloadXls } from "@/utils/util";
import { dateNow } from "@/utils/date";
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

export default {
  data() {
    return {
      form: {},
      query: {},
      search: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: option,
      data: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.alarmInfo_add, false),
        viewBtn: this.validData(this.permission.alarmInfo_view, false),
        delBtn: this.validData(this.permission.alarmInfo_delete, false),
        editBtn: this.validData(this.permission.alarmInfo_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
		handleOperation(){
			if (this.selectionList.length === 0) {
			  this.$message.warning("请选择至少一条数据");
			  return;
			}
			this.$confirm("是否确认将此电站生成运维工单?", {
			  confirmButtonText: "确定",
			  cancelButtonText: "取消",
			  type: "warning"
			}).then(() => {
				return turnMaintenance(this.ids);
			}).then(() => {
				this.onLoad(this.page);
				this.$message({
					type: "success",
					message: "操作成功!"
				});
				this.$refs.crud.toggleSelection();
			}).catch(()=>{});
		},
    rowSave(row, done, loading) {
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    toDevicePage(row){
      console.log(row);
      localStorage.setItem('power_station_detail_id',JSON.stringify(row.powerStation.id));
      localStorage.setItem('power_station_detail_device',2);
      
      this.$router.push('/nh/powerStationDetail');
    },
    rowClose(row) {
      this.$confirm("确定将选择记录关闭?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return batchClose(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleApplyError() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("是否确认将此电站申报故障?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return batchApplyError(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "申报成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleClose() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择记录关闭?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return batchClose(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "关闭成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleExport() {
      let downloadUrl = `/nh/alarmInfo/export-alarmInfo?${this.website.tokenHeader}=${getToken()}`;
      const {
      } = this.query;
      let values = {
      };
      this.$confirm("是否导出数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        NProgress.start();
        exportBlob(downloadUrl, values).then(res => {
          downloadXls(res.data, `设备告警信息表${dateNow()}.xlsx`);
          NProgress.done();
        })
      });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;

      const {
        model,stationName,orderNo,source,capitalName,omProviderName
      } = this.query;

      console.log("this.query")
      console.log(this.query)
      console.log("this.params")
      console.log(this.params)


      let values = {
        "closeStatus_equal":1,
        "model_equal": model,
        stationName,
        orderNo,
        source,
        capitalName,
        omProviderName
      };

      if(this.query.status){
        values["status_ignore"] = this.query.status.join(",");
      }
      if(this.query.type){
        values["type_ignore"] = this.query.type.join(",");
      }

      if(this.query.startTime){
        values["startTime_datege"] = this.query.startTime[0];
        values["startTime_datele"] = this.query.startTime[1];
      }

      getList(page.currentPage, page.pageSize, values).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style></style>
