<template>
  <el-dialog :visible.sync="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form class="form" 
            :model="dataForm" 
            :rules="dataRule" 
            ref="dataForm" 
            @keyup.enter.native="dataFormSubmitHandle()" 
            :label-width="$i18n.locale === 'en-US' ? '120px' : '80px'">
      <el-form-item prop="categoryCode" label="类别">
          <el-select v-model="dataForm.categoryCode" @change="handelChange" placeholder="请选择类别">
              <el-option
              v-for="item in tagCategoryArr"
              :key="item.categoryCode"
              :label="item.categoryName"
              :value="item.categoryCode">
              </el-option>
          </el-select>
      </el-form-item>
      <el-form-item  prop="name" label="名称">
          <el-input  v-model="dataForm.name" placeholder="请输入名称"  style="width:250px"></el-input>
      </el-form-item>
      <!-- 下拉框组织的参数 -->
      <el-form-item  prop="orgId" label="所属组织" v-show="orgListSwitch">
          <el-cascader
              v-model="dataForm.orgId"
              :options="agencytree"
              placeholder="请选择所属组织"
              :props="{ expandTrigger: 'hover', label: 'orgName', value: 'orgId', children: 'subOrgList' }"
              ></el-cascader>
      </el-form-item>
      <!-- 网格党支部下拉框 -->
      <el-form-item prop="pid" label="所属上级" v-show="GridPartyBranchSwitch">
          <el-select v-model="dataForm.pid" placeholder="请选择所属上级">
              <el-option
              v-for="item in GridPartyBranchList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
              </el-option>
          </el-select>
      </el-form-item>
      <!-- 党委下拉框 -->
      <el-form-item prop="pid" label="所属上级" v-show="partyCommSwitch">
          <el-select v-model="dataForm.pid" placeholder="请选择所属上级">
              <el-option
              v-for="item in PartyCommList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
              </el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="排序">
          <el-input-number v-model="dataForm.sort" :min="0" :max="10" label="请输入排序"></el-input-number>
      </el-form-item>
      <el-form-item label="活动坐标"
                    prop="longitude"
                    style="display: block">
        <div class="item_width_1">

          <div class="div_map">
            <div id="app">

            </div>
            <div style="display: none" id="mapSeach_id" class="div_searchmap">
              <el-input class="item_width_4"
                        maxlength="50"
                        size="mini"
                        placeholder="请输入关键字"
                        v-model="keyWords">
              </el-input>
              <el-button style="margin-left: 10px"
                          type="primary"
                          size="mini"
                          @click="handleSearchMap">查询</el-button>
            </div>
          </div>

          <div id="lon_lat_id" style="margin-top: 10px; display: none">
            <span>经度</span>
            <el-input class="item_width_3"
                      maxlength="50"
                      placeholder="请输入经度"
                      v-model="dataForm.longitude">
            </el-input>
            <span style="margin-left: 20px">纬度</span>
            <el-input class="item_width_3"
                      maxlength="50"
                      placeholder="请输入纬度"
                      v-model="dataForm.latitude">
            </el-input>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
