<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 #menu-left>
        <el-button type="primary" @click="statusChange('')">全部 {{ statusCount["sum"] }}</el-button>
        <el-button type="primary" @click="statusChange(1)">正常 {{ statusCount["1"] }}</el-button>
        <el-button type="danger" @click="statusChange(2)">异常{{ statusCount["2"] }}</el-button>
        <el-button type="default" @click="statusChange(3)">离线{{ statusCount["3"] }}</el-button>
      </template>
      <template #menu-right>
        <el-button type="primary" @click="openServ" v-if="permission.bind_server" :disabled="selectionList.length < 1">绑定运维服务商</el-button>
        <el-button type="warning"
                   plain
                   icon="el-icon-download"
                   @click="handleExport">导 出
        </el-button>
      </template>
      <template #menu="{size,row,index}">
        <el-button @click="toMonitorPage(row,index)"
                  text
                  type="primary"
                  :size="size">监控数据</el-button>
      </template>

      <template #address="{ row }">
           {{ row.address }}
      </template>
      <template #actualCapacity="{ row }">
            {{ row.actualCapacity?(zoom(row.actualCapacity)):0.00 }}
      </template>
      <template #etd="{ row }">
            {{ row.entryStat.etd?(zoom(row.entryStat.etd)):0.00 }}
      </template>
      <template #etm="{ row }">
            {{ row.entryStat.etm?zoom(row.entryStat.etm):0.00 }}
      </template>
      <template #ety="{ row }">
            {{ row.entryStat.ety?zoom(row.entryStat.ety):0.00 }}
      </template>
      <template #eta="{ row }">
             {{ row.entryStat.eta?zoom(row.entryStat.eta):0.00 }}
      </template>
      <template #stationCode="{ row }">
        <el-link type="primary" @click="toDetailPage(row)">{{ row.stationCode }}</el-link>
      </template>
      <template #offlineDuring="{ row }">
             {{ convertDuring(row,3) }}
             <!-- {{ row.status!=1?row.errDuring:"" }} -->
      </template>
      <template #errorDuring="{ row }">
             {{ convertDuring(row,2) }}
             <!-- {{ row.status!=1?row.errDuring:"" }} -->
      </template>
    </avue-crud>
  </basic-container>
  <!--    绑定运维服务商-->
  <el-dialog title="绑定运维服务商"
             append-to-body
             v-model="servOpen"
             v-if="servOpen"
             :close-on-click-modal="false"
             :align-center="true"
             width="555px">
    <serviceList :selectionList="selectionList" @childSubmit="childSubmit"></serviceList>
  </el-dialog>
</template>

<script>
  import {getList, getDetail, add, update, remove,getStatusCount, bindingSite} from "@/api/nh/powerStation";
  import option from "@/option/nh/powerStation";
  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 func from '@/utils/func';
  import NProgress from 'nprogress';
  import 'nprogress/nprogress.css';
  import serviceList from "./components/serviceList.vue"

  export default {
    components:{serviceList},
    data() {
      return {
        form: {},
        query: {},
        search: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: option,
        data: [],
        statusCount: {},
        servOpen: false,
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.validData(this.permission.powerStation_add, false),
          viewBtn: this.validData(this.permission.powerStation_view, false),
          delBtn: this.validData(this.permission.powerStation_delete, false),
          editBtn: this.validData(this.permission.powerStation_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    created(){
      this.$route.meta.$keepAlive = true;
    },
    mounted(){
      this.initStatusCount();
    },
    methods: {
      convertDuring(item,type){
        let during="";
        if(item.status==1 && type==item.lastStatus){
          during += item.lastDuringStr;
        }
        if(item.status==type){
          during += item.errDuring;
        }
        return during;
      },
      zoom(num){
        return func.zoomNum(num,1,2);
      },
      toMonitorPage(row,index){
        localStorage.setItem('power_station_monitor_id',row.id);
        this.$router.push('/nh/inverterTree');
      },
      toDetailPage(row){
        localStorage.setItem('power_station_detail_id',JSON.stringify(row.id));
        this.$router.push('/nh/powerStationDetail');
      },
      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: "操作成功!"
            });
          });
      },
      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/powerStation/export-powerStation?${this.website.tokenHeader}=${getToken()}`;
        const {
            stationCode,
            stationName,
        } = this.query;
        let values = {
            stationCode_like: stationCode,
            stationName_like: stationName,
        };
        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);
      },
      statusChange(status) {
        this.query.status = status;
        console.log(this.page,this.query)
        this.onLoad(this.page, this.query);
      },
      initStatusCount(){
        getStatusCount().then(res => {
          const data = res.data.data;
          this.statusCount = data;
          let sum = 0;
          Object.values(data).forEach(value => {
            sum+=value;
          });
          this.statusCount.sum = sum;
        });
      },
      onLoad(page, params = {}) {
        this.loading = true;

        // const {
        //   stationCode,
        //   stationName,
        //   status
        // } = this.query;

        // let values = {
        //   stationCode_like: stationCode,
        //   stationName_like: stationName,
        // };
        if(this.query.offlineDuring){
          this.query.offlineDuring = this.query.offlineDuring;
        }
        if(this.query.errorDuring){
          this.query.errorDuring = this.query.errorDuring;
        }

        getList(page.currentPage, page.pageSize, this.query).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
      //打开绑定服务商
      openServ(){
        this.servOpen = true
      },
      childSubmit(e){
        this.servOpen = false;
        if(e == 'cancel'){
          return
        }
        this.onLoad(this.page);
        this.$refs.crud.toggleSelection();
      },

    }
  };
</script>

<style>
</style>
