<template>
  <div class="warning-box">
    <cpt-card>
      <div class="card-title">
        <img class="title-icon" src="../../../../assets/img/shuju/title-tip.png" />
        <div class="title-label">
          网格党建平面图&nbsp;&nbsp;
          <!-- <el-cascader 
            v-model="selectAgency"
            :options="propTree" 
            :props="{ checkStrictly: true }" 
            :show-all-levels="false"
            :getCheckedNodes="getCheckedNodes" 
            @change="handleCascader">
          </el-cascader> -->
        </div> 
      </div>
      <div class="card-echart">
        <div class="card-left">
          <!-- <div class="card-left-title">党员学历统计</div> -->
          <div class="card-flex">
            <div class="echart-wr echart-wr100">
              <screen-echarts-frame class="echart-org"
                              @myChartMethod="pieInitOks"
                              ref="eduChart"></screen-echarts-frame>
            </div>
          </div>
          <div class="warning-box-bottom">
            <screen-table
              :headerList="headerEduList"
              :tableData="eduList"
              :headerStyle="headerStyle"
              :tableContentStyle="headerStyle"
              :visibleLoading="visibleLoading"
              :operate="false"
              @row="handleClickRow"
            ></screen-table>
            <div class="pagination">
              <el-pagination
                :current-page="pageNo"
                :page-size="pageSize"
                background
                layout="prev, pager, next"
                @size-change="pageSizeChangeHandle"
                @current-change="pageCurrentChangeHandle"
                :total="total"
              >
              </el-pagination>
            </div>
          </div>
        </div>
        <div class="card-right">
          <screen-map class="map"
                      ref="map"
                      @clickFeature="clickProject"
                      @lookMore="lookMore"
                      :showPolygonLayer="true"
                      :isAddOpenlay="true"
                      :clickType="'popup'"
                      :showIconLayer="true"
                      :showPolIconLayer="true"
                      :areaScale="0.1"></screen-map>
        </div>
      </div>
    </cpt-card>
    <member-info v-if="showedUnitMoreInfo"
              :list="unitAclist"
              ref="unitdetailInfo"
              @close="showedUnitMoreInfo = false" />
    <people-more v-show="showedMoreInfo"
              v-if="userId"
              :userId="userId"
              :gridName="''"
              @close="showedMoreInfo = false" />
  </div>
</template>

<script>
import { requestPost } from "@/js/dai/request";
import screenTable from "../components/screen-table/index";
import cptCard from "@/views/modules/visual/cpts/card";
import nextTick from "dai-js/tools/nextTick";
import screenEchartsFrame from "../components/screen-echarts-frame";
import { pieOption } from './options'
import * as echarts from 'echarts';
import screenMap from "@/views/modules/visual/components/screen-map";
import memberInfo from './memberInfo.vue'
import peopleMore from "@/views/modules/visual/basicinfo/cpts/people-more";

