<!--
 * @Author: your name
 * @Date: 2020-11-27 18:53:33
 * @LastEditTime: 2021-05-31 09:02:15
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \WEB\dispatchingManagement\src\views\videoMonitor\cameraManage\popups\addOrEditCamera.vue
-->

<template>
    <div class="alert-body__main_content">
        <zz-form :cols="formCols" :data="formData" :rules="formRules" :errors="formErrors" labelWidth="120" ref="form">
            >
            <select-tree
                :props="defaultProps"
                slot="companyOrgId"
                class="new-select-tree"
                selectTreeTitle="组织机构"
                placeholder="请选择所属公司"
                :options="organListCompany"
                @selected="selectedcompanyOrgId"
                v-model="formData.companyOrgId"
                :labelModel="formData.companyOrgName"
            />
            <select-tree
                :props="defaultProps"
                slot="deptOrgId"
                class="new-select-tree"
                selectTreeTitle="组织机构"
                placeholder="请选择所属部门"
                :options="organListdepartment"
                @selected="selectedDepartOrgId"
                v-model="formData.deptOrgId"
            />
            <select-tree
                :props="defaultPropsscene"
                slot="sceneId"
                class="new-select-tree"
                selectTreeTitle="所属场景"
                placeholder="请选择所属场景"
                :options="allServiceScene"
                v-model="formData.sceneId"
            />
            <!-- 地址 -->
            <el-input slot="address" clearable v-model.trim="formData.address" placeholder="请输入地址">
                <i class="iconfont location-icon" slot="suffix" @click="openMapSelect">&#xe663;</i>
            </el-input>
            <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
            <p slot="sceneId" class="scene-tip-style" >
                <i class="iconfont tips">&#xe639;</i>
                <span>如需正常播放视频，请完整填写视频预览地址、视频回放地址、视频回放地址、APPKEY、SCRERT、设备序列号、通道号等信息</span>
            </p>
        </zz-form>
        <el-dialog :append-to-body="true" title="选择地址" :visible.sync="dialogMapVisible" width="1000" :before-close="cancellocation">
            <div class="doalogmap">
                <div class="addressSearch">
                    <i class="iconfont location-icon-16" slot="suffix">&#xe663;</i>
                    <el-autocomplete
                        class="map-input-filter"
                        v-model="mapInputFilter"
                        :fetch-suggestions="querySearchAsync"
                        placeholder="请输入地址"
                        @select="handleSelect"
                        value-key="text"
                        ref="querySearchAsyncInput"
                    ></el-autocomplete>
                     <!-- 经度 longitude -->
                    <!-- 纬度 latitude -->
                    <el-input class="w100" v-model.trim="inputlongitude" @keyup.native="inputlongitude = oninput(inputlongitude,'x')" placeholder="请输入经度"></el-input>
                    <el-input class="w100" v-model.trim="inputlatitude" @keyup.native="inputlatitude = oninput(inputlatitude,'y')" placeholder="请输入纬度"></el-input>
                    <el-button class="map-input-btn" type="primary" @click="querySearchAsyncBtn"
                        ><i class="iconfont">&#xe6fc;</i>查询</el-button
                    >
                </div>
                <map-init ref="mapInit" v-on:getCityNamevalfn="getCityNameval"  @getwkidfn='getwkid' @getmoveXYfn='getmoveXY'></map-init>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancellocation">取 消</el-button>
                <el-button type="primary" @click="saveAddress">保 存</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import CoordConver from '@/utils/CoordConver.js';
