<template>
  <div class="div_main">

    <div :style="{height:rowHeight}"
         class="div_tree">
      <el-input placeholder="输入关键字进行过滤"
                v-model="filterText">
      </el-input>
      <el-scrollbar :style="{height:treeHeight}"
                    class="scrollar">
        <el-tree ref="ref_tree"
                 v-loading="treeLoading"
                 class="filter_tree"
                 :data="treeData"
                 :props="defaultProps"
                 :highlight-current="true"
                 node-key="id"
                 :default-expanded-keys="openNodes"
                 :expand-on-click-node="false"
                 :filter-node-method="filterNode"
                 @node-click="handleNodeClick">

          <span slot-scope="{ node, data }"
                class="custom-tree-node">
            <span :id="data.id">{{ data.showName }}</span>
          </span>
        </el-tree>
      </el-scrollbar>

    </div>

    <div :style="{height:rowHeight}"
         class=div_left>

      <div class="div_search">
        <el-form :inline="true"
                 ref="ref_searchform"
                 :label-width="'100px'">

          <el-form-item label="房主姓名"
                        prop="ownerName">
            <el-input v-model="ownerName"
                      class="item_width_normal"
                      size="small"
                      clearable
                      placeholder="请输入内容">

            </el-input>
          </el-form-item>
          <el-form-item label="联系方式"
                        prop="ownerPhone">
            <el-input v-model="ownerPhone"
                      class="item_width_normal"
                      size="small"
                      clearable
                      placeholder="请输入手机">
            </el-input>

          </el-form-item>

          <el-form-item label="房屋状态"
                        prop="rentFlag">
            <el-select class="item_width_normal"
                       v-model="rentFlag"
                       placeholder="请选择"
                       size="small"
                       clearable>
              <el-option v-for="item in rentList"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="房屋用途"
                        prop="purpose">
            <el-select v-model="purpose"
                       class="item_width_normal"
                       placeholder="请选择"
                       size="small"
                       clearable>
              <el-option v-for="item in purposeArr"
                         :key="item.dictValue"
                         :label="item.dictName"
                         :value="item.dictValue">
              </el-option>
            </el-select>

          </el-form-item>

          <el-form-item label="备注"
                        prop="remark">
            <el-input v-model="remark"
                      class="item_width_normal"
                      size="small"
                      clearable
                      placeholder="请输入备注">
            </el-input>
          </el-form-item>
          <el-form-item label="更新时间"
                        prop="updateStartDate">
            <el-date-picker v-model="updateStartDate"
                            :picker-options="startPickerOptions"
                            class="item_width_daterange"
                            size="small"
                            type="date"
                            value-format="yyyyMMdd"
                            value="yyyy-MM-dd"
                            placeholder="开始时间">
            </el-date-picker>
            <span class="data-tag">至</span>
            <el-date-picker v-model="updateEndDate"
                            :picker-options="endPickerOptions"
                            class="item_width_daterange data-tag"
                            size="small"
                            type="date"
                            value-format="yyyyMMdd"
                            value="yyyy-MM-dd"
                            placeholder="结束时间">
            </el-date-picker>
          </el-form-item>
          <span class="div_search_label">所属房屋：</span>
          <!-- <el-form-item label="所属房屋"> -->

          <el-form-item prop="neighborHoodId">
            <el-select v-model.trim="neighborHoodId"
                       :disabled="vDisabled"
                       placeholder="小区"
                       size="small"
                       clearable
                       class="item_width_buildcascader"
                       @change="handleChangeV">
              <el-option v-for="item in optionsV"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="buildingId">
            <el-select v-model.trim="buildingId"
                       placeholder="楼号"
                       :disabled="!neighborHoodId || bDisabled"
                       size="small"
                       clearable
                       class="item_width_buildcascader"
                       @change="handleChangeB">
              <el-option v-for="item in optionsB"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="buildingUnitId">
            <el-select v-model.trim="buildingUnitId"
                       placeholder="单元"
                       size="small"
                       :disabled="!buildingId"
                       clearable
                       class="item_width_buildcascader"
                       @change="handleChangeD">
              <el-option v-for="item in optionsD"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="houseId">
            <el-select v-model.trim="houseId"
                       placeholder="房号"
                       :disabled="!buildingUnitId"
                       size="small"
                       clearable
                       class="item_width_buildcascader">
              <el-option v-for="item in optionsH"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <!-- </el-form-item> -->
          <div class="div_search_btn">
            <el-button style="margin-left:30px"
                       size="small"
                       class="diy-button--blue"
                       @click="handleSearch">查询</el-button>
            <el-button style="margin-left:10px"
                       size="small"
                       class="diy-button--gray"
                       @click="resetSearch">重置</el-button>
          </div>
        </el-form>

      </div>
      <div class="div_table">
        <build-table v-if="selTreeObj.level==='neighborHood'&&!showRoomTable"
                     ref="ref_neighTable"
                     :staffAgencyId="staffAgencyId"
                     :showImportBtn="showImportBtn"
                     :ownerName="ownerName"
                     :ownerPhone="ownerPhone"
                     :rentFlag="rentFlag"
                     :purpose="purpose"
                     :remark="remark"
                     :updateStartDate="updateStartDate"
                     :updateEndDate="updateEndDate"
                     @toNextLevel="toNextLevel"
                     @refreshTree="refreshTree"></build-table>

        <room-table v-if="showRoomTable||selTreeObj.level==='building'"
                    :staffAgencyId="staffAgencyId"
                    :showImportBtn="showImportBtn"
                    :ownerName="ownerName"
                    :ownerPhone="ownerPhone"
                    :rentFlag="rentFlag"
                    :purpose="purpose"
                    :neighborHoodId="neighborHoodId"
                    :buildingId="buildingId"
                    :buildingUnitId="buildingUnitId"
                    :houseId="houseId"
                    :remark="remark"
                    :updateStartDate="updateStartDate"
                    :updateEndDate="updateEndDate"
                    ref="ref_buildingTable"
                    @refreshTree="refreshTree"></room-table>

        <community-table v-if="selTreeObj.level!=='building'&&selTreeObj.level!=='neighborHood'&&!showRoomTable"
                         @toNextLevel="toNextLevel"
                         :staffAgencyId="staffAgencyId"
                         :ownerName="ownerName"
                         :ownerPhone="ownerPhone"
                         :rentFlag="rentFlag"
                         :purpose="purpose"
                         :remark="remark"
                         :updateStartDate="updateStartDate"
                         :updateEndDate="updateEndDate"
                         ref="ref_communityTable"
                         @refreshTree="refreshTree"></community-table>
      </div>
    </div>

  </div>
