<template>
  <div class="main">
    <div>
      <el-form
        ref="searchForm"
        :model="searchForm"
        class="searchForm"
        label-width="120px"
      >
        <el-row>
          <el-col :span="6">
            <el-form-item label="业务指标" prop="indexId">
              <el-select
                v-model="searchForm.indexId"
                placeholder="请选择业务指标"
                @change="handleChange"
              >
                <el-option
                  v-for="item in optionArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="区域类型" prop="shapeType">
              <el-select
                v-model="searchForm.shapeType"
                @change="handleChange"
                @clear="handleChange"
              >
                <el-option
                  v-for="item in shapeTypeList"
                  :key="item.label"
                  :label="item.label"
                  :value="item.label"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="区域名称" prop="shapeIds">
              <el-select
                v-model="searchForm.shapeIds"
                multiple
                clearable
                @change="handleChange"
                @clear="handleChange"
              >
                <el-option
                  v-for="item in shapeNameList"
                  :key="item.label"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="归属支行" prop="branchIds">
              <el-select
                v-model="searchForm.branchIds"
                placeholder="请选择"
                multiple
                clearable
                @change="handleChange"
                @clear="handleChange"
              >
                <el-option
                  v-for="item in branchList"
                  :key="item.label"
                  :label="item.label"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="归属网点" prop="outletIds">
              <el-select
                v-model="searchForm.outletIds"
                placeholder="请选择"
                multiple
                clearable
                @change="handleChange"
                @clear="handleChange"
              >
                <el-option
                  v-for="item in outletList"
                  :key="item.label"
                  :label="item.label"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="归属客户经理" prop="manager">
              <el-input
                v-model="searchForm.userName"
                placeholder="请输入"
                clearable
                @clear="handleChange"
                @keyup.enter.native="handleChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="统计日期" prop="dt">
              <el-date-picker
                v-model="searchForm.dt"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择"
                :clearable="false"
                @change="handleChange"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <span class="date" style="float: right;">统计日期（T+1）：{{ date || "-" }}</span>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div ref="mapContainer" class="map-container" />

    <div class="dialog-container">
      <el-dialog
        :visible.sync="visible"
        title=""
        width="50%"
        class="dialog-header"
        :close-on-click-modal="false"
        @close="closeDialog"
      >
        <div class="child-main">
          <div class="my-title">区域名称：{{ areaForm.shapeName }}</div>
          <div class="my-title">网格名称：{{ areaForm.gridName }}</div>
          <div class="my-title">
            归属支行：{{ areaForm.branchs ? areaForm.branchs.join("，") : "-" }}
          </div>
          <div class="my-title">
            归属网点：{{ areaForm.outlets ? areaForm.outlets.join("，") : "-" }}
          </div>
          <div class="my-title">
            归属客户经理：{{
              areaForm.managers ? areaForm.managers.join("，") : "-"
            }}
          </div>
          <div class="my-title">
            整体{{ indexLabel }}：{{ areaForm.indexValue }}
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import {
  getHeatMapGsList,
  getHeatMapLsList,
  getHeatMapIndexList,
  getShapeNameLsList,
  getShapeNameGsList
} from '@/api/grid/performance/collect.js'
import { deptTreeSelect } from '@/api/system/user.js'
import { queryAreas } from '@/api/grid/draw-area.js'
import WKT from 'terraformer-wkt-parser'
import { Message } from 'element-ui'

