<template>
  <el-row>
    <el-col :span="6">
      <div class="box">
        <el-scrollbar>
          <basic-container>
            <avue-tree ref="lazyTree" :option="treeOption" :data="treeData" @node-click="nodeClick" />
          </basic-container>
        </el-scrollbar>
      </div>
    </el-col>
    <el-col :span="18">
      <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" icon="el-icon-edit" plain v-if="permission.inefficientSetting_edit"
              @click="handleEdit">编辑
            </el-button>
            <el-button type="danger" icon="el-icon-delete" plain v-if="permission.inefficientSetting_delete"
              @click="handleDelete">删 除
            </el-button> -->

            <el-button type="warning"
                   plain
                   icon="el-icon-download"
                   @click="handleImport">导 入
          </el-button>
            <!-- <el-button type="warning"
                   plain
                   icon="el-icon-download"
                   @click="handleExport">导 出
        </el-button> -->
          </template>

          <template #citys="{ row }">
                {{ row.citys }}
          </template>

          <template #citys-search>
            <el-select v-model="search.citys">
              <el-option
                v-for="item in cityList"
                :key="item.cityName"
                :label="item.cityName"
                :value="item.cityName"
              />
            </el-select>
          </template>
        </avue-crud>
      </basic-container>
    </el-col>
  </el-row>

    <el-dialog title="低效配置导入" append-to-body v-model="uploadDialog" width="555px">
          <avue-form :option="excelOption" v-model="excelForm" :upload-after="uploadAfter">
            <template #excelTemplate>
              <el-button type="primary" @click="handleTemplate">
                点击下载<i class="el-icon-download el-icon--right"></i>
              </el-button>
            </template>
          </avue-form>
        </el-dialog>
</template>

<script>
import { getList, getDetail, add, update, remove } from "@/api/nh/inefficientSetting";
import { selectCityByProvince } from "@/api/base/region";
import option from "@/option/nh/inefficientSetting";
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 {
      uploadDialog: false,
      form: {},
      query: {},
      cityList:[],
      search: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: option,
      data: [],
      currentCapital:{},
      currentCapitalName:"广州越秀融资租赁有限公司",
      treeData:[{"id":"1","key":"1","parentId":"0","title":"广州越秀融资租赁有限公司","hasChildren":false},{"id":"2","key":2,"parentId":"0","title":"华融金融租赁股份有限公司","hasChildren":false}],
      treeOption: {
        nodeKey: 'id',
        addBtn: false,
        menu: false,
        size: 'small',
        props: {
          labelText: '标题',
          label: 'title',
          value: 'value',
          children: 'children',
        },
      },
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '模板上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '模板上传中，请稍等',
            span: 24,
            propsHttp: {
              res: 'data',
            },
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: '/nh/inefficientSetting/import-inefficientSetting',
          },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24,
          },
        ],
      },
    };
  },
  watch: {
    'search.province'() {
      console.log("query.province" + this.search.province)
      this.cityList = [];
      this.search.citys = "";
      if(this.search.province){
        selectCityByProvince(this.search.province).then(res=>{
        this.cityList = res.data.data;
      })
      }
    }
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.inefficientSetting_add, false),
        viewBtn: this.validData(this.permission.inefficientSetting_view, false),
        delBtn: this.validData(this.permission.inefficientSetting_delete, false),
        editBtn: this.validData(this.permission.inefficientSetting_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  mounted(){
    // console.log(this.$refs.lazyTree.data);
    // this.$refs.lazyTree.setCurrentNode("1")
    // this.currentCapital = this.$refs.lazyTree.data[0];
    // console.log(this.$refs.lazyTree.)
  },
  methods: {
    nodeClick(data) {
      console.log(data.title)
      this.currentCapitalName = data.title;
      this.onLoad(this.page);
    },
    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();
        });
    },
    handleEdit(row) {
      let that = this;
      if (this.selectionList.length != 1) {
        this.$message.warning("请选择一条数据进行编辑");
        return;
      }
      console.log(this.selectionList[0].id);

      that.form = this.selectionList[0];
      this.beforeOpen(function () {
        that.$refs.crud.rowEdit(that.form);
      }, "edit")

      // this.$confirm("确定将选择数据删除?", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "info"
      // })
      //   .then(() => {

      //   })
      //   .then(() => {
      //     this.onLoad(this.page);
      //     this.$message({
      //       type: "success",
      //       message: "操作成功!"
      //     });
      //     this.$refs.crud.toggleSelection();
      //   });
    },
    handleImport(){

      this.uploadDialog = true;
    },
    handleTemplate() {
      exportBlob(
        `/nh/inefficientSetting/export-template?${this.website.tokenHeader}=${getToken()}`
      ).then(res => {
        downloadXls(res.data, '低效电站数据模板.xlsx');
      });
    },
    uploadAfter(res, done, loading, column) {
      window.console.log(column);
      this.uploadDialog = false;
      this.refreshChange();
      done();
    },
    handleExport() {
      let downloadUrl = `/nh/inefficientSetting/export-inefficientSetting?${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 {
        planType,province,citys,recordType
      } = this.query;

      let values = {
        planType,recordType,province,citys,capitalName: this.currentCapitalName
      };

      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>
