<template>
  <el-dialog :visible="visible"
             :title="'修改党组织'"
             :close-on-click-modal="false"
             :close-on-press-escape="true"
              @close="handleDlgClose">
    <el-form class="form"
             :model="dataForm"
             :rules="dataRule"
             ref="dataForm"
             @keyup.enter.native=""
             :label-width="$i18n.locale === 'en-US' ? '120px' : '100px'">

      <el-form-item prop="partyOrgLevel"
                    label="党组织类型">
        {{ this.partyOrgLevelName }}
      </el-form-item>
      
      <el-form-item prop="partyOrgPid"
                    label="上级党组织">
        {{ this.partyOrgPName ? this.partyOrgPName : '--' }}
      </el-form-item>

      <el-form-item prop="orgId"
                    label="行政组织"
                    v-show="xingzhengSelectorVisible">
        {{ this.orgName }}
      </el-form-item>

      <el-form-item prop="principalId"
                    label="负责人">
        <el-select v-model="dataForm.principalId"
                   @change=""
                   clearable
                   placeholder="请选择">
          <el-option
              v-for="principal in principals"
              :key="principal.principalId"
              :label="principal.principalName"
              :value="principal.principalId">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item prop="partyOrgName"
                    label="党组织名称">
        <el-input v-model="dataForm.partyOrgName"
                  placeholder="请输入党组织名称"
                  style="width: 300px"></el-input>
      </el-form-item>
      
      <el-form-item prop="description" label="党组织介绍">
        <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            v-model="dataForm.description">
        </el-input>
      </el-form-item>

      <el-form-item label="地图位置"
                    prop="longitude"
                    style="display: block">
        <div style="width: 500px">
          <el-select v-model="dataForm.address"
                     filterable
                     style="width: 500px"
                     remote
                     :reserve-keyword="true"
                     placeholder="请输入位置关键词"
                     :remote-method="searchOnMap"
                     :loading="mapLoading">
            <el-option v-for="(item,index) in searchOptions"
                       @click.native="handleMapSearchResultSelected(index)"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
          <div id="partyOrgMap"
               class="div_map"></div>
        </div>
      </el-form-item>

    </el-form>
    <template slot="footer">
      <el-button @click="handleDlgClose">取消</el-button>
      <el-button type="primary" @click="handleSubmitUpdate">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
var map
var search
var markers
var infoWindowList
var geocoder // 新建一个正逆地址解析类
import debounce from 'lodash/debounce'
import { requestGet, requestPost } from "@/js/dai/request";
import { EpmetResultResolver } from '@/js/epmet-result-resolver'
import { number } from 'echarts'
import daiMap from "@/utils/dai-map";