export default {
  name: "gridParty",
  components: {
    cptCard,
    screenTable,
    screenEchartsFrame,
    screenMap,
    memberInfo,
    peopleMore
  },
  data() {
    return {
      headerStyle: [
        {
          'max-width': '60px'
        },
        {
          'min-width': '100px'
        },
        {
          'min-width': '100px'
        },
        {
          'min-width': '160px'
        }
      ],
      headerEduList: [
        { title: "序号", coulmn: 'index' },
        { title: "姓名", coulmn: 'name' },
        { title: "手机号码", coulmn: 'mobile' }
      ],
      noEduInit: false,
      selectAgency: null,
      eduTotalCount: 0,
      propTree: [],
      visibleLoading: true,
      agencyId: '',
      orgType: '',
      eduCode: '', // 点击饼状图 查询列表，查询地图
      pageNo: 1,
      pageSize: 10,
      total: 0,
      eduItem: [],
      eduList: [],
      pieEduOptions: null,
      showedUnitMoreInfo: false,
      unitAclist: [],
      // 地图相关*********************************************start
      isfirstInit: true,
      agencyInfo: {},//登陆者的组织信息：主要为了获取地图中心点和level
      iconUrlArray: [],
      parentPolygon: [],
      orgId: '',
      unitMapList: [],
      showedMoreInfo: false,
      userId:"",
      // 地图相关*********************************************end
    };
  },
  async mounted() {
    await nextTick(100);
    // await this.getAgencyList()
    this.agencyId  = this.$store.state.user.agencyId
    this.getEduCount(this.$store.state.user.agencyId) // 饼状统计图
    this.getEduList() // 左下角列表数据
    // 地图相关start
    this.iconUrlArray = [
      require('../../../../assets/img/shuju/measure/lxdj.png'),
      require('../../../../assets/img/shuju/measure/lxzz.png'),
      require('../../../../assets/img/shuju/measure/qydw.png'),
      require('../../../../assets/img/shuju/measure/jgzs.png'),
      require('../../../../assets/img/shuju/measure/qita.png'),
      require('../../../../assets/img/shuju/measure/minban.png'),
      require('../../../../assets/img/shuju/measure/jijin.png'),
      require('../../../../assets/img/shuju/measure/other.png')
    ]
    await this.loadOrgData()
    await this.getWorkUserInfo()
    // this.loadMap()
    this.getMapData()
    // this.isfirstInit = false
    // 地图相关end
  },
  methods: {
    loadMap () {
      if (this.isfirstInit) {
        const polIconUrlArray = [
          'https://elink-esua-epdc.oss-cn-qingdao.aliyuncs.com/epmet/test/20211116/a219130b6bc74b0b80b5ddb0fce0892a.png'
        ]
          this.$refs.map.loadMap(this.agencyInfo, this.parentPolygon, polIconUrlArray, this.unitMapList, this.iconUrlArray, null,)
      } else {
        this.$refs.map.refreshMap(this.agencyInfo, this.parentPolygon, this.unitMapList)
      }
    },
    // 加载组织树
    async getAgencyList(node, resolve) {
      const url = '/gov/org/customeragency/agencygridtree'
      // let params = {
      //   agencyId: this.$store.state.user.agencyId,
      // };
      const { data, code, msg } = await requestPost(url);
      if (code === 0) {
        this.selectAgency = [`${data.agencyId}-${data.level}`]
        this.orgType = data.level
        this.agencyId = data.agencyId
        let arr = []
        arr.push(data)
        this.propTree = arr && this.getTreeData(arr)
      } else {
      }
    },
    // 组织树相关方法
    getTreeData(data){
      if (!Array.isArray(data)) return []
      let arr = data.map(item => {
        let _item = {}
        if (item.subAgencyList) {
          if (item.subAgencyList.length === 0) {
            _item = { 
              label: item.agencyName,
              value: item.agencyId + '-' + item.level,
              level: item.level,
              children: undefined 
            }
          } else _item = { 
            label: item.agencyName,
            value: item.agencyId + '-' + item.level,
            level: item.level,
            children: this.getTreeData(item.subAgencyList)}
        } else {
          _item = { 
            label: item.agencyName,
            value: item.agencyId + '-' + item.level,
            level: item.level,
          }
        }
        return _item
      })
      return arr
    },
    // 组织点击事件
    async handleCascader(val) {
      const _arr = val[val.length - 1].split('-')
      const orgType = _arr[1] !== 'grid' ? 'agency': 'grid'
      this.agencyId = _arr[0]
      this.orgId = _arr[0]
      this.orgType = orgType
      this.noEduInit = false
      this.agencyInfo = { ...this.orgData }
      this.eduCode = ''
      await this.loadOrgData()
      this.getEduCount(_arr[0])
      this.eduList = []
      this.pageNo = 1;
      this.pageSize = 10;
      await this.getEduList()
      this.getMapData()
    },
    // 图标相关*********************************
    // 饼状统计
    async getEduCount(agencyId) {
      const url = "/epmetuser/icVolunteerPoly/statistics";
      let params = {
        agencyId
      };
      const { data, code, msg } = await requestPost(url, params);
      if (code === 0) {
        this.eduItem = data.map(item => {
          return {
            ...item,
            name: item.label,
            isClick: false
          }
        })
        
        this.eduTotalCount = 0
        data.forEach(item => {
          this.eduTotalCount += Number(item.value)
        })
        this.initEduCharts()
      } else {
      }
    },
    initEduCharts() {
      // const eId = document.getElementById('echartOrg')
      // let _charts = echarts.init(eId)
      let option = {
      
      }
      let legend = {
        show: true,
        orient: 'vertical',
        top: '20%',
        right: 0,
        textStyle: {
          width: 90,
          color: '#fff',
          rich: {
            a: {
              width: 90
            }
          }
        },
        formatter: name => {
          for (let a = 0; a < this.eduItem.length; a++) {
            // this.data  这个数据中有名称和次数
            if (this.eduItem[a].name === name) {
              //两个名称进行对比，取出对应的次数
              let params1 = name + "\n"; //然后return你需要的legend格式即可
              let tmp = params1.split("\n");
              let res = "" + params1;
              for (let i in tmp) {
                res = res.replace(tmp[i], "");
              }
              return res + params1;
            }
          }
        }
      }
      this.pieEduOptions = pieOption(this.pieEduChartS)
      this.pieEduOptions.legend = { ...legend }
      this.clickEduPie(0)
      let fun = params => {
        this.clickEduPie(params.dataIndex)
      }
      this.$refs.eduChart.handleClick(fun)
    },
    // 点击饼状图
    clickEduPie (seriesIndex) {
      let _code = ''
      let isClick = false
      this.eduItem.forEach((element, index) => {
        if (index === seriesIndex) {
          _code = element.code

          if (!this.noEduInit) isClick = false
          else {
            element.isClick = !element.isClick
            isClick = element.isClick
          }

          element.label = {
            show: true,

          };
          element.labelLine = {
            show: true,
            lineStyle: {
              opacity: 1,
            }

          };
        } else {
          element.isClick = false
          element.label = {
            show: false,

          };
          element.labelLine = {
            show: false,
            lineStyle: {
              opacity: 0,
              color: 'rgba(255,255,255,0)'
            }

          };

        }
      });
      this.eduCode = isClick && _code || ''
      this.pieEduOptions.title.text = this.eduTotalCount
      this.pieEduOptions.series[1].data = this.eduItem
      // this.$refs.pieChart.hideLoading()
      this.$refs.eduChart.setOption(this.pieEduOptions)
      if (this.noEduInit) {
        const _arr = this.selectAgency[this.selectAgency.length - 1].split('-')
        const orgType = _arr[1] !== 'grid' ? 'agency': 'grid'
        this.pageNo = 1
        this.pageSize = 10;
        this.eduList = []
        this.getEduList(isClick && _code || '')
        this.getMapData(isClick && _code || '')
      }
      this.noEduInit = true
    },
    // 列表相关*************************************
    // 请求列表数据
    async getEduList(_code) {
      this.visibleLoading = true
      const url = "/epmetuser/icVolunteerPoly/list";
      let params = {
        code: this.eduCode,
        agencyId: this.agencyId,
        pageNo: this.pageNo,
        pageSize: this.pageSize
      };
      const { data, code, msg } = await requestPost(url, params);
      if (code === 0) {
        this.eduList = data.list.map((item, index) => {
          return {
            ...item,
            index: index + 1
          }
        })
        this.total = data.total
      } else {
        this.$message.error(msg)
      }
      this.visibleLoading = false
    },
    pieInitOks (dom) {
      this.pieEduChartS = dom
      // this.pieInitState = true
    },
    // 点击列表
    handleClickRow(val) {
      this.servicelist(val.idCard)
    },
    // 多元-社区自组织服务需求分页列表
    async servicelist (idCard) {
      const url = "/heart/residemand/service-list";
      let params = {
        pageNo: 1,
        pageSize: 1000,
        type: 'volunteer', // 志愿者：volunteer；社区自组织：community_org；
        idCard: idCard, // volunteer时传入此参数。
        serverId: ''
      };
      const { data, code, msg } = await requestPost(url, params);
      if (code === 0) {
        if (data.list.length > 0) {
          this.showedUnitMoreInfo = true
          this.unitAclist = data.list
          this.$nextTick(() => {
            this.$refs['unitdetailInfo'].getDetail(this.unitAclist[0].demandRecId)
          }) 
        } else {
          this.showedUnitMoreInfo = false
          this.unitAclist = []
          this.$message.warning('该志愿者还没有需求')
        }
      } else {
      }
    },
    getCheckedNodes(val) {
      console.log('val-nnn', val)
    },
    pageSizeChangeHandle(val) {
      this.pageNo = 1;
      this.pageSize = val;
      this.getEduList(this.eduCode)
    },
    pageCurrentChangeHandle(val) {
      this.pageNo = val;
      this.getEduList(this.eduCode)
    },
    async loadOrgData () {
      const url = "/gov/org/agency/maporg"
      let params = {
        orgId: this.orgId,
        level: this.orgType
      }

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

      if (code === 0) {

        this.orgData = data
        this.orgId = this.orgData.id
        this.orgType = this.orgData.level
        this.parentPolygon = []
        this.parentPolygon = data.children.map(item => {
          return {
            ...item,
            color: "#00E5ED",
            fillColor: "rgba(0, 229, 237, 0.16)"
          }
        })

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

    },
    // 获取当前管理员信息
    getWorkUserInfo () {
      const url = '/epmetuser/customerstaff/staffbasicinfo'
      let params = {}
      window.app.ajax.post(
        url,
        params,
        (data, rspMsg) => {
          this.agencyInfo = data
          if (!data.latitude) {
            this.agencyInfo.latitude = 36.072227
          }
          if (!data.longitude) {
            this.agencyInfo.longitude = 120.389455
          }
          if (!data.level) {
            this.agencyInfo.level = 'street'
          }

        },
        (rspMsg, data) => {
          this.$message.error(rspMsg)
        }
      )

    },
    // 获取位置信息
    async getMapData () {
      const url = "/epmetuser/icVolunteerPoly/mapData"
      let params = {
        agencyId: this.agencyId,
        code: this.eduCode
      }
      const { data, code, internalMsg } = await requestPost(url, params)
      if (code === 0) {
          this.unitMapList = data
          this.loadMap()
          this.isfirstInit = false
          this.$refs.map.handleClosePopup()
      } else {
        this.$message.error(internalMsg)
          this.unitMapList = []
          this.loadMap()
          this.isfirstInit = false
          this.$refs.map.handleClosePopup()
      }
    },
    //点击项目
    async clickProject (feature) {
      this.userId = ''
      const featureInfo = feature.values_.properties.info
      this.userId = feature.values_.properties.info.id
      let coordinate = [featureInfo.longitude, featureInfo.latitude]
      let {name, gridName, houseName, mobile, idCard, gzdw, rhzk, icResiUser} = feature.values_.properties.info
      name = name ? name : '--'
      gridName = gridName ? gridName : '--'
      houseName = houseName ? houseName : '--'
      mobile = mobile ? mobile : '--'
      idCard = idCard ? idCard : '--'
      gzdw = gzdw ? gzdw : '--'
      rhzk = rhzk ? rhzk : '--'
      let showData = `
                <div style='font-size:16px; color:#FFFFFF;'>个人信息</div>
                <div style='font-size:12px; color:#FFFFFF;margin-top:10px'>姓名：
                  <span>`+ name + `</span>
                </div>
                <div style='font-size:12px; color:#FFFFFF;margin-top:10px'>所属网格：
                  <span>`+ gridName + `</span>
                </div>
                <div style='font-size:12px; color:#FFFFFF;margin-top:5px'>所属房屋：
                  <span>`+ houseName + `</span>
                </div>
                <div style='font-size:12px; color:#FFFFFF;margin-top:5px'>手机号：
                  <span>`+ mobile + `</span>
                </div>
                <div style='font-size:12px; color:#FFFFFF;margin-top:5px'>身份证号：
                  <span>`+ idCard + `</span>
                </div> 
                <div style='font-size:12px; color:#FFFFFF;margin-top:5px'>工作单位：
                  <span>`+ gzdw + `</span>
                </div> 
                <div style='font-size:12px; color:#FFFFFF;margin-top:5px'>人户状况：
                  <span>`+ rhzk + `</span>
                </div>
                `
        const isShowMore = icResiUser ? true : false
        this.$refs.map.handleShowPopup(showData, coordinate, isShowMore)
    },
    lookMore(e) {
      this.userId = this.userId
      this.showedMoreInfo = true
    }
  },
};
</script>

<style
  lang="scss"
  src="@/assets/scss/modules/visual/warning.scss"
  scoped
></style>
<style
  lang="scss"
  src="@/assets/scss/modules/visual/basicInfoMain.scss"
  scoped
></style>
<style lang="scss" scoped>
.card-title {
  display: flex;
  align-items: center;
  cursor: pointer;
  .title-icon {
    display: block;
    width: 46px;
    height: 34px;
    box-sizing: border-box;
    margin-right: 6px;
  }
  ::v-deep .el-dropdown {
    font-size: 18px;
    color: #fff;
    font-weight: 800;
  }
  .title-time {
    display: flex;
    align-items: center;
    box-sizing: border-box;
    margin-left: 30px;
    font-size: 14px;
    color: #fff;
    .title-time-label {
      margin-right: 10px;
    }
    ::v-deep .el-date-editor--month {
      width: 100px;
      .el-input__inner {
        width: 100px;
        height: 24px;
        box-sizing: border-box;
        padding: 0;
        font-size: 14px;
        color: #fff;
        line-height: 24px;
        text-align: center;
        background: #06186D;
        border: 1px solid #1A64CC;
        border-radius: 2px;
      }
      .el-input__prefix {
        display: none;
      }
      .el-input__suffix {
        right: 0;
        .el-input__icon {
          line-height: 24px;
        }
      }
      
    }
  }
  .title-label {
    font-size: 20px;
    font-weight: 800;
    ::v-deep .el-input {
      
      width: 180px;
      .el-input__inner {
        font-size: 18px;
        // font-weight: 800;
        color: #fff;
        background: #06186d;
        border: 1px solid #1a64cc;
      }
      .el-icon-arrow-down::before {
          content: "\e790";
      }
    }
  }
}
.card-echart {
  display: flex;
  margin-top: 40px;
  height: 100%;
  .card-left {
    position: relative;
    flex: 1;
    height: 100%;
    width: 50%;
    .card-flex {
      width: 100%;
      display: flex;
    }
  }
  .card-right {
    position: relative;
    flex: 1;
    height: 790px;
    width: 50%;
    .map {
      height: 100%;
      width: 100%;
    }
    .div_map {
        box-sizing: border-box;
        height: 100%;
        color: #fff;
    }
  }
}
.card-left-title {
  position: relative;
  padding-left: 40px;
  font-size: 16px;
  font-weight: 500;
  color: #fff;
}
.card-left-title::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 20px;
  width: 12px;
  height: 12px;
  box-sizing: border-box;
  margin-top: -6px;
  background: #2865FA;
  border-radius: 50%;
}
.echart-wr {
  position: relative;
  flex-shrink: 0;
  width: 50%;
  height: 320px;
  box-sizing: border-box;
  .echart-org {
    width: 100%;
    height: 100%;
  }
  .echart-cicle {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 240px;
    height: 240px;
    box-sizing: border-box;
    margin-top: -120px;
    margin-left: -120px;
    border: 1px dashed rgba(0, 96, 240, 1);
    border-radius: 50%;
  }
  .echart-cicle0 {
    left: 80px;
    margin-left: 0;
  }
}
.echart-wr100 {
  width: 70%;
}
.warning-box-bottom {
  height: calc(100% - 500px);
  box-sizing: border-box;
  margin: 0;
  padding: 0 30px;
  // overflow-y: scroll;
}
</style>