</template>

<script>
import CDialog from '@c/CDialog'
import communityTable from './communityTable'
import buildTable from './buildTable'
import roomTable from './roomTable'
import { requestPost } from "@/js/dai/request";
import { mapGetters } from 'vuex'
import { Loading } from 'element-ui' // 引入Loading服务
import nextTick from 'dai-js/tools/nextTick'

let loading // 加载动画
export default {
  data () {
    let endDisabledDate = (time) => {//这个关键属性我们一定要写在data的里面并且return的外面，这是动态改变区间的关键
      let nowData = Date.now()
      if (this.updateStartDate) {
        let startTime = new Date(this.updateStartDate)
        return time.getTime() > nowData || time.getTime() < startTime || time.getTime() === startTime
      } else {
        return time.getTime() > nowData
      }

    }
    let startDisabledDate = (time) => {//这个关键属性我们一定要写在data的里面并且return的外面，这是动态改变区间的关键
      let nowData = Date.now()
      return time.getTime() > nowData
    }
    return {
      filterText: '',
      treeLoading: true,
      treeData: [],
      openNodes: [],
      defaultProps: {
        children: 'children',
        label: 'showName'
      },

      selTreeObj: {},

      centerPoint: [],
      staffAgencyId: localStorage.getItem("agencyId"),
      showImportBtn: false,

      rentList: [
        {
          value: '1',
          label: '出租'
        },
        {
          value: '2',
          label: '闲置'
        },
        {
          value: '0',
          label: '自住'
        },
        {
          value: '3',
          label: '未出售'
        },
      ],
      ownerName: '',
      ownerPhone: '',
      rentFlag: '',
      purpose: '',
      remark: '',
      updateStartDate: '',
      updateEndDate: '',
      showRoomTable: false,
      selObj: {},
      purposeArr: [
        { dictValue: '1', dictName: '住宅' },
        { dictValue: '2', dictName: '商业' },
        { dictValue: '3', dictName: '办公' },
        { dictValue: '4', dictName: '工业' },
        { dictValue: '5', dictName: '仓储' },
        { dictValue: '6', dictName: '商住混用' },
        { dictValue: '7', dictName: '其他' }
      ],
      endPickerOptions: {
        disabledDate: endDisabledDate
      },
      startPickerOptions: {
        disabledDate: startDisabledDate
      },

      optionsV: [],
      optionsB: [],
      optionsH: [],
      optionsD: [],
      neighborHoodId: "",
      buildingId: "",
      buildingUnitId: "",
      houseId: "",
      selGridId: '',
      selAgencyId: '',

      vDisabled: false,
      bDisabled: false,
    }
  },
  components: {
    CDialog
  },
  async mounted () {
    this.treeLoading = true

    await this.loadOrgData()
    await this.loadTree()
    // await this.loadOpenNode()
    this.getValiheList('', '')

    await this.$refs['ref_communityTable'].loadTable(true, this.selTreeObj)
    if (this.treeData.length > 0) {
      this.$nextTick(() => {
        // ref_tree 元素的ref   value 绑定的node-key
        this.$refs.ref_tree.setCurrentKey(this.treeData[0].id);
      });
    }
    this.treeLoading = false

  },
  computed: {
    rowHeight () {

      return this.$store.state.inIframe ? this.clientHeight - 160 + this.iframeHeight + 'px' : this.clientHeight - 160 + 'px'

    },
    treeHeight () {
      return this.$store.state.inIframe ? this.clientHeight - 215 + this.iframeHeight + 'px' : this.clientHeight - 215 + 'px'

    },

    ...mapGetters(['clientHeight', 'iframeHeight'])
  },
  methods: {
    handleChangeV (val) {

      this.buildingId = "";
      this.buildingUnitId = "";
      this.houseId = "";
      this.getBuildList();
      // this.getUniList();
      // this.getHouseList();
    },
    handleChangeB (val) {

      this.buildingUnitId = "";
      this.houseId = "";
      this.getUniList();
      // this.getHouseList();
    },
    handleChangeD () {
      this.houseId = "";
      this.getHouseList();
    },

    async getValiheList () {
      const { user } = this.$store.state;
      if (!this.selGridId) {
        this.selAgencyId = this.selAgencyId ? this.selAgencyId : user.agencyId
      }

      const url = "/gov/org/icneighborhood/neighborhood-options";
      // const url = "http://yapi.elinkservice.cn/mock/245/epmetuser/epidemicPrevention/page"
      let params = {
        gridId: this.selGridId,
        agencyId: this.selAgencyId,
        isPage: false
      };

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

      if (code === 0) {
        this.optionsV = data;

        this.neighborHoodId = ""
        this.buildingId = "";
        this.buildingUnitId = "";
        this.houseId = "";
      } else {
        this.$message.error(msg);
      }


    },

    async getBuildList () {
      const url = "/gov/org/icbuilding/buildingoption";
      // const url = "http://yapi.elinkservice.cn/mock/245/epmetuser/epidemicPrevention/page"
      let params = {
        neighborHoodId: this.neighborHoodId,
      };

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

      if (code === 0) {
        this.optionsB = data;
        this.buildingId = "";
        this.buildingUnitId = "";
        this.houseId = "";
      } else {
        this.$message.error(msg);
      }


    },
    async getUniList () {

      const url = "/gov/org/icbuildingunit/unitoption";
      // const url = "http://yapi.elinkservice.cn/mock/245/epmetuser/epidemicPrevention/page"
      let params = {
        buildingId: this.buildingId,
      };

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

      if (code === 0) {
        this.optionsD = data;
        this.buildingUnitId = "";
        this.houseId = "";
      } else {
        this.$message.error(msg);
      }


    },
    getHouseList () {
      this.$http
        .post("/gov/org/ichouse/houseoption", { unitId: this.buildingUnitId })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {

            this.optionsH = res.data;
            this.houseId = "";
          }
        })
        .catch(() => {
          return this.$message.error("网络错误");
        });
    },

    handleSearch () {
      // if (this.ownerName || this.ownerPhone || this.rentFlag || this.purpose || this.remark) {
      this.showRoomTable = true

      this.$nextTick(() => {
        this.$refs['ref_buildingTable'].loadTable('search', this.selTreeObj)
      })
      // } else {
      //   this.$message.warning('请输入查询条件')
      // }


    },

    //重置搜索条件
    resetSearch () {
      this.ownerName = ''
      this.ownerPhone = ''
      this.rentFlag = ''
      this.purpose = ''
      this.remark = ''
      this.updateStartDate = ''
      this.updateEndDate = ''
      this.neighborHoodId = ''
      this.buildingId = ''
      this.buildingUnitId = ''
      this.houseId = ''

      this.pageSize = 10
      this.pageNo = 1
      // this.handleNodeClick(this.selObj)
      // this.loadTable()
    },

    async loadOpenNode () {
      const url = "/gov/org/building/tree-ids"
      let params = {}

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

      if (code === 0) {
        this.openNodes = data


      } else {
        this.$message.error(msg)
      }
    },
    async loadTree (isRefresh) {
      const url = "/gov/org/building/treelist"
      let params = {}

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

      if (code === 0) {
        this.openNodes = []
        this.openNodes.push(data[0].id)

        this.treeData = data
        if (!isRefresh && data.length > 0) {

          this.selTreeObj = data[0]
          if (!this.selTreeObj.latitude) {
            this.selTreeObj.latitude = this.centerPoint[0]
          }

          if (!this.selTreeObj.longitude) {
            this.selTreeObj.longitude = this.centerPoint[1]
          }
        }

      } else {
        this.$message.error(msg)
      }
    },

    //加载组织数据
    async loadOrgData () {
      const url = "/gov/org/agency/maporg"
      // const url = "http://yapi.elinkservice.cn/mock/245/gov/org/agency/maporg"
      let params = {}

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

      if (code === 0) {
        this.centerPoint = []

        this.centerPoint.push(data.latitude)
        this.centerPoint.push(data.longitude)

      } else {
        this.$message.error(msg)
      }

    },

    async handleNodeClick (obj) {
      this.ownerName = ''
      this.ownerPhone = ''
      this.rentFlag = ''
      this.purpose = ''
      this.remark = ''
      this.updateStartDate = ''
      this.updateEndDate = ''
      this.showRoomTable = false

      this.selObj = JSON.parse(JSON.stringify(obj))
      this.getTreeObj(obj)
      await nextTick(1000)
      this.vDisabled = false
      this.bDisabled = false
      if (obj.level === 'building') {//点击楼栋
        this.$refs['ref_buildingTable'].loadTable('tree', this.selTreeObj)
        this.selAgencyId = ''
        this.selGridId = ''
        await this.getValiheList()
        this.neighborHoodId = this.selTreeObj.pid
        await this.getBuildList()
        this.buildingId = this.selTreeObj.id
        await this.getUniList()
        this.vDisabled = true
        this.bDisabled = true

      } else if (obj.level === 'neighborHood') {//点击小区
        this.$refs['ref_neighTable'].loadTable(true, this.selTreeObj)
        this.selAgencyId = ''
        this.selGridId = ''
        await this.getValiheList()
        this.neighborHoodId = this.selTreeObj.id
        await this.getBuildList()
        this.vDisabled = true
      } else {
        this.$refs['ref_communityTable'].loadTable(true, this.selTreeObj)

        if (obj.level === 'grid') {
          this.selAgencyId = ''
          this.selGridId = this.selTreeObj.id
        } else {
          this.selAgencyId = this.selTreeObj.id
          this.selGridId = ''
        }
        this.getValiheList('', '')
      }


    },

    //添加小区结束
    async refreshTree () {
      this.treeLoading = true
      await this.loadTree(this.selTreeObj.id)
      this.$nextTick(() => {
        // ref_tree 元素的ref   value 绑定的node-key
        this.$refs.ref_tree.setCurrentKey(this.selTreeObj.id);
      });
      this.treeLoading = false
    },

    //进入下一级
    toNextLevel (row, level) {

      if (level === 'community') {
        this.selTreeObj = this.$refs.ref_tree.getNode(row.neighborHoodId).data
        this.openNodes.push(this.selTreeObj.id)
      } else {
        this.selTreeObj = this.$refs.ref_tree.getNode(row.buildingId).data
      }


      this.handleNodeClick(this.selTreeObj)
      this.$nextTick(() => {
        // ref_tree 元素的ref   value 绑定的node-key
        this.$refs.ref_tree.setCurrentKey(this.selTreeObj.id);
      });

      const node = document.getElementById(this.selTreeObj.id) // 通过Id获取到对应的dom元素
      setTimeout(() => {
        if (node) {
          this.$nextTick(() => {
            node.scrollIntoView({ block: 'center' }) // 通过scrollIntoView方法将对应的dom元素定位到可见区域 【block: 'center'】这个属性是在垂直方向居中显示
          })
        }
      }, 100)


    },

    //解析树数据
    getTreeObj (obj) {
      // 树接口：
      // 组织：组织id、组织名称、type、经度、纬度
      // 小区：小区id、小区名称、type、所属网格id、所属网格名称、所属组织id、所属组织名称、经度、纬度
      // 楼：楼id、楼名称、type、所属小区id、所属小区名称
      if (obj.level === 'building') {//点击楼栋
        let neighborHoodNode = this.$refs.ref_tree.getNode(obj.pid)//所属小区

        let gridNode = this.$refs.ref_tree.getNode(neighborHoodNode.data.pid)//所属网格
        let agencyNode = this.$refs.ref_tree.getNode(gridNode.data.pid)//所属社区
        obj.agencyId = agencyNode.data.id
        obj.agencyName = agencyNode.data.label
        obj.gridId = gridNode.data.id
        obj.gridName = gridNode.data.label
        obj.neighborHoodId = neighborHoodNode.data.id
        obj.neighborHoodName = neighborHoodNode.data.label
        if (obj.agencyId === this.staffAgencyId) {
          this.showImportBtn = true
        } else {
          this.showImportBtn = false
        }

      } else if (obj.level === 'neighborHood') {//点击小区
        let gridNode = this.$refs.ref_tree.getNode(obj.pid)
        let agencyNode = this.$refs.ref_tree.getNode(gridNode.data.pid)
        obj.gridId = gridNode.data.id
        obj.gridName = gridNode.data.label
        obj.agencyId = agencyNode.data.id
        obj.agencyName = agencyNode.data.label
        if (obj.agencyId === this.staffAgencyId) {
          this.showImportBtn = true
        } else {
          this.showImportBtn = false
        }

      } else {

      }

      if (!obj.latitude) {
        obj.latitude = this.centerPoint[0]
      }

      if (!obj.longitude) {
        obj.longitude = this.centerPoint[1]
      }
      this.selTreeObj = obj
      console.log('selTreeObj', this.selTreeObj)

    },

    filterNode (value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },

    // 开启加载动画
    startLoading () {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: '正在加载……', // 加载中需要显示的文字
        background: 'rgba(0,0,0,.7)' // 背景颜色
      })
    },
    // 结束加载动画
    endLoading () {
      // clearTimeout(timer);
      if (loading) {
        loading.close()
      }
    }
  },
  watch: {
    filterText (val) {
      this.$refs.ref_tree.filter(val);
    }
  },
  components: {
    communityTable, buildTable, roomTable
  }
}
</script>