export default {
  data () {
    return {
      dataForm: this.initForm(),
      partyOrgPName: null,
      partyOrgLevel: null,
      partyOrgLevelName: null,
      orgName: null,
      orgId: null,
      
      principals: [], // 负责人列表
      
      // 地图
      searchOptions: [], //用于展示的地图搜索结果列表
      searchValue: '',
      mapLoading: false, // 地图加载
      mapSearchResultList: [], // 地图搜索结果列表 
      epmetResultResolver: null, // epmet请求结果解析器
      visible: false,
      xingzhengSelectorVisible: true, // 行政组织是否可见
    }
  },
  mounted () {
    this.epmetResultResolver = new EpmetResultResolver(this);
  },
  methods: {
    /**
     * 初始化
     * @param parentPartyOrgLevel 非必填，父党组织级别的level，在添加下级党组织的时候传递，否则为空
     * @param parentPartyOrgId 非必填，父党组织级别的ID，在添加下级党组织的时候传递，否则为空
     * @returns {Promise<void>}
     */
    async init (partyOrgId, partyOrgLevel) {
      this.visible = true;
      
      // 加载党组织简要信息
      var partyOrgInfo;
      await this.getPartyOrgDetail(partyOrgId).then((poi) => {
        partyOrgInfo = poi;
      });

      this.orgName = partyOrgInfo.orgName;
      this.orgId = partyOrgInfo.orgId;
      this.partyOrgLevel = partyOrgInfo.partyOrgLevel;
      this.partyOrgLevelName = partyOrgInfo.partyOrgLevelName;
      this.partyOrgPName = partyOrgInfo.partyOrgPName;
      this.dataForm.id = partyOrgInfo.id;
      this.dataForm.partyOrgName = partyOrgInfo.partyOrgName;
      this.dataForm.description = partyOrgInfo.description;
      this.dataForm.longitude = partyOrgInfo.longitude;
      this.dataForm.latitude = partyOrgInfo.latitude;
      this.dataForm.address = partyOrgInfo.address;

      if (partyOrgLevel >= 6) {
        this.xingzhengSelectorVisible = false;
      } else {
        this.xingzhengSelectorVisible = true;
      }
      
      /** ● 加载负责人 **/
      await this.loadPrincipals();
      
      // 初始化地图
        this.dataForm.principalId = partyOrgInfo.principalId;
        console.log(this.principals)
        console.log(this.dataForm.principalId )
       this.$nextTick(()=>{
        if (!map) {
          this.initMap(this.dataForm.latitude, this.dataForm.longitude);
        } else {
          map.setCenter(this.dataForm.latitude, this.dataForm.longitude);
          map.setMarker(this.dataForm.latitude, this.dataForm.longitude);
        }
       })
    },

    // 初始化地图
    initMap (latitude, longitude) {
      let d = document.getElementById("partyOrgMap");
      console.log("地图div:" + d);
      map = new daiMap(
          document.getElementById("partyOrgMap"),
          { latitude, longitude },
          {
            zoom: 16.2, // 设置地图缩放级别
            pitch: 43.5, // 设置俯仰角
            rotation: 45, // 设置地图旋转角度
          }
      );

      // 监听地图平移结束事件
      map.on("dragend", (e) => {
        this.handleMoveCenter(e);
      });

      // 设置地图默认经纬度中心店和标记
      map.setCenter(latitude, longitude);
      map.setMarker(latitude, longitude);
    },

    /**
     * 重置
     */
    initForm() {
      this.principals = [];
      this.searchValue = null;
      return {
        id: null,
        partyOrgName: null,
        principalId: null,
        description: null,
        longitude: null,
        latitude: null,
        address: null
      };
    },
    
    /**
     * 加载负责人
     * @returns {Promise<void>}
     */
    async loadPrincipals() {
      let url = "/actual/base/party/org/listPrincipal";
      let rst = await requestGet(url, {
        orgId: this.orgId,
        partyOrgLevel: this.partyOrgLevel
      });
    
      this.epmetResultResolver
          .success((data) => {
            this.principals = data;
          })
          .parse(rst);
    },

    /**
     * 对话框关闭事件
     * @returns {Promise<void>}
     */
    async handleDlgClose() {
      this.visible = false;
      this.$emit("update:visiable", false);
      this.initForm();
      this.$refs.dataForm.resetFields();
    },

    /**
     * 提交表单事件
     * @returns {Promise<void>}
     */
    async handleSubmitUpdate() {
      
      this.$refs.dataForm.validate((success) => {
        if (success) {
          this.submitUpdatePartyOrg();
        }
      });
    },

    /**
     * 执行提交
     * @returns {Promise<void>}
     */
    async submitUpdatePartyOrg() {
      let url = "/actual/base/party/org/update";

      let params = {
        ...this.dataForm
      }

      let rst = await requestPost(url, params)

      this.epmetResultResolver
          .success((data) => {
            this.$message.success("提交成功");
            this.handleDlgClose(); // 关闭对话框
            this.$emit('refreshTree');
          })
          .parse(rst);
    },

    // 地图搜索
    async searchOnMap (query) {

      if (query !== '') {
        this.mapLoading = true;

        const { msg, data } = await map.searchNearby(query);
        this.mapLoading = false;
        this.mapSearchResultList = []

        if (msg == "success" && data.resultList && data.resultList.length > 0) {

          if (data.resultList && data.resultList.length > 0) {
            this.mapSearchResultList = data.resultList
            this.searchOptions = this.mapSearchResultList.map(item => {
              return { value: `${item.hotPointID}`, label: `${item.address + item.name}` };
            });
          }
        } else {
          this.searchOptions = [
            {
              value: '0',
              label: '未检索到结果'
            }
          ]
        }
      } else {
        this.searchOptions = [];
      }
    },

    // 地图中心点移动
    async handleMoveCenter () {
      //修改地图中心点
      const { lat, lng } = map.getCenter();
      this.dataForm.latitude = lat;
      this.dataForm.longitude = lng;
      map.setMarker(lat, lng);

      let { msg, data } = await map.getAddress(lat, lng);
      if (msg == "success") {
        this.dataForm.address = data.address;
        this.searchOptions = [];

      }
    },

    /**
     * 地图文本搜索，选中
     * @param index
     */
    handleMapSearchResultSelected (index) {
      let selPosition = this.resultList[index]
      let lonlat = selPosition.lonlat.split(" ")
      map.setCenter(lonlat[1], lonlat[0]);
      map.setMarker(lonlat[1], lonlat[0]);
      this.dataForm.latitude = lonlat[1];
      this.dataForm.longitude = lonlat[0];
      this.dataForm.address = selPosition.address + selPosition.name
    },

    /**
     * 党组织详情
     * @param partyOrgId
     * @returns {Promise<*>}
     */
    async getPartyOrgDetail(partyOrgId) {
      let url = "/actual/base/party/org/brief";

      let params = {
        id: partyOrgId
      }

      let rst = await requestGet(url, params)

      let partyOrgDetail;
      this.epmetResultResolver
          .success((data) => {
            partyOrgDetail = data;
          })
          .parse(rst);
      return partyOrgDetail;
    },

    /**
     * 加载行政组织
     * @returns {Promise<void>}
     */
    async loadXingzhengOrgs() {
      let url = "/actual/base/party/org/listXingZhengOrgs";
      let rst = await requestGet(url, {
        partyOrgPid: this.dataForm.partyOrgPid,
        partyOrgLevel: this.dataForm.partyOrgLevel
      });

      this.epmetResultResolver
          .success((data) => {
            this.xingzhengOrgs = data;

            // 1:省委，2：市委，3：区委，4：党工委，5：党委，6：党总支，7：党支部，8：楼院党小组
            // 如果是 >=6 ，那么他们对应的行政组织，就是上级党组织对应的行政组织，自动选中即可
            this.$nextTick(() => {
              if (this.dataForm.partyOrgLevel >= 6 && data && data.length > 0) {
                this.dataForm.orgId = this.xingzhengOrgs[0].orgId;

                // 自动选择了行政组织，然后自动加载负责人列表
                this.loadPrincipals();
              }
            })
          })
          .parse(rst);
    }
    
  },
  computed: {
    dataRule () {
      return {
        partyOrgName: [
          { required: true, message: '党组织名称不能为空', trigger: 'blur' },
        ],
        principalId: [
          { required: true, message: '请选择负责人', trigger: 'blur' },
        ],
        longitude: [
          { required: true, message: '请选择地图位置', trigger: 'blur' },
        ],
      }
    },
  },
  props: {
    // visible: {
    //   defult: false,
    //   type: Boolean
    // }
  }
}
</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>
