<template>
  <div>
    <div class="dialog-h-content scroll-h">
      <div v-show="!propertyFormShow">
        <el-form ref="ref_form"
                 :inline="true"
                 :model="dataForm"
                 :rules="dataRule"
                 :disabled="formType === 'detail'"
                 class="form">

      <el-form-item prop="categoryCode" label="类别" label-width="150px">
          <el-select class="item_width_1" v-model="dataForm.categoryCode" @change="handelChange" placeholder="请选择类别" clearable>
              <el-option
              v-for="item in structCategoryArr"
              :key="item.categoryCode"
              :label="item.categoryName"
              :value="item.categoryCode">
              </el-option>
          </el-select>
      </el-form-item>
          <el-form-item label="名称"
                        prop="name"
                        label-width="150px"
                        style="display: block">
            <el-input class="item_width_1"
                      maxlength="50"
                      show-word-limit
                      placeholder="请输入名称"
                      v-model="dataForm.name">
            </el-input>
          </el-form-item>
          <!-- 下拉框组织的参数 -->
          <el-form-item abel-width="150px" prop="agencyId" label="所属组织" v-if="orgListSwitch" label-width="150px">
              <el-cascader
                  class="item_width_1"
                  v-model="dataForm.agencyId"
                  :options="agencytree"
                  placeholder="请选择所属组织"
                  :props="{ expandTrigger: 'hover', emitPath: false, label: 'orgName', value: 'orgId', children: 'subOrgList' }"
                  :show-all-levels="false"
                  clearable />
          </el-form-item>
          <el-form-item abel-width="150px" prop="pid" label="所属上级" v-if="!orgListSwitch" label-width="150px">
              <el-cascader
                class="item_width_1"
                placeholder="请选择所属上级"
                :options="parentStructTree"
                v-model="dataForm.pid"
                :props="{ expandTrigger: 'hover', emitPath: false, label: 'name', value: 'id', children: 'children' }"
                :show-all-levels="false"
                clearable />
          </el-form-item>
          <el-form-item abel-width="150px" label="排序" label-width="150px">
              <el-input-number v-model="dataForm.sort" :min="0" :max="10" label="请输入排序"></el-input-number>
          </el-form-item>
          <el-form-item label="输入位置查坐标"
                        prop="longitude"
                        label-width="150px"
                        style="display: block">
            <div style="width:500px">
              <el-input class="item_width_4"
                        maxlength="50"
                        placeholder="请输入关键字"
                        v-model="keyWords">
              </el-input>
              <el-button style="margin-left: 10px"
                         type="primary"
                         size="small"
                         @click="handleSearchMap">查询</el-button>
              <div id="app"
                   class="div_map"></div>
              <div style="margin-top: 10px">
                <span>经度</span>
                <el-input class="item_width_3"
                          maxlength="50"
                          placeholder="请输入经度"
                          :readonly="true"
                          v-model="dataForm.longitude">
                </el-input>
                <span style="margin-left: 20px">纬度</span>
                <el-input class="item_width_3"
                          maxlength="50"
                          placeholder="请输入纬度"
                          :readonly="true"
                          v-model="dataForm.latitude">
                </el-input>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="div_btn">
      <el-button size="small"
                 @click="handleCancle">取 消</el-button>
      <el-button size="small"
                 v-if="formType != 'detail'"
                 type="primary"
                 :disabled="btnDisable"
                 @click="handleComfirm">确 定</el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { Loading } from 'element-ui' // 引入Loading服务
