<template>
  <div
    v-loading="mapLoading"
    class="map-box"
    element-loading-text="数据加载中,预估等待30s,请稍后..."
  >
    <div ref="mapContainer" class="map-grid" />
    <div class="range-box">
      <el-form size="small" class="myForm">
        <el-form-item label="汇总维度" label-width="80px">
          <el-select
            v-model="searchForm.timeInterval"
            placeholder="请选择"
            @change="toggleRange"
          >
            <el-option
              v-for="item in rangeList"
              :key="item.key"
              :value="item.key"
              :label="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="showDate" label="选择日期" label-width="80px">
          <el-date-picker
            v-model="searchForm.date"
            type="date"
            placeholder="请选择"
            value-format="yyyy-MM-dd"
            :picker-options="pickDateOption"
            :clearable="false"
            @change="toggleDate"
          />
        </el-form-item>
        <el-form-item
          v-if="!isCommonManager"
          label="归属机构"
          label-width="80px"
          class="tree-select"
          prop="deptTree"
        >
          <treeselect
            ref="orgTree"
            v-model="searchForm.deptId"
            :options="deptOptions"
            placeholder="请选择"
            no-options-text="暂无数据"
            no-results-text="暂无数据"
            style="width: 250px"
            @select="onDeptTreeSelect"
            @deselect="clearTreeSelect"
            @open="onOrgTreeFocus"
            @clear="clearTreeSelect"
          />
        </el-form-item>
        <el-form-item
          v-if="!isCommonManager"
          label="客户经理"
          label-width="80px"
          prop="clientManager"
          class="tree-select"
        >
          <el-select
            ref="clientManager"
            v-model="searchForm.userName"
            :collapse-tags="false"
            size="small"
            style="width: 300px"
            filterable
            placeholder="请选择"
            clearable
            @focus="onClientManagerFocus"
            @change="userChange"
          >
            <el-option
              v-for="option in managerOptions"
              :key="option.userId"
              :label="`${option.deptName}-${option.userName}-${option.nickName}`"
              :value="option.userName"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import {
  getPointInfo1,
  getPointInfo2
} from '@/api/grid/performance/collect.js'
import { getDeptTree } from '@/api/grid/address/tree.js'
import { getUserListByDeptIds } from '@/api/grid/region.js'
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      mapLoading: false,
      data: [],
      searchForm: {
        timeInterval: '30',
        date: undefined,
        deptId: undefined,
        userName: ''
      },
      rangeList: [
        { key: '', value: '按天' },
        { key: '30', value: '近30天' },
        { key: '90', value: '近90天' },
        { key: '180', value: '近180天' },
        { key: '365', value: '近365天' }
      ],
      pickDateOption: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e7
        }
      },
      defaultDate: '',
      showDate: false,
      max: 100,
      deptOptions: [],
      managerOptions: [],
      // checkedArr: [],
      currentLevel: '',
      node: {},
      hotData: []
    }
  },
  computed: {
    ...mapGetters(['roles', 'userName']),
    // 客户经理
    isCommonManager() {
      return this.roles.includes('commonManager')
    }
  },
  watch: {
    'searchForm.deptId': function(newVlaue, oldValue) {
      console.log(newVlaue, oldValue)
      if (!newVlaue) {
        this.searchForm.userName = ''
        this.node = {}
        this.managerOptions = []
        this.data = []
        this.map.centerAndZoom('浙江省', 9)
        this.map.clearOverlays()
      }
    }
  },

  created() {
    const today = new Date()
    const preDay = new Date(today.getTime() - 24 * 3600 * 1000)
    this.defaultDate = preDay
    this.searchForm.date = preDay
    if (this.isCommonManager) {
      this.searchForm.userName = this.userName
    }
    this.getDeptTreeSelect()
  },

  mounted() {
    this.initMap()
  },
  methods: {
    formatData(data) {
      return data.map((item) => {
        if (item.children && item.children.length > 0) {
          this.formatData(item.children)
        }
        // if (item.level === 'head') {
        //   item.isDisabled = true;
        // } else {
        //   item.isDisabled = false;
        // }
        return item
      })
    },
    getDeptTreeSelect() {
      getDeptTree().then((response) => {
        const newData = this.formatData(response.data)
        this.deptOptions = newData
      })
    },
    // 勾选归属机构
    onDeptTreeSelect(node) {
      console.log(node, this.searchForm)
      this.node = node
      // this.orgCheckedOnlyOneArr = [node];
      // if (node.children) {
      //   const childrenArr = node.children.map((child) => child.id);
      //   this.checkedArr = [
      //     ...new Set([
      //       ...this.checkedArr,
      //       ...this.userChecked,
      //       node.id,
      //       ...childrenArr,
      //     ]),
      //   ];
      // } else {
      // this.checkedArr = [node.id];
      // }
      this.fetchSelectOptions([node.id])
      this.getPoint()
    },
    // 取消勾选归属机构
    clearTreeSelect(node) {
      console.log(33333)
      // const index = this.checkedArr.findIndex((id) => id === node.id);
      // if (index > -1) {
      //   this.checkedArr.splice(index, 1);
      // }
      // const { children = [] } = node;
      // if (children.length > 0) {
      //   children.map((child) => {
      //     const index = this.checkedArr.findIndex((id) => id === child.id);
      //     if (index > -1) {
      //       this.checkedArr.splice(index, 1);
      //     }
      //   });
      // }
      // this.checkedArr=[];
      this.node = {}
      // this.fetchSelectOptions(this.checkedArr);
      this.fetchSelectOptions('')
    },
    fetchSelectOptions(deptIds, data = []) {
      this.searchForm.userName = ''
      if (!deptIds) {
        this.managerOptions = []
        this.getPoint()
        return
      }
      // if (isEmpty(deptIds)) {
      //   this.formData.clientManager = [];
      //   return (this.managerOptions = []);
      // }
      getUserListByDeptIds({ deptIds: deptIds }).then((response) => {
        this.managerOptions = response.data
      })
    },
    handleInput(selected) {
      console.log(selected)
      // if (selected.length > 1) {
      //   this.formData.deptId = [selected[selected.length - 1]];
      // } else {
      this.formData.deptId = selected
      // }
    },
    onOrgTreeFocus() {
      this.$refs.clientManager.blur()
    },
    onClientManagerFocus() {
      this.$refs.orgTree.blurInput()
    },
    userChange() {
      this.getPoint()
    },
    toggleRange(v) {
      if (v == '') {
        this.showDate = true
        this.searchForm.date = this.defaultDate
      } else {
        this.showDate = false
        this.searchForm.date = undefined
      }
      if (this.isCommonManager || this.node.id) {
        this.getPoint()
      }
    },
    toggleDate() {
      if (this.isCommonManager || this.node.id) {
        this.getPoint()
      }
    },
    formatDate(dateString) {
      const date = new Date(dateString)
      return date.toISOString().slice(0, 10).replace('T', ' ')
    },
    // 初始化地图
    initMap() {
      this.mapLoading = true
      this.map = new BMapGL.Map(this.$refs.mapContainer, {
        enableHighResolution: false,
        enableAutoResize: true,
        displayOptions: {
          building: false
        }
      })
      const localCity = new BMapGL.LocalCity()
      // localCity.get((result) => {
      //   console.log(result);
      this.map.centerAndZoom('浙江省', 9)
      // this.map.centerAndZoom('杭州市临安区林业和草原局', 50);
      // });
      // this.drawHeatMap();
      this.map.enableScrollWheelZoom()
      if (this.isCommonManager) {
        this.getPoint()
      } else {
        this.mapLoading = false
      }
    },

    getPoint() {
      this.map.clearOverlays()
      const centerLabel = this.node.label.startsWith('临海农商银行') ? this.node.label : `临海农商银行${this.node.label}`
      this.map.centerAndZoom(centerLabel, 13)
      const { timeInterval, date, deptId, userName } = this.searchForm
      // console.log(deptId, userName,this.node);
      const params = {}
      if (timeInterval == '') {
        params.date = (date && this.formatDate(date)) || ''
      } else {
        params.timeInterval = timeInterval
      }
      if (this.node.level == 'head') {
        params.headId = this.node.id
      } else if (this.node.level == 'branch') {
        params.branchId = this.node.id
      } else if (this.node.level == 'outlet') {
        params.outletId = this.node.id
      }
      params.userName = userName
      console.log(params)
      this.mapLoading = true
      const Api = timeInterval ? getPointInfo1 : getPointInfo2
      setTimeout(() => {
        Api(params).then((res) => {
          console.log(res, 'ressssss')
          if (res.code == 200) {
            this.data = res.data
            if (this.data.length) {
              this.max = this.data.reduce((prev, current) =>
                Number(prev.count) > Number(current.count) ? prev : current
              ).count
              this.drawHeatMap()
            } else {
              this.mapLoading = false
            }
          }
        })
      }, 300)
    },

    drawHeatMap() {
      const heatmapOverlay = new BMapLib.HeatmapOverlay({
        radius: 15,
        visible: true,
        opacity: 70
      })
      this.map.addOverlay(heatmapOverlay)
      // heatmapOverlay.setOptions({
      //   gradient:{
      //     0:'blue',
      //     0.1:'rgb(0,255,255)',
      //     0.2:'rgb(0,255,0)',
      //     0.4:'yellow',
      //     0.6:'red',
      //     1:'maroon',
      //   }
      // })
      const data = {
        max: this.max,
        data: this.data
      }
      // console.log(heatmapOverlay)
      heatmapOverlay.setDataSet(data)
      // this.map.setViewport();
      this.mapLoading = false
    }
  }
}
</script>
<style lang="scss" scoped>
.map-box {
  position: relative;
  width: 100%;
  height: 100%;
  .map-grid {
    width: 100%;
    height: calc(100vh - 130px);
    margin: 0;
    padding: 0;
  }
  .range-box {
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 999;
    background: #fff;
    padding: 5px;
    border-radius: 5px;
    .myForm {
      display: flex;
      ::v-deep .el-form-item {
        margin-bottom: 0;
      }
    }
  }
  ::v-deep .BMap_bubble_pop {
    border: 2px solid #2094ff !important;
    overflow: hidden;
    padding: 0 !important;
  }
  ::v-deep .BMap_bubble_top {
    text-align: center;
    font-weight: bold;
    background-color: #2094ff !important;
  }
  ::v-deep .BMap_bubble_title {
    color: #fff !important;
  }
  ::v-deep .BMap_bubble_pop img {
    display: none;
  }
}
</style>
