<template>
  <div>

    <div class="div_btn">

      <el-button style="float:left"
                 class="diy-button--add"
                 size="small"
                 @click="handleAdd">新增楼栋</el-button>
      <div class="btn_upload"
           v-if="showImportBtn">
        <el-button style=";margin-left:10px"
                   class="diy-button--export"
                   size="small"
                   @click="handleExportModule('building')">下载楼栋模板</el-button>

        <el-upload style=""
                   ref="upload_building"
                   :multiple='false'
                   :show-file-list='false'
                   :before-upload="((file)=>{beforeUpload(file, 'building')})"
                   action=""
                   accept=".xls,.xlsx"
                   :http-request="(()=>{uploadFile( 'building')})">
          <el-button style="margin-left:10px"
                     size="small"
                     class="diy-button--delete">导入楼栋数据</el-button>
        </el-upload>
        <el-button style=";margin-left:10px"
                   class="diy-button--export"
                   size="small"
                   @click="handleExportModule('room')">下载房屋模板</el-button>

        <el-upload style=""
                   ref="upload_room"
                   :multiple='false'
                   :show-file-list='false'
                   :before-upload="((file)=>{beforeUpload(file, 'room')})"
                   action=""
                   accept=".xls,.xlsx"
                   :http-request="(()=>{uploadFile( 'room')})">
          <el-button style="margin-left:10px"
                     size="small"
                     class="diy-button--delete">导入房屋数据</el-button>
        </el-upload>
      </div>
      <el-button style="float:left;margin-left:10px"
                 class="diy-button--reset"
                 size="small"
                 @click="handleExport">导出</el-button>
      <el-button style="float:left;margin-left:10px"
                 class="diy-button--more"
                 size="small"
                 @click="deleteBatch">批量删除</el-button>
      <el-button style=";margin-left:10px"
                 class="diy-button--export"
                 size="small"
                 :disabled="yihuyidangDisabled"
                 @click="handleExportYihuyidang()">导出一户一档</el-button>
      <el-button size="small" v-if="displayedBaobiaoBtn"
              class="diy-button--add"
              @click="reportForm">智能填报</el-button>
    </div>

    <div class="div_table_item">
      <el-table ref="ref_table"
                :data="tableData"
                :header-cell-style="{background:'#2195FE',color:'#FFFFFF'}"
                border
                @sort-change="handleSortOrderChange"
                :height="tableHeight"
                v-loading="tableLoading"
                style="width: 100%"
                @select-all="selectAll"
                @selection-change="selectionChange">
        <el-table-column type="selection"
                         :selectable="checkSelect"
                         width="55">
        </el-table-column>
        <el-table-column fixed="left"
                         width="55"
                         type="index"
                         label="序号"
                         :index="indexMethod">
        </el-table-column>

        <el-table-column prop="buildingName"
                         fixed="left"
                         label="楼栋名称"
                         min-width="180">
          <template slot-scope="scope">
            <a class="name-a"
               @click="handleToNextLevel(scope.row)">
              {{ scope.row.buildingName }}
            </a>
          </template>
        </el-table-column>
        <el-table-column prop="neighborHoodName"
                         label="所属小区"
                         min-width="160">
        </el-table-column>
        <el-table-column prop="buildingType"
                         label="楼栋类型"
                         min-width="110">
        </el-table-column>
        <el-table-column prop="buildingLeaderName"
                         label="楼长姓名"
                         min-width="90">
        </el-table-column>
        <el-table-column prop="buildingLeaderMobile"
                         label="楼长电话"
                         min-width="110">
        </el-table-column>
        <el-table-column prop="totalUnitNum"
                         label="单元数">
        </el-table-column>
        <el-table-column prop="totalFloorNum"
                         label="层数">
        </el-table-column>
        <el-table-column prop="realTotalHouseNum"
                         label="实际录入总数">
        </el-table-column>
        <el-table-column prop="totalHouseNum"
                         label="总户数">
        </el-table-column>
        <el-table-column prop="sort"
                         sortable="custom"
                         min-width="140"
                         label="排序">
          <template slot-scope="scope">
            <div @click="handleEditSort(scope.row)">
              <span v-if="!scope.row.isChange">{{scope.row.sort}}</span>
              <el-input-number v-else
                               @change="handleChangeSort(scope.row)"
                               v-model="scope.row.sort"
                               class="item_width_4"
                               :precision="2"
                               size="small"
                               :min="0"
                               :max="9999"
                               label="描述文字"></el-input-number>
            </div>

          </template>
        </el-table-column>

        <el-table-column label="操作"
                         fixed="right"
                         width="140"
                         header-align="center"
                         align="center"
                         class="operate">
          <template slot-scope="scope">

            <el-button type="text"
                       class="div-table-button--detail"
                       size="small"
                       @click="handleDetail(scope.row)">查看</el-button>
            <el-button v-if="scope.row.showBtn"
                       type="text"
                       class="div-table-button--edit"
                       size="small"
                       @click="handleEdit(scope.row)">修改</el-button>

            <el-button v-if="scope.row.showBtn"
                       type="text"
                       class="div-table-button--delete"
                       size="small"
                       @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div>
        <el-pagination @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page.sync="pageNo"
                       :page-sizes="[20, 50, 100, 200]"
                       :page-size="pageSize"
                       layout="sizes, prev, pager, next, total"
                       :total="total">
        </el-pagination>
      </div>

    </div>

    <!-- 修改弹出框 -->
    <el-dialog :visible.sync="formShow"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :title="formTitle"
               top="5vh"
               width="900px"
               class="dialog-h"
               @closed="diaClose">
      <build-form ref="ref_form"
                  @dialogCancle="addFormCancle"
                  @dialogOk="addFormOk"></build-form>
    </el-dialog>

    <baobiao ref="baobiao" />
  </div>