import { requestPost } from '@/js/dai/request'
var map
var search
var markers
var infoWindowList
let loading // 加载动画
export default {
  data () {
    return {
      formType: 'add', //表单操作类型 add新增，edit编辑，detail详情
      btnDisable: false,
      dataForm: {
        id:'',
        name:'',
        agencyId:'',
        structLevel: null,
        pid:'',
        categoryCode:'',
        sort:'',
        longitude: '', //经度
        latitude: ''//纬度
      },
      propertyFormShow: false,
      keyWords: '',
      structCategoryArr: [], // 查询动力主轴标签类别
      leaderCategoryArr: [], // 查询动力主轴负责人标签类别
      agencytree: [], // 绑定组织列表
      parentStructTree: [], // 上级节点列表
      orgListSwitch: false, // 组织列表开关
    }
  },
  components: {},
  mounted () {
    this.initMap()
  },
  methods: {
    initForm (type, id) {
      this.$refs.ref_form.resetFields();
      this.formType = type
      this.getTagCategoryArr()
      this.getAgencyTree()
      if (this.formType === 'edit') {
         this.getInfo(id)
      }
    },
    // 获取动力主轴标签
    async getTagCategoryArr(){
        const url = '/pli/power/axisTag/listSimpleAll'
        let params = {}
        const { data, code, msg } = await requestPost(url, params)
        if (code === 0) {
            data.forEach((item) => {
                if (item.tagCategory === 'struct') {
                    this.structCategoryArr = item.tagList
                }
                if (item.tagCategory === 'leader') {
                    this.leaderCategoryArr = item.tagList
                } 
            })
        } 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;
    },
    removeEmptyStructTree (structArray) {
        structArray.forEach((structInfo) => {
            if (structInfo && structInfo.children) {
                if (structInfo.children.length === 0) {
                    structInfo.children = undefined
                } else {
                    this.removeEmptyStructTree(structInfo.children)
                }
            }
        })
        return structArray;
    },
    // 获取信息
    getInfo (id) {
      this.$http.post(`/pli/power/axisStruct/queryModifyById/${id}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg);
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
        map.setCenter(new TMap.LatLng(this.dataForm.latitude, this.dataForm.longitude))
        this.setMarker(this.dataForm.latitude, this.dataForm.longitude)
        this.structCategoryArr.forEach((item) => {
          if(item.categoryCode === this.dataForm.categoryCode){
            this.dataForm.structLevel = item.structLevel
            if(this.dataForm.structLevel === 0) {
              this.orgListSwitch = true
            } else {
              this.orgListSwitch = false
              this.getParentStructTree(this.dataForm.structLevel)
            }
          }
        })
      }).catch(() => {})
    },
    // 获取上级动力主轴节点
    async getParentStructTree(structLevel){
        const url = `/pli/power/axisStruct/bylevel/${structLevel}/parenttree`
        let params = {}
        const { data, code, msg } = await requestPost(url,params)
        if (code === 0) {
            this.parentStructTree = this.removeEmptyStructTree(data)
        } else {
            this.$message.error(msg)
        }
    },
    // 动力主轴选中后的操作
    handelChange(val){
        this.dataForm.categoryCode = val
        this.structCategoryArr.forEach((item) => {
          if(item.categoryCode === val){
            this.dataForm.structLevel = item.structLevel
          }
        })
        if (this.dataForm.structLevel === 0) {
          this.orgListSwitch = true
          this.dataForm.pid = '0'
        } else {
          this.orgListSwitch = false
          this.dataForm.pid = ''
          this.getParentStructTree(this.dataForm.structLevel)
        }
    },


    // 添加
    async handleComfirm () {
      // 确定
        this.btnDisable = true
        setTimeout(() => {
          this.btnDisable = false
        }, 10000)
        this.$refs['ref_form'].validate((valid, messageObj) => {
          if (!valid) {
            app.util.validateRule(messageObj)
            this.btnDisable = false
          } else {
            this.addCommunity()
          }

        })
    },
    async addCommunity () {
      let url = ''
      if (this.formType === 'add') {
        this.dataForm.id = ''
        url = '/pli/power/axisStruct/save'
      } else {
        url = '/pli/power/axisStruct/update'
      }
      const { data, code, msg } = await requestPost(url, this.dataForm)
      if (code === 0) {
        this.$message({
          type: 'success',
          message: '操作成功'
        })
        // this.resetData()
        this.$emit('dialogOk')
        this.btnDisable = false
      } else {
        this.btnDisable = false
        this.$message.error(msg)
      }

    },
    // 取消按钮 
    handleCancle () {
      // this.resetData()
      this.$emit('dialogCancle')
    },
    resetData () {
      this.keyWords = ''
      this.dataForm = {
        id:'',
        name:'',
        agencyId:'',
        structLevel: null,
        pid:'',
        categoryCode:'',
        sort:'',
        longitude: '', //经度
        latitude: ''//纬度
      }
      this.propertyFormShow = false
      this.keyWords= ''
      this.structCategoryArr = [] // 查询动力主轴标签类别
      this.leaderCategoryArr = [] // 查询动力主轴负责人标签类别
      this.agencytree = [] // 绑定组织列表
      this.parentStructTree = [] // 上级节点列表
    },
    // 开启加载动画
    startLoading () {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: '正在加载……', // 加载中需要显示的文字
        background: 'rgba(0,0,0,.7)' // 背景颜色
      })
    },
    // 结束加载动画
    endLoading () {
      // clearTimeout(timer);
      if (loading) {
        loading.close()
      }
    },
    // 地图初始化函数，本例取名为init，开发者可根据实际情况定义
    initMap () {
      // 定义地图中心点坐标
      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)

      // 监听地图平移结束
      map.on('panend', () => {
        this.handleMoveCenter()
      })
      this.handleMoveCenter()
    },
    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
          } 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)
    }
  },
  computed: {
    dataRule () {
      return {
        categoryCode:[
            { required: true, message: "类别不能为空", trigger: "blur" }
        ],
        name:[
            { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        agencyId:[
            { required: true, message: "所属组织不能为空", trigger: "blur" }
        ],
        pid:[
            { required: true, message: "所属上级不能为空", trigger: "blur" }
        ],
        longitude: [
          { required: true, message: '坐标不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  props: {}
}
</script>
<style lang="scss" scoped >
@import "@/assets/scss/modules/visual/communityManageForm.scss";
</style>