<style>
/* .aui-content > .el-tabs > .el-tabs__content {
    padding: 0px;
  } */

.el-tree-node:focus > .el-tree-node__content {
  /* background-color: #ccc !important; */
  color: #2195fe;
}
</style>

<style lang="scss" scoped >
@import "@/assets/scss/modules/visual/communityManage.scss";
@import "@/assets/scss/modules/management/list-main.scss";
</style>

<style lang="scss" scoped >
.div_main {
  display: flex;
}
.scrollar {
  margin-top: 10px;
  /deep/
    .el-tree--highlight-current
    .el-tree-node.is-current
    > .el-tree-node__content {
    background-color: #e1ecff;
    border-radius: 3px;
  }

  /deep/ .el-tree-node:focus > .el-tree-node__content {
    color: #0043c8;
    // background-color: #fff;
  }
  /deep/ .el-tree-node__expand-icon {
    color: #0043c8;
    border: 1px solid #e1ecff;
    background-color: #e1ecff;
    padding: 0px;
    margin-right: 8px;
    font-size: 9px;
  }

  /deep/.el-tree {
    flex: 1;

    .el-tree-node {
      margin-left: 2px;
    }

    //原有的箭头 去掉
    .el-icon svg {
      display: none;
      height: 0;
      width: 0;
    }
    //引入图标的位置
    .el-tree-node__expand-icon {
      // position: absolute;
      // left: 2px;
      // 图标是否旋转，如果是箭头类型的，可以设置旋转90度。
      .expanded {
        transform: rotate(90deg);
      }
      // 未展开的节点
      &:before {
        // content: "\008B";
        // content: "\008B";
        font-size: 12px;
        color: #0043c8;
      }
    }
    // 叶子节点（不显示图标）
    .is-leaf.el-tree-node__expand-icon::before {
      // display: none;
      // background: none !important;
      // border: 0px;

      // content: "";
      // width: 18px;
      // height: 18px;
    }
  }
}

.div_tree {
  margin: 7px 8px 7px 7px;
  /deep/ .el-scrollbar__wrap {
    overflow-x: hidden !important;
  }

  //搜索输入框样式
  /deep/ .el-input--medium .el-input__inner {
    height: 27px;
    border-radius: 0;
  }
  flex: 0 0 280px;
  background-color: #f6f6f6;
  border: 1px solid #d3dce6;
  // border-radius: 5px;
  padding: 19px 15px;
  overflow-y: hidden;
}

.filter_tree {
  overflow-x: auto;
  background-color: #f6f6f6;
  margin-top: 5px;
}

.div_left {
  // flex: 1;
  width: calc(100% - 300px);
}
</style>