</template>

<script>

import BuildForm from './buildForm'

import { requestPost } from "@/js/dai/request";
import { mapGetters } from 'vuex'
import { Loading } from 'element-ui' // 引入Loading服务
import baobiao from "@/views/modules/cpts/baobiao";

let loading // 加载动画
export default {
  data () {
    return {
      importBuildingLoading: false,
      importRoomLoading: false,
      total: 0,
      pageSize: 20,
      pageNo: 0,
      sortType: 'asc',//asc：正，desc：倒
      tableLoading: true,
      tableData: [],

      agencyObj: {},//树所选的小区对象

      validTableDataNum: 0,//有效的数据数量，即有权限操作的数据数量
      selection: [],


      //form相关
      formShow: false,
      formTitle: '新增楼栋',

      yihuyidangDisabled: false,

      displayedBaobiaoBtn: false,
    }
  },
  components: {
    baobiao,
    BuildForm
  },
  async mounted() {
    this.displayedBaobiaoBtn = await this.$refs.baobiao.existsTemplate({
      elseParams: {
        categoryKeys:['house_info'], categoryKey: 'house_info',
      }
    });
  },
  computed: {
    tableHeight () {

      return this.$store.state.inIframe ? this.clientHeight - 425 + this.iframeHeight : this.clientHeight - 425

    },

    ...mapGetters(['clientHeight', 'iframeHeight'])
  },
  methods: {
    reportForm(){
      let paramMap = {
        pageSize: this.pageSize,
        pageNo: this.pageNo,
        level: this.agencyObj.level,
        id: this.agencyObj.id,
        ownerName: this.ownerName,
        ownerPhone: this.ownerPhone,
        rentFlag: this.rentFlag,
        purpose: this.purpose,
        remark: this.remark,
        sortType: this.sortType,
        updateStartDate: this.updateStartDate,
        updateEndDate: this.updateEndDate,
      };
      this.$refs.baobiao.init({
        elseParams: {
          categoryKeys:['house_info'], categoryKey: 'house_info', paramMap
        }
      })
    },

    indexMethod (index) {
      return index + 1;
    },
    handleSortOrderChange (value) {
      console.log(value.column, value.prop, value.order)
      this.sortType = value.order === 'ascending' ? 'asc' : 'desc'
      this.loadTable()

    },
    // handleChangeSort(row){

    // },

    handleEditSort (row) {
      if (!row.isChange) {
        row.isChange = true
      }

    },


    async handleChangeSort (row, index) {
      // row.isChange = false
      console.log(row.sort)
      let params = {
        id: row.buildingId,
        sort: row.sort,
        type: 'building',
      }

      let url = '/gov/org/house/update-sort'

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        // this.$message({
        //   type: 'success',
        //   message: '操作成功'
        // })


      } else {

        this.$message.error(msg)
      }


    },

    checkSelect (row, index) {
      let isChecked = false;
      if (row.showBtn) { // 判断里面是否存在某个参数
        isChecked = true
      } else {
        isChecked = false
      }
      return isChecked
    },

    async loadTable (fromTree, treeObj) {
      this.tableLoading = true
      if (fromTree) {
        this.sortType = 'asc'

        this.agencyObj = treeObj

        // if (this.agencyObj.pid === this.staffAgencyId) {//如果所选树的父级组织id和登录人员id相同，有权限
        //   this.showImportBtn = true
        // } else {
        //   this.showImportBtn = false
        // }
      }


      console.log(this.agencyObj)
      const url = "/gov/org/building/buildinglist"
      let params = {
        pageSize: this.pageSize,
        pageNo: this.pageNo,
        sortType: this.sortType,
        neighborHoodId: this.agencyObj.id
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        this.validTableDataNum = 0
        this.total = data.total
        data.list.forEach(item => {
          item.sort = parseInt(item.sort) || 0;
          item.sort = item.sort.toFixed(2)
          item.isChange = false
          if (item.agencyId === this.staffAgencyId) {
            item.showBtn = true
            this.validTableDataNum++
          } else {
            item.showBtn = false
          }

        });
        this.tableData = data.list
      } else {
        this.$message.error(msg)
      }
      this.tableLoading = false
    },

    diaClose () {
      this.$refs.ref_form.resetData()
      this.formShow = false
    },

    async handleDetail (row) {
      this.formTitle = '楼栋详情'
      this.formShow = true
      const _data = await this.detail(row)
      this.$nextTick(() => {
        this.$refs.ref_form.initForm('detail', _data, this.agencyObj)
      })
    },

    handleAdd () {
      this.formTitle = '新增楼栋'
      this.formShow = true
      this.$nextTick(() => {
        this.$refs.ref_form.initForm('add', null, this.agencyObj)
      })
    },

    async handleEdit (row) {
      this.formTitle = '修改楼栋'
      this.formShow = true
      const _data = await this.detail(row)
      this.$nextTick(() => {
        this.$refs.ref_form.initForm('edit', _data, this.agencyObj)
      })
    },

    handleToNextLevel (row) {
      this.$emit('toNextLevel', row, 'building')
    },

    addFormCancle () {
      this.formShow = false
    },
    addFormOk () {
      this.formShow = false
      this.loadTable()
      this.$emit('refreshTree')
    },


    deleteBatch () {
      if (this.selection.length > 0) {
        this.$confirm("确认删除选择的楼栋?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.deleteCommunityBatch()
          })
          .catch(err => {
            if (err == "cancel") {
              // this.$message({
              //   type: "info",
              //   message: "已取消删除"
              // });
            }

          });
      } else {
        this.$message.warning('请先选择要删除的楼栋')
      }
    },
    selectAll (selection) {
      this.selection = selection

    },
    selectionChange (selection) {
      this.selection = selection

    },
    async handleDelete (row) {

      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteBuild(row)
        })
        .catch(err => {
          if (err == "cancel") {
            // this.$message({
            //   type: "info",
            //   message: "已取消删除"
            // });
          }

        });


    },

    async deleteCommunityBatch () {
      let ids = []
      this.selection.forEach(element => {

        ids.push(element.buildingId)
      });

      const url = "/gov/org/house/delete"

      let params = {
        type: 'building',
        ids: ids
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        this.$message({
          type: "success",
          message: "删除成功"
        });
        this.$emit('refreshTree')
        this.loadTable()
      } else if (code > 8000) {
        this.$message({
          showClose: true,
          message: msg,
          duration: 0
        })
        this.$emit('refreshTree')
        this.loadTable()
      } else {
        this.$message.error(msg)
      }
    },

    async deleteBuild (row) {
      const url = "/gov/org/building/buildingdel"

      let params = {
        buildingId: row.buildingId
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        this.$message({
          type: "success",
          message: "删除成功"
        });
        this.$emit('refreshTree')
        this.loadTable()
      } else {
        this.$message.error(msg)
      }
    },
    async detail (row) {
      const url = "/gov/org/houseInformation/getBuildingDetail/" + row.buildingId


      const { data, code, msg } = await requestPost(url)

      if (code === 0) {
        return data
      } else {
        this.$message.error(msg)
      }
    },

    //导出表格
    async handleExport () {
      let title = this.agencyObj.label
      title = title + '—楼栋列表'

      const url = "/gov/org/building/exportbuildinginfo"
      let params = {

        neighborHoodId: this.agencyObj.id
      }

      app.ajax.exportFilePost(
        url,
        params,
        (data, rspMsg) => {

          this.download(data, title + '.xls')
        },
        (rspMsg, data) => {
          this.$message.error(rspMsg);
        }
      );

    },

    // 下载文件
    download (data, fileName) {
      if (!data) {
        return
      }

      var csvData = new Blob([data])

      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(csvData, fileName);
      }
      // for Non-IE (chrome, firefox etc.)
      else {
        var a = document.createElement('a');
        document.body.appendChild(a);
        a.style = 'display: none';
        var url = window.URL.createObjectURL(csvData);
        a.href = url;
        a.download = fileName;
        a.click();
        a.remove();
        window.URL.revokeObjectURL(url);
      }

    },

    handleExportModule (type) {

      let title = ''
      let url = ""
      if (type === 'building') {
        title = '楼栋导入模板'
        url = '/gov/org/building/exporttemplate'

      } else if (type === 'room') {
        title = '房屋导入模板'
        url = '/gov/org/house/exporttemplate'
      }


      let params = {}

      app.ajax.exportFilePost(
        url,
        params,
        (data, rspMsg) => {

          this.download(data, title + '.xls')
        },
        (rspMsg, data) => {
          this.$message.error(rspMsg);
        }
      );
    },

    //导出一户一档
    handleExportYihuyidang () {
      this.yihuyidangDisabled = true
      let title = this.agencyObj.label
      title = title + '-一户一档'
      let url = "/gov/org/house/exportHouseUser"


      let params = {
        agencyId: '',
        gridId: '',
        ownerName: this.ownerName,
        ownerPhone: this.ownerPhone,
        rentFlag: this.rentFlag,
        purpose: this.purpose,
        remark: this.remark,
        updateStartDate: this.updateStartDate,
        updateEndDate: this.updateEndDate,
        neighborHoodId: this.agencyObj.id

      }


      app.ajax.exportFilePost(
        url,
        params,
        (data, rspMsg) => {

          this.download(data, title + '.xls')
          this.yihuyidangDisabled = false
        },
        (rspMsg, data) => {
          this.$message.error(rspMsg);
          this.yihuyidangDisabled = false
        }
      );
    },


    // 上传文件之前的钩子
    beforeUpload (file, type) {
      this.files = file;

      const isText = file.type === 'application/vnd.ms-excel'
      const isTextComputer = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

      if (!isText && !isTextComputer) {
        this.$message.error('请选择正确格式的文件')
        this.files = null
        this.fileName = ''
        return false
      } else {
        this.fileName = file.name;
        return true
      }

    },
    // 上传文件个数超过定义的数量
    handleExceed (files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，请删除后继续上传`)
    },

    async uploadFile (type) {
      if (this.fileName == "") {
        this.$message.warning('请选择要上传的文件！')
        return false
      }
      this.$message({
        showClose: true,
        message: '导入中，请到系统管理-导入记录中查看进度',
        duration: 0
      })


      //清空上传列表
      let url = ''
      let params = {}
      let fileFormData = new FormData();
      fileFormData.append('file', this.files);//filename是键，file是值，就是要传的文件，test.zip是要传的文件名
      fileFormData.append('orgId', this.agencyObj.id);//filename是键，file是值，就是要传的文件，test.zip是要传的文件名
      fileFormData.append('orgType', this.agencyObj.level);//filename是键，file是值，就是要传的文件，test.zip是要传的文件名

      // params.file = fileFormData
      // params.orgId = this.agencyObj.id
      // params.orgType = this.agencyObj.level

      if (type === 'building') {
        this.$refs['upload_building'].clearFiles()
        // url = 'http://192.168.51.26:8080/api/gov/org/building/buildingimport'
        url = '/gov/org/building/buildingimport'
        this.importBuildingLoading = true

      } else if (type === 'room') {
        this.$refs['upload_room'].clearFiles()
        // url = 'http://192.168.51.26:8080/api/gov/org/house/houseimport'
        url = '/gov/org/house/houseimport'
        this.importRoomLoading = true
      }

      window.app.ajax.post2(url, fileFormData,
        (data, rspMsg) => {

          if (data.code === 0 && data.msg == 'success') {
            // this.$message.success('导入成功')
          } else {
            // this.$message({
            //   showClose: true,
            //   message: rspMsg,
            //   duration: 0,
            //   type: "error"
            // })
            // this.$message.error(rspMsg)
          }
          this.$emit('refreshTree')
          this.loadTable()
          if (type === 'building') {
            this.importBuildingLoading = false

          } else if (type === 'room') {
            this.importRoomLoading = false
          }
        },
        (rspMsg, data) => {
          if (type === 'building') {
            this.importBuildingLoading = false

          } else if (type === 'room') {
            this.importRoomLoading = false
          }
        }, { headers: { 'Content-Type': 'multipart/form-data' } })

    },

    showMessage (msg) {
      this.$alert(msg, '操作结果', {
        confirmButtonText: '关闭',
        callback: action => {
          this.$emit('refreshTree')
          this.loadTable()
        }
      });
    },

    handleSizeChange (val) {
      this.pageSize = val
      this.pageNo = 1
      this.loadTable()
    },
    handleCurrentChange (val) {
      this.pageNo = val
      this.loadTable()
    },

    // 开启加载动画
    startLoading () {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: '正在加载……', // 加载中需要显示的文字
        background: 'rgba(0,0,0,.7)' // 背景颜色
      })
    },
    // 结束加载动画
    endLoading () {
      // clearTimeout(timer);
      if (loading) {
        loading.close()
      }
    }
  },
  watch: {

  },
  props: {
    staffAgencyId: {
      type: String,
      default: '',
    },
    showImportBtn: {
      type: Boolean,
      default: false,
    },
    ownerName: {
      type: String,
      default: '',
    },
    ownerPhone: {
      type: String,
      default: '',
    },
    rentFlag: {
      type: String,
      default: '',
    },
    purpose: {
      type: String,
      default: '',
    },
    remark: {
      type: String,
      default: '',
    },
    updateStartDate: {
      type: String,
      default: '',
    },
    updateEndDate: {
      type: String,
      default: '',
    },
  }
}
</script>
<style lang="scss" scoped >
@import "@/assets/scss/modules/visual/communityManage.scss";

.item_width_4 {
  width: 120px;
}

/deep/.el-input-number--medium .el-input-number__decrease,
/deep/.el-input-number--medium .el-input-number__increase {
  width: 26px;
}
/deep/.el-input-number--medium .el-input__inner {
  padding-left: 0px;
  padding-right: 0px;
}
</style>