export default {
  props: {
    selectedTab: {
      type: String,
      default: '1'
    }
  },
  data() {
    return {
      mapLoading: false,
      map: null, // 地图
      searchForm: {
        dt: '',
        indexId: '', // 指标id
        shapeType: '',
        shapeIds: [],
        branchIds: [],
        outletIds: [],
        manager: ''
      },
      optionArr: [],
      Loading: false,
      opsDept: '',
      date: '',
      min: 0,
      max: 100,
      showDialog: false,
      layerInfo: {},
      shapeTypeList: [], // 区域类型列表
      shapeNameList: [], // 区域名称列表
      sortedShapeIds: [],
      areaForm: {},
      visible: false,
      branchList: [],
      outletList: [],
      deptTreeData: []
    }
  },
  computed: {
    indexLabel() {
      return this.searchForm.indexId
        ? this.optionArr.filter(
          (item) => item.value === this.searchForm.indexId
        )[0].label
        : ''
    }
  },
  watch: {
    selectedTab: {
      handler(val) {
        if (val) {
          this.opsDept = val === '1' ? 'ls' : 'gs'
          this.removeALLOverlays()
          this.init()
        }
      },
      immediate: true
    },
    'searchForm.shapeType'(newVal) {
      this.getShapeNameList()
    },
    'searchForm.branchIds'(newVal) {
      this.searchForm.outletIds = []
      if (newVal.length === 0) {
        this.outletList = []
      } else {
        const matchArr = this.deptTreeData.filter((item) =>
          newVal.includes(item.id)
        )
        const result = []
        for (const item of matchArr) {
          result.push(...item.children)
        }
        this.outletList = result
      }
    }
  },
  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}`
  },
  mounted() {
    this.getDept()
    this.initMap()
  },
  methods: {
    init() {
      Promise.all([this.getIndcList(), this.getShapeList()]).then(() => {
        this.getPerEchartsData()
      })
    },
    initMap() {
      // 初始化地图
      this.mapLoading = true
      this.map = new BMapGL.Map(this.$refs.mapContainer)
      const localCity = new BMapGL.LocalCity()
      localCity.get((result) => {
        console.log(result.center)
        this.cityCenter = result.center
        this.map.centerAndZoom(result.center, 14)
      })
      this.map.enableScrollWheelZoom()
      this.mapLoading = false
    },
    removeALLOverlays() {
      if (!this.map) return
      const overlays = this.map?.getOverlays()
      overlays.map((overlay) => {
        this.map.removeOverlay(overlay)
      })
    },
    getColorByValue(value) {
      const ratio =
        this.min === this.max
          ? 0.5
          : Math.pow((value - this.min) / (this.max - this.min), 0.8)

      const start = { r: 153, g: 204, b: 255 }
      const end = { r: 51, g: 102, b: 153 }

      const r = Math.round(start.r + (end.r - start.r) * ratio)
      const g = Math.round(start.g + (end.g - start.g) * ratio)
      const b = Math.round(start.b + (end.b - start.b) * ratio)

      return `rgb(${r}, ${g}, ${b})`
    },
    showWKT(data, showModal = false) {
      this.removeALLOverlays()
      if (!data.length) {
        const localCity = new BMapGL.LocalCity()
        localCity.get((result) => {
          this.map.centerAndZoom(result.center, 14)
        })
      }
      let allPoints = []
      data.map((item) => {
        const wkt = item.shapeWkt
        const geojson = WKT.parse(wkt)
        allPoints = allPoints.concat(
          this.renderPolygon(geojson.coordinates, item, showModal, item)
        )
      })
      console.log(allPoints, 'allPoints')
      this.map.setViewport(allPoints)
    },
    /**
     * 绘制多边形覆盖物
     */
    renderPolygon(coordinates, val, showModal, data) {
      const pointArr = []
      const than = this
      coordinates.map((ring) => {
        const points = ring.map((coord) => {
          const point = new BMapGL.Point(coord[0], coord[1])
          pointArr.push(point)
          return point
        })
        const polygon = new BMapGL.Polygon(points, {
          strokeColor: this.getColorByValue(data.indexValue),
          strokeWeight: 3,
          strokeOpacity: 0.8,
          strokeStyle: 'solid',
          fillColor: this.getColorByValue(data.indexValue),
          fillOpacity: 0.4,
          areaValue: val // 添加额外的属性
        })

        function getCenterPoint(path) {
          let x = 0
          let y = 0
          for (let i = 0; i < path.length; i++) {
            x += parseFloat(path[i].lng)
            y += parseFloat(path[i].lat)
          }
          x /= path.length
          y /= path.length
          return new BMapGL.Point(x, y)
        }

        const point = getCenterPoint(polygon.getPath())
        const label = new BMapGL.Label(
          `<span>${data.shapeName}</span><br><span style="color: #555555">${data.indexValue}</span>`,
          {
            position: point
          }
        )
        label.setStyle({
          border: 'none',
          background: 'transparent',
          textAlign: 'center'
        })
        // if (showModal) {
        //   // 点击单个区域 显示详情弹窗
        //   const { shapeList } = this.$store.state.featuredAreas
        //   const shapeItem = shapeList[0].children.find(
        //     (shape) => shape.shapeId === id
        //   )
        //   if (shapeItem) {
        //     console.log(shapeItem)
        //     this.areaForm = shapeItem
        //     this.infoType = 'SHOW'
        //     this.visible = true
        //     this.currentPolygon = polygon
        //     this.originalPlygon = polygon.getPath()
        //     this.currentPolygonType = 'noAdd'
        //   } else {
        //     this.$message({
        //       type: 'info',
        //       message: '未找到图形信息'
        //     })
        //   }
        // }
        polygon.addEventListener('click', function(e) {
          than.areaForm = e.target._config.areaValue || {}
          than.visible = true
        })
        this.map.addOverlay(polygon)
        this.map.addOverlay(label)
      })
      return pointArr
    },
    /**
     * 多边形点击事件
     */
    handlerPolygon(e) {
      const currentColor = e.target.getFillColor()
      const { shapeList } = this.$store.state.featuredAreas
      const shapeId = e.target._config.shapeId
      const shapeItem = shapeList[0].children.find(
        (shape) => shape.shapeId === shapeId
      )
      if (shapeItem) {
        this.areaForm = shapeItem
        this.infoType = 'SHOW'
        console.log(shapeItem)
      } else {
        this.$message({
          type: 'info',
          message: '未找到图形信息'
        })
      }
      if (currentColor === this.layerInfo.color) {
        this.setAllFillColor()
        e.target.setFillOpacity(0.1)
        e.target.setFillColor('red')
        e.target.setStrokeColor('red')
        e.target.setStrokeWeight(5)
        if (shapeItem) this.visible = true
      } else {
        e.target.setFillOpacity(0.4)
        e.target.setFillColor(this.layerInfo.color)
        e.target.setStrokeColor(this.layerInfo.color)
        e.target.setStrokeWeight(3)
        this.cancelSaveArea()
      }
    },
    // 查询地图数据
    getPerEchartsData() {
      const params = {
        ...this.searchForm
      }
      const Api = this.opsDept === 'ls' ? getHeatMapLsList : getHeatMapGsList
      Api(params).then((res) => {
        if (res.code === 200) {
          const arr = res.data || []
          if (!arr.length) {
            Message.warning('暂无数据')
            return
          }
          this.date = arr[0].dt
          const values = res.data.map((item) => item.indexValue)
          const minValue = Math.min(...values)
          const maxValue = Math.max(...values)
          this.min = Math.floor(minValue)
          this.max = Math.ceil(maxValue)
          this.showWKT(res.data)
        }
      })
    },
    // 查询业务指标
    getIndcList() {
      return new Promise((resolve) => {
        getHeatMapIndexList({ type: this.opsDept }).then((res) => {
          if (res.code === 200) {
            this.optionArr = Object.entries(res.data || {}).map(
              ([key, label]) => ({
                value: key,
                label: label
              })
            )
            this.searchForm.indexId = this.optionArr[0]?.value
            this.date = ''
            // this.getPerEchartsData()
            resolve()
          }
        })
      })
    },

    // 查询区域类型
    getShapeList() {
      return new Promise((resolve) => {
        queryAreas().then((res) => {
          if (res.code === 200) {
            this.shapeTypeList = res.data.map((item) => {
              return {
                label: item.layerName,
                value: item.layerId
              }
            })
            this.searchForm.shapeType = this.shapeTypeList[0].label
            resolve()
          }
        })
      })
    },

    // 查询区域名称
    getShapeNameList() {
      this.searchForm.shapeIds = []
      const Api =
        this.opsDept === 'ls' ? getShapeNameLsList : getShapeNameGsList
      Api({ shapeType: this.searchForm.shapeType }).then((res) => {
        if (res.code === 200) {
          this.shapeNameList = Object.entries(res.data || {}).map(
            ([value, label]) => ({
              value: value,
              label: label
            })
          )
        }
      })
    },

    getDept() {
      deptTreeSelect().then((res) => {
        if (res.code === 200) {
          this.deptTreeData = res.data?.[0]?.children || []
          this.branchList = res.data?.[0]?.children || []
        }
      })
    },
    closeDialog() {
      this.visible = false
    },
    handleChange() {
      this.date = null
      this.$nextTick(() => {
        this.removeALLOverlays()
        this.getPerEchartsData()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.main {
  padding-top: 0px !important;
  padding-bottom: 10px !important;
}
.map-container {
  width: 100%;
  height: 650px;
  border: 1px solid #ddd;
  position: relative;
}
.area-info-modal {
  width: 390px;
  color: #fff;
  position: absolute;
  top: 40px;
  right: 40px;
  background-color: rgba(0, 0, 0, 0.7);
  border-radius: 8px;
  z-index: 1000;
  .form-box {
    padding-right: 20px;
  }
  .area-form-item {
    margin-bottom: 0px;
    span {
      color: #ccc;
      line-height: 24px;
      display: inline-block;
    }
    .module-tips {
      color: #ffa0a0;
    }
  }
  .area-radio {
    ::v-deep .el-radio {
      margin-right: 15px;
    }
    ::v-deep .el-radio__label {
      padding-left: 0;
      color: #ccc;
    }
    ::v-deep .el-radio__input.is-disabled .el-radio__inner {
      background-color: #c6c6c6;
      border-color: #6d6d6d;
    }
    ::v-deep .el-radio__input.is-disabled.is-checked .el-radio__inner::after {
      background-color: #5c5c5c;
    }
  }
  .area-form-item1 {
    margin-bottom: 6px;
  }
  h4 {
    font-size: 18px;
    color: #ffffff;
    line-height: 25px;
    font-weight: 600;
    text-align: center;
    margin: 24px 0;
    position: relative;
  }
  .el-icon-close {
    position: absolute;
    right: 24px;
    top: 0;
    font-size: 18px;
    cursor: pointer;
  }
  ::v-deep .el-form-item__label {
    color: #fff;
    font-weight: normal;
  }
}
.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>