export default {
    mixin: [CoordConver],
    props: ['params'],
    data() {
        return {
            organList: [
                {
                    id: 1,
                    tenantId: 'string123',
                    orgName: '公司',
                    parentOrgId: 0,
                    orgs: [{ id: 2, tenantId: 'string123', orgName: '部门', parentOrgId: 1, orgs: null, display: true }],
                    display: true
                }
            ],
            scenetypeList: [],
            allServiceScene: [],
            organListCompany: [],
            organListdepartment: [],
            formData: {
                address: '',
                companyOrgId: 0,
                deptOrgId: 0,
                deviceCode: 0,
                deviceMode: '',
                name: '',  //摄像头名称
                scrert: '', //萤石scrert 
                appkey: '', //萤石appkey
                deviceSerial: '',  //设备序列号
                channelNo: '',    //通道号
                deviceType: '',
                deviceTypeId: 0,
                enableState: 1,
                id: 0,
                manufacturerId: 0,
                pointX: 0,
                pointY: 0,
                remark: '',
                sceneId: 0,
                sceneName: '',
                status: 0,
                tenantId: '',
                channelNo: '' , //通道号
                palyUrl: ''     //视频预览地址
            },
            mapInputFilter: '',
            inputlongitude:'',
            inputlatitude:'',
            dialogMapVisible: false,
            defaultProps: {
                value: 'id', // 唯一标识
                label: 'orgName', // 标签显示
                children: 'orgs' // 子级
            },
            defaultPropsscene: {
                value: 'id', // 唯一标识
                label: 'sceneName', // 标签显示
                children: 'children' // 子级
            },
            formCols: [
                [
                    {
                        label: '名称',
                        prop: 'name',
                        input: true
                    },
                    {
                        label: '所属公司',
                        prop: 'companyOrgId',
                        slot: 'companyOrgId'
                    },
                    {
                        label: '所属部门',
                        prop: 'deptOrgId',
                        slot: 'deptOrgId'
                    },
                    {
                        label: '所属场景',
                        prop: 'sceneId',
                        slot: 'sceneId'
                    },
                    {
                        label: '地址',
                        prop: 'address',
                        slot: 'address'
                    },
                    {
                        label: '视频预览地址',
                        prop: 'palyUrl',
                        input: true
                    },
                    {
                        label: 'APPKEY',
                        prop: 'appkey',
                        input: true
                    },
                    {
                        label: 'SCRERT',
                        prop: 'scrert',
                        input: true
                    },
                    {
                        label: '设备序列号',
                        prop: 'deviceSerial',
                        input: true
                    },
                    {
                        label: '通道号',
                        prop: 'channelNo',
                        input: true
                    }
                ]
            ],
            formRules: {
                name: [this.$valid.inputRequired('名称'),this.$valid.limitVideoNumber20()],
                companyOrgId: [this.$valid.selectRequired('所属公司')],
                sceneId: [this.$valid.selectRequired('所属场景')],
                address: [this.$valid.inputRequired('地址'),this.$valid.limitVideo(), { trigger: 'change' }],
                palyUrl: [this.$valid.inputRequired('视频预览地址')],
                appkey: [this.$valid.inputRequired('APPKEY'),this.$valid.limitVideoNumber()],
                scrert: [this.$valid.inputRequired('SCRERT'),this.$valid.limitVideoNumber()],
                deviceSerial: [this.$valid.inputRequired('设备序列号'),this.$valid.limitVideoNumber()],
                channelNo: [this.$valid.inputRequired('通道号'),this.$valid.cameraChannel()]
            },
            formErrors: {},
            getCityName: '',
            getWkidVal:''
        };
    },
    created() {
        this.__setValue('formData');
        // this.formData = this.params.data ? this.params.data : this.formData;
        this.organList = this.params.organList ? this.params.organList : this.organList;
        this.scenetypeList = this.params.scenetypeList ? this.params.scenetypeList : this.scenetypeList;
         this.allServiceScene = this.params.allServiceScene ? this.params.allServiceScene : this.allServiceScene;
         this.organListCompany = this.params.organListCompany ? this.params.organListCompany : this.organListCompany;
        this.organListdepartment = this.params.organListdepartment ? this.params.organListdepartment : this.organListdepartment;
        this.deviceTypeIdoptions = this.params.deviceTypeIdoptions ? this.params.deviceTypeIdoptions : this.deviceTypeIdoptions;
        this.allRoleId = this.params.allRoleId ? this.params.allRoleId : this.allRoleId;
        this.allUserType = this.params.allUserType ? this.params.allUserType : this.allUserType;
        if(!this.formData.id){
            this.formData.enableState = 1
        }
    },
    methods: {
        getmoveXY(val){
            this.getmoveXYVal = val;
        },
        getwkid(val){
            this.getWkidVal = val;
        },
        // 获取子级传的值
        getCityNameval(val) {
            this.getCityName = val;
        },
        selectedcompanyOrgId(e) {
            this.formData.deptOrgId = '';
            this.organListdepartment = [];
            this.formData.sceneId = '';
            this.allServiceScene = [];
            if (!e) return;
            // 获取 部门树e
            this.$http.postForm('/sc-user-center/org/getOrgUserTree', { orgType: 'department', id: e }).then(({ status, data, msg }) => {
                if (status === 0) {
                    this.organListdepartment = data ? data : [];
                    this.selectedSceneOrgId();
                } else {
                    this.$message.error(msg);
                }
            });
        },
        selectedDepartOrgId(e) {
            this.formData.sceneId = '';  //选择部门时，清空场景原有值
            this.allServiceScene = [];   //选择部门时，清空场景原有值
            // if (e ==='') return ;
            
            this.selectedSceneOrgId(e); 
        },
        selectedSceneOrgId(e) {
            // if(!e)return   
            // 获取 上级场景列表
            this.$http
                .get('/sc-zoniot-water/scene/selectListForParm', { comId: this.formData.companyOrgId, deptId: this.formData.deptOrgId })
                .then(({ status, data, msg }) => {
                    if (status === 0) {
                        this.allServiceScene = data ? data : [];
                    } else {
                        this.$message.error(msg);
                    }
                });
        },
        // GCJ-02 => 墨卡托
        //经度转墨卡托
        handle_x(x) {
            return (x / 180.0) * 20037508.34;
        },
        //纬度转墨卡托
        handle_y(y) {
            if (y > 85.05112) {
                y = 85.05112;
            }
            if (y < -85.05112) {
                y = -85.05112;
            }
            y = (Math.PI / 180.0) * y;
            var tmp = Math.PI / 4.0 + y / 2.0;
            return (20037508.34 * Math.log(Math.tan(tmp))) / Math.PI;
        },


        /**
         * 调用高德地图执行模糊查询
         * @param {Number} page  当前页
         * @param {String} inputval  关键字
         * @param {Function} cb 回调函数
         * @param {Boolean} isMark 是否在地图上标记点
         */
        AmapSearch(page, inputval, cb, isMark) {
            var keywords = inputval;
            AMap.plugin('AMap.PlaceSearch', () => {
                var autoOptions = {
                    city: this.getCityName,
                    citylimit: true,
                    pageIndex: page
                };
                var placeSearch = new AMap.PlaceSearch(autoOptions);
                placeSearch.search(keywords, (status, result) => {
                    if (status != 'complete') {
                        return;
                    }
                    var datas = result.poiList;
                    let count = datas.count;
                    let crupage = datas.pageIndex;
                    let arr = datas.pois;
                    var pointData = [];
                    var returnObjectList = [];
                    for (let i = 0; i < arr.length; i++) {
                        const element = arr[i];
                        var xy = [];
                        var x = element.location.lng; //经度
                        var y = element.location.lat; // 纬度
                        x = this.handle_x(x);
                        y = this.handle_y(y);
                        xy.push(x);
                        xy.push(y);

                        var returnObject = new Object();
                        returnObject.id = element.id;
                        returnObject.text = element.name;
                        returnObject.address = element.address;
                        returnObject.XY = xy;
                        var marksData = {
                            json: xy
                        };
                        pointData = pointData.concat(marksData);
                        returnObjectList.push(returnObject);
                    }
                    // var symbol = new PictureMarkSymbolArgs();
                    // symbol.url = 'images/amap_l_gray.png';
                    // symbol.height = 36;
                    // symbol.width = 36;
                    // symbol.yoffset = 15;
                    // symbol.xoffset = 3;
                    // if (isMark) {
                    //     createMarkLayer(pointData, 'vagueQueryLyr', symbol);
                    // }
                    var resDatasObj = {
                        keywords: keywords,
                        page: crupage,
                        count: count,
                        list: returnObjectList
                    };
                    cb(resDatasObj);
                });
            });
        },
        querySearchAsyncBtn() {
            if(this.mapInputFilter){
                this.$refs.querySearchAsyncInput.handleFocus();
            }else{
                this.$http.post('/sc-operation-manager/track/TaskTrack/convertXY', {
                        "moveXY": this.getmoveXYVal,
                        "wkid": this.getWkidVal,
                        "xy": [`${this.inputlongitude},${this.inputlatitude}`]
                        })
                    .then(({ status, data, msg }) => {
                        this.handleSelect({
                            'XY':data.convertXY[0].split(','),
                            'text':''
                        })
                    })
            }
        },
        querySearchAsync(queryString, cb) {
            if (!queryString) return;
            if(this.getWkidVal===2360){
                this.$refs.mapInit.fuzzyQueryLocation(queryString,(res)=>{
                    let newarr = []
                    res.map(item=>{
                        var itemobj = {
                            XY:[item.feature.geometry.x,item.feature.geometry.y],
                            address:item.feature.attributes.TEXTSTRING,
                            id:item.feature.attributes.OBJECTID,
                            text:item.value
                        }
                        newarr.push(itemobj)
                    })
                    cb(newarr);
                });
            }else if(this.getWkidVal===3857){
                this.AmapSearch(
                    1,
                    queryString,
                    (result) => {
                        // 
                        console.log(result.list);
                        
                        cb(result.list);
                    },
                    false
                );
            }
        },
        /**
         * 调用高德地图执行模糊查询
         * @param {Number} page  当前页
         * @param {String} inputval  关键字
         * @param {Function} cb 回调函数
         * @param {Boolean} isMark 是否在地图上标记点
         */
        AmapSearch(page, inputval, cb, isMark) {
            var keywords = inputval;
            AMap.plugin('AMap.PlaceSearch', () => {
                var autoOptions = {
                    city: this.getCityName,
                    citylimit: true,
                    pageIndex: page
                };
                var placeSearch = new AMap.PlaceSearch(autoOptions);
                placeSearch.search(keywords, (status, result) => {
                    if (status != 'complete') {
                        return;
                    }
                    var datas = result.poiList;
                    let count = datas.count;
                    let crupage = datas.pageIndex;
                    let arr = datas.pois;
                    var pointData = [];
                    var returnObjectList = [];
                    for (let i = 0; i < arr.length; i++) {
                        const element = arr[i];
                        var xy = [];
                        var x = element.location.lng; //经度
                        var y = element.location.lat; // 纬度
                        x = this.handle_x(x);
                        y = this.handle_y(y);
                        xy.push(x);
                        xy.push(y);

                        var returnObject = new Object();
                        returnObject.id = element.id;
                        returnObject.text = element.name;
                        returnObject.address = element.address;
                        returnObject.XY = xy;
                        var marksData = {
                            json: xy
                        };
                        pointData = pointData.concat(marksData);
                        returnObjectList.push(returnObject);
                    }
                    // var symbol = new PictureMarkSymbolArgs();
                    // symbol.url = 'images/amap_l_gray.png';
                    // symbol.height = 36;
                    // symbol.width = 36;
                    // symbol.yoffset = 15;
                    // symbol.xoffset = 3;
                    // if (isMark) {
                    //     createMarkLayer(pointData, 'vagueQueryLyr', symbol);
                    // }
                    var resDatasObj = {
                        keywords: keywords,
                        page: crupage,
                        count: count,
                        list: returnObjectList
                    };
                    cb(resDatasObj);
                });
            });
        },
        openMapSelect() {
            this.dialogMapVisible = true;
            let item = {
                XY: '',
                address: '',
                id: '',
                text: ''
            }; 
            if (this.formData.pointX && this.formData.pointY) {
                item.XY = [this.formData.pointX, this.formData.pointY];
                item.text = this.formData.address;
            }
            this.$store.commit('setSearchPointInfo', item);
        },
        handleSelect(item) {
            this.formData.pointX = item.XY[0];
            this.formData.pointY = item.XY[1];
            this.formData.address = item.text;
            this.$store.commit('setSearchPointInfo', item);
            this.$refs.mapInit.centerAtByPoint(item.XY[0], item.XY[1]);
        },
        //地址地图取消
        cancellocation() {
            // this.$store.commit('setSearchPointInfo', '');
            // this.formData.pointX = '';
            // this.formData.pointY = '';
            // this.formData.address = '';
            this.dialogMapVisible = false;
        },
        //地址保存
        saveAddress() {            
            this.formData.pointX = this.$store.getters['getSearchPointInfo'].XY[0];
            this.formData.pointY = this.$store.getters['getSearchPointInfo'].XY[1];
            this.formData.address = this.$store.getters['getSearchPointInfo'].text;
            this.dialogMapVisible = false;
        },
        oninput(value,tip) {
            if(!value){return}
            if(tip==='x'){
                if(value>180||value<-180){
                    this.$message.warning('请输入正确的经度')
                    return value.substring(0,value.length-1);
                }
            }else{
                 if(value>90||value<-90){
                    this.$message.warning('请输入正确的纬度')
                    return value.substring(0,value.length-1);
                }
            }
            let str = value;
            let len1 = str.substr(0, 1);
            let len2 = str.substr(1, 1);
            //如果第一位是0，第二位不是点，就用数字把点替换掉
            if (str.length > 1 && len1 == 0 && len2 != ".") {
                str = str.substr(1, 1);
            }
            //第一位不能是.
            if (len1 == ".") {
                str = "";
            }
            if (len1 == "+") {
                str = "";
            }
            if (len1 == "-") {
                str = "";
            }

            //限制只能输入一个小数点
            if (str.indexOf(".") != -1) {
                let str_ = str.substr(str.indexOf(".") + 1);
                if (str_.indexOf(".") != -1) {
                str = str.substr(0, str.indexOf(".") + str_.indexOf(".") + 1);
                }
            }
            //正则替换
            str = str.replace(/[^\d^\.]+/g, ""); // 保留数字和小数点
            str = str.replace(/^\D*([0-9]\d*\.?\d{0,11})?.*$/, "$1"); // 小数点后只能输 11 位
            return str;
        },
        submit() {
            new Promise((resolve) => {
                this.$refs.form.validate(resolve);
            }).then(() => {
                var loading = this.$loading();
                var posturl = '';
                if(this.params.todo  === 'edit'){
                    posturl = '/sc-zoniot-water/cameraManage/update';
                }else {
                    posturl = '/sc-zoniot-water/cameraManage/insert'
                }
                this.formData.status = 1;
                this.$http.post(posturl, this.formData).then(({ status, data, msg}) => {
                    loading.close();
                    if(0 == status) {
                        this.$message.success(msg);
                        this.params.callback && this.params.callback();
                        this.$emit('close');
                    } else {
                        this.$message.error(msg);
                    }
                })
                .catch((err) => {
                    loading.close();
                })
            })
        }
    }
};
</script>

