<template>
  <div class="main">
    <div>
      <el-form ref="searchForm" :model="searchForm" class="searchForm">
        <el-row>
          <el-col :span="4">
            <el-button
              v-if="level == '2' && !isOutletAdmin && !isCommonManager"
              class="back"
              @click="backTo"
            >返回</el-button>
            <span class="date">统计日期（T+1）：{{ date }}</span>
          </el-col>
          <el-col :span="4">
            <el-form-item label="业务指标" prop="itemIdx" label-width="80px">
              <el-select
                v-model="searchForm.itemIdx"
                placeholder="请选择业务指标"
                @change="handleChange"
              >
                <el-option
                  v-for="item in optionArr"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="归属支行" prop="branchName" label-width="80px">
              <el-input
                v-model="searchForm.branchName"
                placeholder="请输入"
                clearable
                @clear="getPerEchartsData"
                @keyup.enter.native="getPerEchartsData"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="归属网点" prop="outletName" label-width="80px">
              <el-input
                v-model="searchForm.outletName"
                placeholder="请输入"
                clearable
                @clear="getPerEchartsData"
                @keyup.enter.native="getPerEchartsData"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item
              label="归属客户经理"
              prop="nickName"
              label-width="100px"
            >
              <el-input
                v-model="searchForm.nickName"
                placeholder="请输入"
                clearable
                @clear="getPerEchartsData"
                @keyup.enter.native="getPerEchartsData"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="统计日期" prop="dt" label-width="100px">
              <el-date-picker
                v-model="searchForm.dt"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择"
                :clearable="false"
                @change="getPerEchartsData"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="echart-box">
      <div ref="echart" class="echart" />
    </div>
    <div class="dialog-container">
      <el-dialog
        :visible.sync="showDialog"
        title=""
        width="50%"
        class="dialog-header"
        :close-on-click-modal="false"
        @close="closeDialog"
      >
        <template #title>
          <div class="dialog-title">
            <span>业绩指标信息</span>
            <el-button
              v-if="level == 1"
              type="primary"
              size="mini"
              class="btn"
              @click="gotoNext"
            >下钻查看村/社区</el-button>
          </div>
        </template>
        <div class="child-main">
          <div v-if="level == 1">
            <div class="my-title">总行行政网格：{{ layerInfo.name }}</div>
            <div class="my-title">归属支行：{{ allBranch }}</div>
            <div class="my-title">
              整体{{ layerInfo.itemName }}：{{ layerInfo.value }}%
            </div>
            <div
              v-for="(item, index) in otherInfo"
              :key="index"
              class="branch-box"
            >
              <div>
                (支行) {{ item.name }}{{ layerInfo.itemName }}：{{
                  item.itemVal
                }}%
              </div>
              <div class="org-box">
                <span v-for="(i, k) in item.managerList" :key="k">
                  <span>{{ i.nickName }}{{ layerInfo.itemName }}：{{
                    i.itemVal
                  }}%</span>
                  <span v-if="k < item.managerList.length - 1">，</span>
                </span>
              </div>
              <div v-for="(i, k) in item.children" :key="k" class="outlet-box">
                <div>
                  (网点) {{ i.name }}{{ layerInfo.itemName }}：{{ i.itemVal }}%
                </div>
                <div class="org-box">
                  <span v-for="(j, s) in i.managerList" :key="s">
                    <span>{{ j.nickName }}{{ layerInfo.itemName }}：{{
                      j.itemVal
                    }}%</span>
                    <span v-if="s < i.managerList.length - 1">，</span>
                  </span>
                </div>
              </div>
            </div>
          </div>
          <div v-if="level == 2">
            <div class="my-title">支行行政网格：{{ layerInfo.name }}</div>
            <div class="my-title">归属支行：{{ allBranch }}</div>
            <div class="my-title">归属网点：{{ allOutlet }}</div>
            <div class="my-title">归属客户经理：{{ allManager }}</div>
            <div class="my-title">
              整体{{ layerInfo.itemName }}：{{ layerInfo.value }}%
            </div>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import * as echarts from 'echarts'
