<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 ? 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"
                    clearable />
            </el-form-item>
            <el-form-item  prop="mySelectOrg" label="上级党组织">
                <el-cascader
                    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 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 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="请输入经度"
                            :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>
        <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'

    export default {
        data() {
            return {
                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:''
                },
                orgListVisible: false,
                agencyListVisible:false,
                orgList: [],
                agencyId: '',
                partyOrgTypeList: [],
                agencyOrgList:[]
            }
        },
        // mounted () {
        //     setTimeout(() => {
        //         console.log(':::::::::::::::::::::::')
        //         this.initMap()
        //     }, 800);
        // },
        methods: {
            init() {
                this.visible = true
                this.agencyId = localStorage.getItem('agencyId')
                this.dataForm.customerId = localStorage.getItem('customerId')
                this.dataForm.staffId = localStorage.getItem('staffId')
                this.$nextTick(() => {
                    this.$refs['dataForm'].resetFields()
                    this.dataForm.latitude = ''
                    //设置党组织类型
                    this.setPartyOrgType()
                    this.getOrgList().then(() => {
                        if (this.dataForm.id) {
                            this.getInfo()
                        } else {
                            this.initMap()
                            if(this.dataForm.orgId) {
                                this.dataForm.mySelectOrg = this.dataForm.orgId
                                this.dataForm.orgPid = this.dataForm.orgId
                                this.dataForm.orgPids = this.dataForm.orgPids + ':' + this.dataForm.orgId
                                console.log(this.dataForm.orgPid)
                                console.log(this.dataForm.orgPids)
                            } else {
                                this.dataForm.mySelectOrg = ''
                            }
                        }
                    })
                })
            },
            //设置组织类型
            setPartyOrgType() {
                // 社区级：community，街道级:street,区县级: district,市级: city 省级:province
                // 党组织类型 0省委,1市委,2区委,3党工委,4党委,5支部
                this.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: '支部'}
                    ]
                }
            },
            // 选中组织类型 组织类型为支部时不需要选择行政组织
            changePartyOrgType(value){
                if(value != '5'){ // 支部
                    this.dataForm.agencyId = ''
                    this.dataForm.agencyPids = ''
                }
                this.$http.get('/gov/org/customeragency/getOrgTreeByUserAndType', {params: {agencyId: this.agencyId, orgType:value}}).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(() => {})
            },
            // 获取党组织列表
            getOrgList() {
                return this.$http.get('/resi/partymember/icPartyOrg/getTreelist', {params: {agencyId: this.agencyId}}).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)
                    this.orgList.unshift({
                        partyOrgName: '一级组织',
                        id: '0'
                    });
                }).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.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.id
                    // this.dataForm.mySelectOrg.push(this.dataForm.id)
                    console.log(JSON.stringify(this.dataForm.mySelectOrg))
                    // 行政组织
                    this.dataForm.agencyId = this.dataForm.agencyId
                    this.initMap()
                }).catch(() => {
                })

                //根据组织类型获取行政组织
                this.getInfoAgencyLisy()
            },
            getInfoAgencyLisy(){
                this.$http.get('/gov/org/customeragency/getOrgTreeByUserAndType',
                    {params:
                            {agencyId: 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 = res.data
                }).catch(() => {
                })
            },
            // 地图初始化函数，本例取名为init，开发者可根据实际情况定义
            initMap () {
            document.getElementById('app').innerHTML = ''
            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( this.dataForm.latitude ? this.dataForm.latitude : 36.0722275,  this.dataForm.longitude ? this.dataForm.longitude : 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()
                if (lng === 120.38945519) {
                    this.dataForm.latitude = ''
                    this.dataForm.longitude = ''
                } else {
                    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 () {
                if (!this.dataForm.latitude || !this.dataForm.longitude) {
                    return this.$message.error('请滑动地图选择党组织位置')
                }
                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.visible = false
                                this.$emit('refreshDataList')
                            }
                        })
                    }).catch(() => {
                    })
                })
            }, 1000, {'leading': true, 'trailing': false})
        },
        computed: {
            dataRule() {
                return {
                    partyOrgName: [
                        {required: true, message: this.$t('validate.required'), trigger: 'blur'}
                    ],
                    mySelectOrg: [
                        {required: true, message: this.$t('validate.required'), trigger: 'blur'}
                    ],
                    partyOrgType: [
                        {required: true, message: this.$t('validate.required'), trigger: 'blur'}
                    ],
                    agencyId: [
                        {required: true, message: this.$t('validate.required'), 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>