var map
var search
var markers
var infoWindowList
var geocoder // 新建一个正逆地址解析类
import debounce from 'lodash/debounce'
import { requestPost } from "@/js/dai/request";
export default {
  data () {
    return {
      visible: false,
      keyWords: '',
      dataForm: {
        id:'',
        name:'',
        customerId:'',
        agencyId:'',
        agencyName:'',
        orgId: '',
        agencyType:'',
        pid:'',
        categoryCode:'',
        sort:'',
        address: '', //详细地址
        longitude: 36.0722275, //经度
        latitude: 120.38945519 //纬度
      },      
      tagCategoryArr: [], // 查询动力主轴标签类别
      agencytree: [], // 绑定组织列表
      GridPartyBranchList:[], // 上级网格党支部列表
      PartyCommList:[], // 党委列表
      orgListSwitch:false, // 组织列表开关
      GridPartyBranchSwitch:false, // 上级网格党支部列表
      partyCommSwitch:false, // 党委下拉框列表开关
    }
  },
  computed: {
    dataRule () {
      return {
        categoryCode:[
            { required: true, message: "上级部门不能为空", trigger: "blur" }
        ],
        name:[
            { required: true, message: "上级部门不能为空", trigger: "blur" }
        ],
        orgId:[
            { required: true, message: "上级部门不能为空", trigger: "blur" }
        ],
        pid:[
            { required: true, message: "上级部门不能为空", trigger: "blur" }
        ],
        longitude: [
          { required: true, message: '坐标不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  mounted () {
    setTimeout(() => {
      this.initMap()
    }, 500);
  },
  methods: {
    init () {
      this.visible = true;
      this.dataForm.customerId = localStorage.getItem('customerId')
      this.getTagCategoryArr()
      this.getAgencyTree()
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.getInfo()
        }
      })
    },
    // 获取动力主轴标签
    async getTagCategoryArr(){
        const url = '/pli/power/axisTag/listSimple/struct'

        let params = {}

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

        if (code === 0) {
            this.tagCategoryArr = data
        } else {
            this.$message.error(msg)
        }
    },
    // 获取组织列表
    async getAgencyTree(){
        const url = '/data/aggregator/org/agencytree'

        let params = {
            agencyId:  localStorage.getItem('agencyId'),
            client:'gov'
        }
        const { data, code, msg } = await requestPost(url,params)
        if (code === 0) {
            let _data
            if (data) {
                _data = this.removeByOrgType(data, 'agency')
                if (_data) {
                    this.agencytree = this.removeEmptySubOrgList(_data)
                }
            }
        } else {
            this.$message.error(msg)
        }
    },
    removeByOrgType (orgArray, orgType) {
        if (orgArray && orgArray.length > 0) {
            for (let p = orgArray.length - 1; p >= 0; p--) {
                let orgInfo = orgArray[p]
                if (orgInfo) {
                    if (orgInfo.orgType !== orgType) {
                        orgArray.splice(p, 1)
                    } else {
                        this.removeByOrgType(orgInfo.subOrgList, orgType)
                    }
                }
            }
        }
        return orgArray
    },
    removeEmptySubOrgList (orgArray) {
        orgArray.forEach((orgInfo) => {
            if (orgInfo && orgInfo.subOrgList) {
                if (orgInfo.subOrgList.length === 0) {
                    orgInfo.subOrgList = undefined
                } else {
                    this.removeEmptySubOrgList(orgInfo.subOrgList)
                }
            }
        })
        return orgArray;
    },
    // 获取信息
    getInfo () {
      this.$http.post(`/pli/power/axisStruct/queryModifyById/${this.dataForm.id}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg);
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
        if(this.dataForm.categoryCode === 'community_party') {
            this.orgListSwitch = true
            this.GridPartyBranchSwitch = false
            this.partyCommSwitch = false
        }
        if(this.dataForm.categoryCode === 'grid_party') {
            this.orgListSwitch = false
            this.GridPartyBranchSwitch = false
            this.partyCommSwitch = true
            this.getPartyCommList()
        }
        if(this.dataForm.categoryCode === 'group_party') {
            this.GridPartyBranchSwitch = true
            this.partyCommSwitch = false
            this.getGridPartyBranchList()
        }
      }).catch(() => {})
    },
    // 获取上级网格党支部
    async getGridPartyBranchList(){
        const url = '/pli/power/axisStruct/GridPartyBranchList'

        let params = {}

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

        if (code === 0) {
            this.GridPartyBranchList = data
        } else {
            this.$message.error(msg)
        }
    },
    // 获取上级组织党委
    async getPartyCommList(){
        const url = '/pli/power/axisStruct/getPartyCommList'

        let params = {}

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

        if (code === 0) {
            this.PartyCommList = data
        } else {
            this.$message.error(msg)
        }
    },
    // 动力主轴选中后的操作
    handelChange(val){
        this.dataForm.categoryCode = val
        if (val === 'community_party') {
            this.orgListSwitch = true
            this.GridPartyBranchSwitch = false
            this.partyCommSwitch = false
            this.dataForm.pid = 0
        } 
        if(val === 'grid_party') {
            this.orgListSwitch = false
            this.GridPartyBranchSwitch = false
            this.partyCommSwitch = true
            this.getPartyCommList()
            this.dataForm.pid = ''
        }
        if(val === 'group_party') {
            this.GridPartyBranchSwitch = true
            this.partyCommSwitch = false
            this.dataForm.pid = ''
            this.getGridPartyBranchList()
        }
    },
    // 地图初始化函数，本例取名为init，开发者可根据实际情况定义
    initMap () {
      if (document.getElementById('app')) {
        document.getElementById('mapSeach_id').style.display = "block"
        document.getElementById('lon_lat_id').style.display = "block"
      }
      
      // 定义地图中心点坐标
      var center = new window.TMap.LatLng(36.0722275, 120.38945519)
      // 定义map变量，调用 TMap.Map() 构造函数创建地图
      map = new window.TMap.Map(document.getElementById('app'), {
        center: center, // 设置地图中心点坐标
        zoom: 17.2, // 设置地图缩放级别
        pitch: 43.5, // 设置俯仰角
        rotation: 45 // 设置地图旋转角度
      })

      search = new window.TMap.service.Search({ pageSize: 10 })
      // 新建一个地点搜索类
      markers = new TMap.MultiMarker({
        map: map,
        geometries: []
      })
      infoWindowList = Array(10)

      geocoder = new TMap.service.Geocoder(); // 新建一个正逆地址解析类

      // 监听地图平移结束
      map.on('panend', () => {
        this.handleMoveCenter()
      })
      this.handleMoveCenter()
      this.convert()
    },

    setMarker (lat, lng) {
      markers.setGeometries([])
      markers.add([
        {
          id: '4',
          styleId: 'marker',
          position: new TMap.LatLng(lat, lng),
          properties: {
            title: 'marker4'
          }
        }
      ])
    },

    handleSearchMap () {
      infoWindowList.forEach((infoWindow) => {
        infoWindow.close()
      })
      infoWindowList.length = 0
      markers.setGeometries([])
      // 在地图显示范围内以给定的关键字搜索地点
      search
        .searchRectangle({
          keyword: this.keyWords,
          bounds: map.getBounds()
        })
        .then((result) => {
          let { data } = result
          if (Array.isArray(data) && data.length > 0) {
            const {
              location: { lat, lng }
            } = data[0]


            map.setCenter(new TMap.LatLng(lat, lng))
            this.setMarker(lat, lng)
            this.dataForm.latitude = lat
            this.dataForm.longitude = lng
            this.convert()
          } else {
            this.$message.error('未检索到相关位置坐标')
          }
        })
    },

    handleMoveCenter () {
      //修改地图中心点
      const center = map.getCenter()
      const lat = center.getLat()
      const lng = center.getLng()
      this.dataForm.latitude = lat
      this.dataForm.longitude = lng
      this.setMarker(lat, lng)
      this.convert(lat, lng)
    },

    convert (lat, lng) {
      markers.setGeometries([]);
      // var input = document.getElementById('location').value.split(',');
      let location
      if (lat && lng) {
        location = new TMap.LatLng(lat, lng);
      } else {
        location = new TMap.LatLng(this.dataForm.latitude, this.dataForm.longitude);
      }
      // map.setCenter(location);
      markers.updateGeometries([
        {
          id: 'main', // 点标注数据数组
          position: location,
        },
      ]);
      geocoder
        .getAddress({ location: location }) // 将给定的坐标位置转换为地址
        .then((result) => {
          this.dataForm.address = result.result.address
          // 显示搜索到的地址
        });
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        if(this.dataForm.id) { // 修改
          this.submitModifyOrg()
        } else { // 新增
          this.submitAddNewOrg()
        }
      })
    }, 1000, { 'leading': true, 'trailing': false }),
    // 修改
    async submitModifyOrg(){
        this.dataForm.agencyId = this.dataForm.orgId[this.dataForm.orgId.length - 1]
        const url = '/pli/power/axisStruct/modifyOrg'
        const { data, code, msg } = await requestPost(url,this.dataForm)
        if (code === 0) {
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        } else {
            return this.$message.error(msg)
        }
    },
    // 新增
    async submitAddNewOrg(){
        const url = '/pli/power/axisStruct/addOrg'
        this.dataForm.agencyId = this.dataForm.orgId[this.dataForm.orgId.length - 1]
        const { data, code, msg } = await requestPost(url,this.dataForm)
        if (code === 0) {
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        } else {
            return this.$message.error(msg)
        }
    },
  }
}
</script>
<style lang="scss" scoped >
@import "@/assets/scss/modules/visual/communityManageForm.scss";
</style>
<style  lang="scss" scoped>
.item_width_1 {
  width: 560px;

  /deep/.tox .tox-dialog {
    z-index: 20000;
  }
}


.div_map {
  position: relative;
}
.div_searchmap {
  z-index: 5000;
  position: absolute;
  top: 5px;
  left: 5px;
}

.tinymce_view {
  height: 400px;
  overflow: auto;
}
.text_p {
  margin: 0;
  padding: 0 10px;
  border: 1px solid #d9d9d9;
  border-radius: 5px;
  > p {
    margin: 0;
  }
}
</style>