import {
  searchEchartTownData,
  searchEchartVillageData,
  getPerIndcList,
  getHotMapInfo
} from '@/api/grid/performance/collect.js'
// import {geoData} from './geo';
import WKT from 'terraformer-wkt-parser'
import { Message } from 'element-ui'
import { mapGetters } from 'vuex'
import { debounce } from '@/utils'
export default {
  props: {
    selectedTab: {
      type: String,
      default: '1'
    }
  },
  data() {
    return {
      searchForm: {
        dt: '',
        itemIdx: '',
        branchName: '',
        outletName: '',
        nickName: ''
      },
      optionArr: [],
      Loading: false,
      myChart: null,
      mapData: {
        type: 'FeatureCollection',
        features: []
      },
      perData: [],
      level: '1',
      opsDept: '',
      code: '',
      noData: true,
      date: '',
      min: 0,
      max: 100,
      showDialog: false,
      layerInfo: {},
      otherInfo: [],
      allBranch: '',
      allOutlet: '',
      allManager: '',
      code1: '',
      code2: ''
    }
  },
  computed: {
    ...mapGetters(['roles']),
    // 网点主任
    isOutletAdmin() {
      return this.roles.includes('outletAdmin')
    },
    // 客户经理
    isCommonManager() {
      return this.roles.includes('commonManager')
    }
  },
  watch: {
    selectedTab: {
      handler(val) {
        if (val) {
          this.opsDept = val == '1' ? '0' : '1'
          this.getIndcList()
        }
      },
      immediate: true
    }
  },
  created() {
    const date = new Date()
    date.setDate(date.getDate() - 1)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    this.searchForm.dt = `${year}-${month}-${day}`
    if (this.isOutletAdmin || this.isCommonManager) {
      this.level = '2'
    }
  },
  mounted() {
    this.myChart = echarts.init(this.$refs.echart)
  },
  methods: {
    // 获取弹框详情数据--添加防抖
    getModalInfo: debounce(function() {
      getHotMapInfo({
        opsDept: this.opsDept,
        itemIdx: this.searchForm.itemIdx,
        code: this.level == '1' ? this.code1 : this.code2,
        dt: this.searchForm.dt
        // code:'331082001207',
      }).then((res) => {
        if (res.code == 200) {
          const data = (res.data && res.data[0]) || {}
          if (!res?.data?.length) {
            Message.warning('暂无数据')
          }
          this.otherInfo = data.children || []
          this.allBranch = this.otherInfo.map((item) => item.name).join(',')
          const outlet = []
          this.otherInfo.map((item) => {
            item.children.map((i) => {
              outlet.push(i.name)
            })
          })
          this.allOutlet = outlet.join(',')
          const manager = []
          data.managerList.map((item) => {
            manager.push(item.nickName)
          })
          this.otherInfo.map((item) => {
            item.managerList.map((i) => {
              manager.push(i.nickName)
            })
            item.children.map((i) => {
              i.managerList.map((n) => {
                manager.push(n.nickName)
              })
            })
          })
          this.allManager = manager.join(',')
          this.showDialog = true
        }
      })
    }, 500),
    // 前端筛选数据
    // getCurrentData(){
    //     const {branch,outlet,manager}=this.searchForm;
    //     this.perData = this.perData.map(item=>{
    //         let isNoSee = false;
    //         if(!item.relateDepts.includes(branch)){
    //             isNoSee=true;
    //         }
    //         return{
    //             ...item,
    //             isNoSee
    //         }
    //     })
    //     console.log(this.perData)
    //     this.renderMap();
    // },
    // 下钻
    gotoNext() {
      this.level = '2'
      this.code1 = this.layerInfo.code
      this.showDialog = false
      this.searchForm.branchName = ''
      this.searchForm.outletName = ''
      this.searchForm.nickName = ''
      this.getPerEchartsData()
    },
    closeDialog() {
      this.showDialog = false
    },
    // 返回
    backTo() {
      this.level = '1'
      this.searchForm.branchName = ''
      this.searchForm.outletName = ''
      this.searchForm.nickName = ''
      this.getPerEchartsData()
    },
    // 查询镇/村数据
    getPerEchartsData() {
      const Api =
        this.level == '1' ? searchEchartTownData : searchEchartVillageData
      const params = {
        ...this.searchForm,
        opsDept: this.opsDept
      }
      if (this.level == '2') {
        params.code = this.code1
      }
      this.myChart.showLoading()
      Api(params).then((res) => {
        if (res.code == 200) {
          const arr = res.data || []
          if (!arr.length) {
            this.noData = true
            this.mapData.features = []
            this.perData = []
            this.myChart.hideLoading()
            this.renderMap()
            Message.warning('暂无数据')
            return
          }
          this.date = arr[0].createTime
          // console.log(this.date)
          this.mapData.features = []
          this.perData = []
          arr.map((item, index) => {
            const value = item.itemVal
            this.perData.push({
              name: item.regionName || '',
              value: Number(value),
              relateGrids: item.relateGrids || '',
              relateDepts: item.relateDepts || '',
              relateUsers: item.relateUsers || '',
              itemName: item.itemName || '',
              code: item.code || '',
              evoFlag: item.evoFlag
            })
            this.mapData.features.push({
              type: 'Feature',
              properties: {
                name: item.regionName || ''
              },
              geometry: {
                type: WKT.parse(item.wkt).type,
                coordinates: WKT.parse(item.wkt).coordinates
              }
            })
          })
          const values = this.perData.map((item) => item.value)
          const minValue = Math.min(...values)
          const maxValue = Math.max(...values)
          this.min = Math.floor(minValue)
          this.max = Math.ceil(maxValue)
          this.noData = false
          this.renderMap()
        }
        this.myChart.hideLoading()
      })
    },
    // 查询业务指标
    getIndcList() {
      getPerIndcList({ opsDept: this.opsDept }).then((res) => {
        if (res.code == 200) {
          this.optionArr = res.data
          this.searchForm.itemIdx = res.data[0] && res.data[0].dictValue
          this.date = ''
          this.noData = true
          this.mapData.features = []
          this.perData = []
          this.getPerEchartsData()
        }
      })
    },
    handleChange() {
      if (this.isOutletAdmin || this.isCommonManager) {
        this.level = '2'
      } else {
        this.level = 1
      }
      this.getPerEchartsData()
    },
    renderMap() {
      echarts.registerMap('hotMap', this.mapData)
      const option = {
        // title:{
        //     text:'热力图'
        // },
        tooltip: {
          show: false,
          trigger: 'item',
          // position: "top",
          backgroundColor: 'rgba(0,0,0,.5)',
          borderColor: '#5aabd3',
          // position:['40%','10%'],
          formatter: (params) => {
            console.log(params, 'params')
            if (this.level == '1') {
              const value = params?.data?.value?.toFixed(2)
              return `<div style="color:#fff;width:300px;min-height:100px;"><div style="white-space:pre-wrap">总行行政网格：${params.data.relateGrids}</div><div style="white-space:pre-wrap">归属支行：${params.data.relateDepts}</div><div>整体${params.data.itemName}：${value}%</div></div>`
            }
            return `<div style="color:#fff;width:300px;min-height:100px;"><div style="white-space:pre-wrap">支行行政网格：${params.data.relateGrids}</div><div>归属客户经理：${params.data.relateUsers}</div></div>`
          }
        },
        // 地图偏移位置
        layoutCenter: ['50%', '50%'],
        layoutSize: '170%',
        visualMap: {
          show: true,
          min: this.min,
          max: this.max,
          text: ['高', '低'],
          realtime: false,
          calculable: true,
          inRange: {
            color: [
              '#caf0f8',
              '#ade8f4',
              '#90e0ef',
              '#48cae4',
              '#00b4d8',
              '#0096c7',
              '#0077b6',
              '#023e8a',
              '#03045e'
            ]
          },
          bottom: 60
        },
        series: [
          {
            name: '图层名称',
            type: 'map',
            map: 'hotMap',
            selectedMode: false,
            roam: true,
            // select:{
            //     itemStyle:{
            //         areaColor:'#fff',
            //     },
            // },
            itemStyle: {
              // normal:{
              //     areaColor:'#fff',
              //     borderColor:'#fff',
              //     borderWidth:2,
              // },
              // emphasis:{
              //     areaColor:'#222',
              // }
            },
            // 高亮
            emphasis: {
              // disabled:true,
              itemStyle: {
                // areaColor:'skyblue',
                borderWidth: 2,
                shadowOffsetX: 2,
                shadowOffsetY: 2,
                shadowColor: 'rgba(250,250,250,0.5)'
              }
            },
            label: {
              show: true,
              textStyle: {
                // fontSize:14,
                // color:'#526b63',
              },
              formatter: function(params) {
                // console.log(params,'222')
                const value =
                  params?.data?.evoFlag != 'true'
                    ? '0.00'
                    : params?.value?.toFixed(2)
                return (
                  '{num|' +
                  params.name +
                  '}' +
                  '\r\n' +
                  '{num|' +
                  value +
                  '%' +
                  '}'
                )
              },
              rich: {
                num: {
                  color: '#fff',
                  fontSize: 14,
                  // fontWeight:'bold',
                  padding: [5, 2, 0, 0]
                }
              }
              // emphasis:{
              //     show:true,
              //     color:'#fff',
              //     fontSize:20
              // },
            },
            data: this.perData
          }
        ]
      }
      option.series[0].data.forEach((item) => {
        // console.log(item,item.itemStyle)
        // 设置颜色区间
        if (item.evoFlag != 'true') {
          item.itemStyle = {
            color: '#ddd',
            borderColor: '#222',
            borderWidth: 1
          }
          item.emphasis = {
            disabled: true
          }
        } else {
          item.itemStyle = {}
          item.emphasis = {
            disabled: false,
            itemStyle: {
              borderWidth: 2,
              shadowOffsetX: 2,
              shadowOffsetY: 2,
              shadowColor: 'rgba(250,250,250,0.5)'
            }
          }
        }
      })
      this.myChart.setOption(option, true)

      // 单击某个区域
      this.myChart.on('click', (params) => {
        console.log('click', params)
        // if(this.level == '1'){
        // this.level = 2;
        // this.code = params.data.code;
        // this.getPerEchartsData();
        // }
        if (params.data.evoFlag != 'true') {
          return
        }
        if (this.level == '1') {
          this.code1 = params.data.code
        }
        if (this.level == '2') {
          this.code2 = params.data.code
        }
        this.layerInfo = params.data
        this.getModalInfo()
        // this.showDialog=true;
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.main {
  padding-top: 0px !important;
  padding-bottom: 10px !important;
}
.echart-box {
  position: relative;
  .echart {
    width: 100%;
    height: 650px;
    border: 1px solid #ddd;
  }
  .grid-color {
    min-height: 100px;
    min-width: 87px;
    position: absolute;
    top: 10px;
    left: 10px;
    border-radius: 3px;
    background: rgba(164, 173, 179, 1);
    padding: 3px 10px;
    .box {
      display: flex;
      align-items: center;
      margin: 5px 0;
    }
    .color-box {
      display: inline-block;
      width: 10px;
      height: 10px;
    }
    .range {
      color: #fff;
      font-size: 12px;
      margin-left: 6px;
      display: inline-block;
      min-width: 50px;
    }
  }
  .nodate-tip {
    position: absolute !important;
    text-align: center;
    color: #b9b9b9;
    line-height: 500px;
  }
}
.searchForm {
  .date {
    display: inline-block;
    line-height: 36px;
  }
  .back {
    // color: #4886f8;
    margin-right: 10px;
    // cursor: pointer;
  }
  .date {
    font-size: 14px;
    color: #606266;
    font-weight: 700;
  }
}
.dialog-container {
  .child-main {
    max-height: 600px;
    overflow-y: auto;
  }
  .branch-box {
    border: 1px solid #ddd;
    border-radius: 5px;
    margin-bottom: 5px;
    padding: 5px 5px;
  }
  .org-box {
    padding: 5px 0px 5px 15px;
    font-weight: 400;
    font-size: 14px;
    color: #3d3d3d;
  }
  .my-title {
    font-weight: 400;
    font-size: 14px;
    color: #3d3d3d;
    line-height: 30px;
  }
  .dialog-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .btn {
      margin-right: 32px;
    }
  }
  ::v-deep .el-dialog__body {
    padding-top: 10px;
  }
  ::v-deep .el-dialog:not(.is-fullscreen) {
    margin-top: 20vh !important;
  }
  .outlet-box {
    margin-left: 10px;
  }
}
</style>
