<template>
  <el-dialog :visible.sync="visible"
             :title="!dataForm.id ? '新增党组织' : '更新党组织'"
             :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' : '100px'">
      <el-form-item prop="partyOrgType"
                    label="党组织类型">
        <el-select :disabled="dataForm.id || dataForm.orgId ? true : false"
                   v-model="dataForm.partyOrgType"
                   @change="changePartyOrgType"
                   clearable
                   placeholder="请选择党组织类型">
          <el-option v-for="item in partyOrgTypeList"
                     :key="item.value"
                     :label="item.name"
                     :value="item.value">
          </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 label="党组织编码"
                    prop="partyOrgCode">
        <el-input v-model="dataForm.partyOrgCode"
                  placeholder="党组织编码"
                  style="width: 300px"></el-input>
      </el-form-item>
      <el-form-item v-if="dataForm.partyOrgType != '5'"
                    prop="agencyId"
                    label="行政组织">
        <el-cascader style="width: 300px"
                     v-model="dataForm.agencyId"
                     :options="agencyOrgList"
                     placeholder="请选择行政组织"
                     :props="{
            emitPath: false,
            checkStrictly: true,
            label: 'name',
            value: 'id',
            children: 'children',
          }"
                     :disabled="dataForm.id ? true : false"
                     :show-all-levels="false"
                     @change="changeAgencyOrg"
                     clearable />
      </el-form-item>
      <el-form-item v-if="!dataForm.sjdzzName"
                    prop="mySelectOrg"
                    label="上级党组织">
        <el-cascader ref="myOrg"
                     style="width: 300px"
                     v-model="dataForm.mySelectOrg"
                     :options="orgList"
                     placeholder="请选择上级党组织"
                     :props="{
            checkStrictly: true,
            label: 'partyOrgName',
            value: 'id',
            children: 'children',
          }"
                     @change="handleChangeOrg"
                     :disabled="dataForm.id || dataForm.orgId ? true : false"
                     clearable />
      </el-form-item>
      <el-form-item v-if="dataForm.sjdzzName"
                    label="上级党组织">
        <el-input :disabled="true"
                  v-model="dataForm.sjdzzName"
                  style="width: 300px"></el-input>
      </el-form-item>
      <el-form-item label="党组织介绍"
                    prop="introduction">
        <el-input style="width: 300px"
                  v-model="dataForm.introduction"
                  type="textarea"
                  maxlength="500"
                  placeholder="党组织介绍"></el-input>
      </el-form-item>
      <el-form-item label="地图位置"
                    prop="longitude"
                    style="display: block">
        <div style="width: 500px">
          <el-select v-model="searchValue"
                     filterable
                     style="width: 500px"
                     remote
                     :reserve-keyword="true"
                     placeholder="请输入关键词"
                     :remote-method="remoteMethod"
                     :loading="loading">
            <el-option v-for="(item,index) in searchOptions"
                       @click.native="handleClickKey(index)"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
          <div id="app_icparty"
               class="div_map"></div>
        </div>
      </el-form-item>
      <el-form-item label="详细地址"
                    prop="address">
        <el-input style="width: 300px"
                  v-model="dataForm.address"
                  placeholder="详细地址"></el-input>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="handleCancle">{{ $t("cancel") }}</el-button>
      <el-button type="primary"
                 @click="dataFormSubmitHandle()">{{
        $t("confirm")
      }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import daiMap from "@/utils/dai-map";

var map;
var search;
var markers;
var infoWindowList;
var geocoder; // 新建一个正逆地址解析类
import debounce from "lodash/debounce";

export default {
  data () {
    return {
      searchOptions: [],
      searchValue: '',
      resultList: [],
      loading: false,

      visible: false,
      keyWords: "",
      dataForm: {
        id: "",
        partyOrgType: "", // 党组织类型 0省委,1市委,2区委,3党工委,4党委,5支部
        partyOrgName: "", // 组织名称
        partyOrgCode: "", // 组织编码
        mySelectOrg: "", // 我选中的当前党组织
        orgPid: "", // 党组织的上级ID,没有上级时为0
        orgPids: "", // 党组织的所有上级ID,没有上级时为0
        agencyId: "", // 行政组织id
        agencyPids: "", // 行政组织父ids(英文逗号隔开)
        longitude: "", //经度
        latitude: "", //纬度
        address: "",
        introduction: "", // 党组织介绍
        orgId: "",
        customerId: "",
        staffId: "",
        orgPidName: "",
        agencyName: "",
        pid: "",
        sjdzzName: "", // 新增下级上级党组织名字
      },
      orgListVisible: false,
      agencyListVisible: false,
      orgList: [],
      agencyId: "",
      level: "",
      partyOrgTypeList: [],
      agencyOrgList: [],
    };
  },
  methods: {
    handleCancle () {
      this.resetData()
      this.visible = false
    },
    resetData () {
      this.searchValue = ''
      this.searchOptions = []
      this.resultList = []
    },
    init () {
      this.visible = true;
      this.agencyId = localStorage.getItem("agencyId");
      this.dataForm.customerId = localStorage.getItem("customerId");
      this.dataForm.staffId = localStorage.getItem("staffId");
      this.keyWords = "";
      //设置党组织类型
      setTimeout(() => {
        this.$refs["dataForm"].resetFields();
        this.dataForm.latitude = "";
        this.dataForm.agencyId = "";
        if (this.dataForm.id) {
          this.setPartyOrgType();
          this.getInfo();
        } else {
          this.setPartyOrgType();
          let { latitude, longitude } = this.$store.state.user;
          this.$nextTick(() => {
            if (!map) {
              this.initMap(latitude, longitude);
            } else {
              map.setCenter(latitude, longitude);
              map.setMarker(latitude, longitude);
            }
          })
          if (this.dataForm.orgId) {
            this.dataForm.mySelectOrg = this.dataForm.orgId;
            this.dataForm.orgPid = this.dataForm.orgId;
            this.dataForm.orgPids = this.dataForm.orgPids
              ? this.dataForm.orgPids + ":" + this.dataForm.orgId
              : this.dataForm.orgId;
            this.dataForm.partyOrgType = this.dataForm._partyOrgType;

            this.setPartyOrgType_xzxj();
            this.getInfoAgencyLisy();
          } else {
            this.dataForm.mySelectOrg = "";
          }
        }
      }, 50);
      // this.$nextTick(() => {

      // })
    },
    // 设置组织类型 新增党组织
    setPartyOrgType_xzxj () {
      if (this.dataForm.partyOrgType === "0") {
        // 党组织类型 0省委,1市委,2区委,3党工委,4党委,5支部
        this.dataForm.partyOrgType = "1";
      } else if (this.dataForm.partyOrgType === "1") {
        this.dataForm.partyOrgType = "2";
      } else if (this.dataForm.partyOrgType === "2") {
        this.dataForm.partyOrgType = "3";
      } else if (this.dataForm.partyOrgType === "3") {
        this.dataForm.partyOrgType = "4";
      } else if (this.dataForm.partyOrgType === "4") {
        this.dataForm.partyOrgType = "5";
      }
    },
    //设置组织类型
    setPartyOrgType () {
      // 社区级：community，街道级:street,区县级: district,市级: city 省级:province
      // 党组织类型 0省委,1市委,2区委,3党工委,4党委,5支部
      this.level = localStorage.getItem("level")
        ? localStorage.getItem("level")
        : "";
      if (this.level == "province") {
        this.partyOrgTypeList = [
          { value: "0", name: "省委" },
          { value: "1", name: "市委" },
          { value: "2", name: "区委" },
          { value: "3", name: "党工委" },
          { value: "4", name: "党委" },
          { value: "5", name: "支部" },
        ];
      } else if (this.level == "city") {
        this.partyOrgTypeList = [
          { value: "1", name: "市委" },
          { value: "2", name: "区委" },
          { value: "3", name: "党工委" },
          { value: "4", name: "党委" },
          { value: "5", name: "支部" },
        ];
      } else if (this.level == "district") {
        this.partyOrgTypeList = [
          { value: "2", name: "区委" },
          { value: "3", name: "党工委" },
          { value: "4", name: "党委" },
          { value: "5", name: "支部" },
        ];
      } else if (this.level == "street") {
        this.partyOrgTypeList = [
          { value: "3", name: "党工委" },
          { value: "4", name: "党委" },
          { value: "5", name: "支部" },
        ];
      } else if (this.level == "community") {
        this.partyOrgTypeList = [
          { value: "4", name: "党委" },
          { value: "5", name: "支部" },
        ];
      }
    },
    // 选中行政组织
    changeAgencyOrg () {
      if (!this.dataForm.orgId) {
        // 有orgId 证明是从新增下级过来的，新增下级操作 上级党组织不需要查询
        this.getOrgList();
      }
    },
    // 选中组织类型 组织类型为支部时不需要选择行政组织
    changePartyOrgType (value) {
      if (value == "5") {
        // 支部 不选择行政组织
        this.dataForm.agencyId = localStorage.getItem("agencyId");
        this.dataForm.agencyPids = "";
        // 先清空数据
        this.orgList = [];
        (this.dataForm.mySelectOrg = ""), // 我选中的当前党组织
          (this.dataForm.orgPid = ""), // 党组织的上级ID,没有上级时为0
          (this.dataForm.orgPids = "");
        this.getOrgList();
      } else {
        // 先清空数据
        this.agencyOrgList = [];
        this.dataForm.agencyId = "";

        // 先清空数据
        this.orgList = [];
        (this.dataForm.mySelectOrg = ""), // 我选中的当前党组织
          (this.dataForm.orgPid = ""), // 党组织的上级ID,没有上级时为0
          (this.dataForm.orgPids = "");
        this.getInfoAgencyLisy();
      }
    },
    // 获取上级党组织列表
    getOrgList () {
      if (!this.dataForm.id) {
        // 修改不做处理
        this.orgList = [];
        (this.dataForm.mySelectOrg = ""), // 我选中的当前党组织
          (this.dataForm.orgPid = ""), // 党组织的上级ID,没有上级时为0
          (this.dataForm.orgPids = "");
      }
      this.$http
        .get("/resi/partymember/icPartyOrg/getParentOrgList", {
          params: {
            agencyId: this.dataForm.agencyId,
            partyOrgType: this.dataForm.partyOrgType,
          },
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(
              res.internalMsg ? res.internalMsg : res.msg ? res.msg : "查询失败"
            );
          }
          this.orgList = this.removeEmptyChildren(res.data);
        })
        .catch(() => { });
    },
    removeEmptyChildren (orgArray) {
      orgArray.forEach((orgInfo) => {
        if (orgInfo && orgInfo.children) {
          if (orgInfo.children.length === 0) {
            orgInfo.children = undefined;
          } else {
            this.removeEmptyChildren(orgInfo.children);
          }
        }
      });
      return orgArray;
    },
    // 党组织选中事件
    handleChangeOrg (e) {
      if (this.dataForm.mySelectOrg.length > 0 && this.dataForm.mySelectOrg) {
        this.dataForm.orgPid =
          this.dataForm.mySelectOrg[this.dataForm.mySelectOrg.length - 1];
        this.dataForm.orgPids =
          this.$refs.myOrg.getCheckedNodes()[0].data.orgPids;
        this.dataForm.mySelectOrg.forEach((element) => {
          this.dataForm.orgPids = this.dataForm.orgPids
            ? this.dataForm.orgPids + ":" + element
            : element;
        });
      } else {
        this.dataForm.orgPid = "";
        this.dataForm.orgPids = "";
      }
    },
    // 获取信息
    getInfo () {
      this.$http
        .get(`/resi/partymember/icPartyOrg/${this.dataForm.id}`)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(
              res.internalMsg ? res.internalMsg : res.msg ? res.msg : "查询失败"
            );
          }
          this.dataForm = {
            ...this.dataForm,
            ...res.data,
          };
          // 党组织组织
          this.dataForm.mySelectOrg = this.dataForm.orgPid;
          // 行政组织
          this.dataForm.agencyId = this.dataForm.agencyId;
          //根据组织类型获取行政组织
          this.getInfoAgencyLisy();
          // 获取上级党组织
          this.getOrgList();
          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);
            }
          })

        })
        .catch(() => { });
    },
    getInfoAgencyLisy () {
      this.$http
        .get("/gov/org/customeragency/getOrgTreeByUserAndType", {
          params: {
            agencyId: this.dataForm.pid ? this.dataForm.pid : this.agencyId,
            orgType: this.dataForm.partyOrgType,
          },
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(
              res.internalMsg ? res.internalMsg : res.msg ? res.msg : "查询失败"
            );
          }
          this.agencyOrgList = this.removeEmptyChildren(res.data);
        })
        .catch(() => { });
    },
    // 地图初始化函数，本例取名为init，开发者可根据实际情况定义
    initMap (latitude, longitude) {

      map = new daiMap(
        document.getElementById("app_icparty"),
        { 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);

    },


    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.searchValue = data.address
        this.searchOptions = []

      }
    },

    async remoteMethod (query) {

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

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

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

          if (data.resultList && data.resultList.length > 0) {
            this.resultList = data.resultList
            this.searchOptions = this.resultList.map(item => {
              return { value: `${item.hotPointID}`, label: `${item.address + item.name}` };

            });
          }
        } else {
          this.searchOptions = [
            {
              value: '0',
              label: '未检索到结果'
            }
          ]
        }
      } else {
        this.searchOptions = [];
      }
    },

    handleClickKey (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
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        if (!this.dataForm.latitude || !this.dataForm.longitude) {
          return this.$message.error("请滑动地图选择党组织位置");
        }
        if (this.dataForm.orgPids === "0") {
          this.dataForm.orgPids = "";
        }
        this.$refs["dataForm"].validate((valid) => {
          if (!valid) {
            return false;
          }
          this.$http[!this.dataForm.id ? "post" : "put"](
            "/resi/partymember/icPartyOrg/",
            this.dataForm
          )
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(
                  res.internalMsg
                    ? res.internalMsg
                    : res.msg
                      ? res.msg
                      : "查询失败"
                );
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  this.resetData()
                  this.visible = false;

                  this.$emit("refreshDataList");
                },
              });
            })
            .catch(() => { });
        });
      },
      1000,
      { leading: true, trailing: false }
    ),
  },
  computed: {
    dataRule () {
      return {
        partyOrgName: [
          { required: true, message: "党组织名称不能为空", trigger: "blur" },
        ],
        mySelectOrg: [
          { required: true, message: "上级党组织不能为空", trigger: "blur" },
        ],
        partyOrgType: [
          { required: true, message: "党组织类型不能为空", trigger: "blur" },
        ],
        agencyId: [
          { required: true, message: "行政组织不能为空", trigger: "blur" },
        ],
      };
    },
  },
};
</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>