<style lang="scss" scoped>
@import '@assets/css/public-style.scss';
.scene-tip-style {
    text-align: left;
    position: absolute;
    top: 380px;
    i {
        font-size: 16px;
        color: #fe7271;
        vertical-align: middle;
        text-indent: -20px;
        display: inline-block;
        
    }
    span {
        font-size: 12px;
        margin-left: 10px;
    }
    .jumpbtn {
        color: $mainTextColor;
        padding: 10px 0px 10px 10px;
        cursor: pointer;
    }
}
.location-icon {
    font-size: 12px;
    color: #7B7F86;
}
.doalogmap {
    width: 910px;
    height: 460px;
    position: relative;

    .addressSearch {
        position: absolute;
        z-index: 10;
        width: 570px;
        height: 40px;
        background: #ffffff;
        box-shadow: 0px 5px 20px #d1d6dd;
        opacity: 1;
        border-radius: 6px;
        padding: 5px 6px;
        box-sizing: border-box;
        .w100{
            width: 100px;
            margin-right: 10px;
        }
        .location-icon-16 {
            font-size: 16px;
            color: #7d7f87;
        }
        .map-input-filter {
            width: 240px;
            height: 30px;
            background: #f5f5f5;
            opacity: 1;
            border-radius: 4px;
            margin: 0 10px;
        }
        .map-input-btn {
            width: 60px;
            height: 30px;
            background: $mainTextColor;
            opacity: 1;
            border-radius: 4px;
            padding: 0;
            vertical-align: top;
            i {
                margin-right: 4px;
            }
        }
    }
}

</style>