/**
 * Created by Administrator on 2021/4/5.
 */
define(['jquery', "template", "Tools", "paging", 'dateTime', 'swiper'], function ($, template, Tools) {
    //数据存储
    var module = {
        data: {
            propertyList:'',
            treeselect:[{
                value:100,
                label:'全部'
            }],
            treeselectSecond:[{
                value:100,
                label:'全部'
            }],
            useType:[{
                dictValue:'',
                dictLabel:'全部'
            }],
            propertyDetail:{},
            map: '',                // 地图图层
            resourceLayer: '',      // 资源图层
        },
    };
    var tools = new Tools();

    module.init = function (page) {
        tools.doGet(treeselect, {}, module.treeselect , true);
        tools.doGet(webList, {}, module.webList , true);
        // tools.doGet(webDeptType+'use_code', {}, module.webDeptType , true);

    };

    module.useContent = function (data) {
        if (data.code == 200) {
            module.data.treeselectA = data.data;
            module.data.phone = data.data.phone;
            module.data.leader = data.data.leader;
            var propertyDetailData = template('propertyDetailData', module.data);
            $("#propertyDetailContent").html(propertyDetailData);
            module.data.map.getView().setCenter(ol.proj.fromLonLat([data.data.lng, data.data.lat]));
            module.data.map.getView().setZoom(13);
        }
    }

    module.webDeptType = function (data) {
        if (data.code == 200) {
            var content = data.data;
            content.map(res=>{
                module.data.useType.push(res)
            })
            // module.data.useType = content;
            var useTypeData = template('useTypeData', module.data);
            $("#useTypeContent").html(useTypeData);
        }
    }

    module.webList = function (data) {
        if (data.code == 200) {
            var content = data.data;
            module.data.webList = content;
            var webData = template('webData', module.data);
            $("#webContent").html(webData);
            var titData = template('titData', module.data);
            $("#titContent").html(titData);
            $('#ewm').attr('src', 'static/images/'+content.top.bz);
        }
    }

    module.assetList = function (data) {
        if (data.code == 200) {
            var content = data.rows;
            if (module.data.propertyList == '') {
                var page_s1 = createPage('.page_s1');
                //设置分页
                setPage(page_s1, {
                    pageTotal: data.total, // 数据总条数
                    pageSize: 10,    // 每页显示条数
                    pageCurrent: 1,  //  当前页
                    maxBtnNum: 5,   // 最多按钮个数  （最少5个）
                })
            }
            module.data.propertyList = content;
            // 添加资源图层
            addResourceLayer(content);
            // $('#page_s1').html('共' + 10 + '页')
            var propertyData = template('propertyData', module.data);
            $("#propertyContent").html(propertyData);
        }
    }

    // 添加资源图层
    addResourceLayer = function (content) {
        if (module.data.resourceLayer) {
            module.data.map.removeLayer(module.data.resourceLayer);
            module.data.resourceLayer = '';
        }
        let features = [];
        content.forEach(item => {
            if (item.theGeom != null && item.theGeom !== '') {
                const iconFeature = new ol.Feature({
                    geometry: new ol.geom.MultiPolygon(JSON.parse(item.theGeom).coordinates),
                    // name: item.centerName,
                    // centerDeptId: item.deptId,
                    level: 'resource',
                    id: item.id
                });
                features.push(iconFeature);
            }
        });
        const vectorSource = new ol.source.Vector({
            features: features,
        });
        module.data.resourceLayer = new ol.layer.Vector({
            source: vectorSource,
            name: 'resourceLayer',
            style: new ol.style.Style({
                fill: new ol.style.Fill({
                    //矢量图层填充颜色，以及透明度
                    color: "rgba(255, 255, 0, 0.3)",
                }),
                stroke: new ol.style.Stroke({
                    //边界样式
                    color: "#ffff00",
                    width: 2,
                }),
            })
        });
        module.data.map.getLayers().insertAt(3, module.data.resourceLayer);
    }

    openDialog = function(id){
        tools.doGet(assetresourceGet+id, {translate_dict: 1}, module.assetDetail , true);
    }

    closeDialog = function(id){
        $('#dialog').css('display','none');
    }

    module.assetDetail = function(data){
        if (data.code == 200) {
            var content = data.data;
            module.data.propertyDetail = content;
            tools.doGet(attachmentList, {
                tableId:content.id,
                tableName: 't_asset_resource',
                bizPath: 'asset'
            }, module.attachmentDetail , true);
            // var propertyDetailData = template('propertyDetailData', module.data);
            // $("#propertyDetailContent").html(propertyDetailData);
            // $('#dialog').css('display','block');
        }
    }

    module.attachmentDetail = function(data){
        if (data.code == 200) {
            var content = data.rows;
            var attachmentList = [];
            content.map(res=>{
                if (res.fileName.indexOf('png')>-1||res.fileName.indexOf('jpg')>-1){
                    attachmentList.push(res);
                }
            })
            module.data.attachment = attachmentList;
            var propertyDetailData = template('propertyDetailData', module.data);
            $("#propertyDetailContent").html(propertyDetailData);
            $('#dialog').css('display','block');
        }
    }

    module.treeselect = function(data){
        if (data.code == 200) {
            var content = data.data[0].children;
            content.map(res=>{
                module.data.treeselect.push(res)
            })
            // module.data.treeselect = content[0].children;
            // module.data.treeselectA = data.data[0];
            var treeselectData = template('treeselectData', module.data);
            $("#treeselectContent").html(treeselectData);
            var treeselectSecondData = template('treeselectSecondData', module.data);
            $("#treeselectSecondContent").html(treeselectSecondData);
            initMap(data.data[0]);
            //资产列表
            tools.doGet(assetresourceList, {
                deptId: 100,
                translate_dict: 1,
                pageNum: 1,
                pageSize: 10,
                useType:'2'
            }, module.assetList , true);
            tools.doGet(treeselectSecond+'100', {}, module.useContent, true);
        }
    }

    initMap = function (dept) {
        let mapCenterLocation;
        if (dept.lng && dept.lat) {
            mapCenterLocation = [dept.lng, dept.lat];
        } else {
            mapCenterLocation = [116.391461, 39.902359];
        }

        document.getElementById("container").innerHTML = "";
        // 定义地图投影
        let projection = new ol.proj.Projection({
            code: "EPSG:3857",
            units: "degrees",
        });
        // 定义地图图层
        let aerial = new ol.layer.Tile({
            source: new ol.source.XYZ({
                url: "http://t{0-7}.tianditu.com/img_w/wmts?" +
                    "SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles" +
                    "&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=cc4aba6e967096098249efa069733067",
            }),
            isGroup: true,
            name: "卫星影像图",
        });
        let yingxzi = new ol.layer.Tile({
            source: new ol.source.XYZ({
                url: "http://t{0-7}.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=cc4aba6e967096098249efa069733067",
            }),
            isGroup: true,
            name: "天地图文字标注--卫星影像图",
        });
        //加载地图
        module.data.map = new ol.Map({
            controls: ol.control.defaults({attribution: false, zoom: false, rotate: false}).extend([]),
            layers: [aerial, yingxzi],
            projection: projection,
            target: "container",
            view: new ol.View({
                center: ol.proj.fromLonLat(mapCenterLocation), // 地图中心坐标
                zoom: 13,
                minZoom: 1, //地图缩小限制
                maxZoom: 18, //地图放大限制
                // extent: [13481224.75161,5667110.83528,13811063.06278,5880284.11416]
            }),
            /*interactions: ol.interaction.defaults({
              doubleClickZoom: false,   // 双击放大地图
              // mouseWheelZoom: false,    // 鼠标滚轮放大地图
              // shiftDragZoom: false,     // shift + 鼠标左键拖拽 放大地图
            })*/
        });
        // 地图点击事件
        module.data.map.on("click", (evt) => {
            let feature = module.data.map.forEachFeatureAtPixel(
                evt.pixel,
                (feature) => feature
            );
            if (feature) {
                if (feature.get('level') === 'resource') {
                    openDialog(feature.get('id'));
                }
            }
        });
        // 鼠标指针移动到指定的feature上，改变鼠标指针的样式为 pointer(小手)
        module.data.map.on('pointermove', (evt) => {
            if (evt.dragging) {
                return ;
            }
            const pixel = module.data.map.getEventPixel(evt.originalEvent);
            // const hit = module.data.map.hasFeatureAtPixel(pixel);
            // let features = module.data.map.getFeaturesAtPixel(pixel);
            const hit = module.data.map.forEachFeatureAtPixel(pixel, function (feature) {
                if (feature && feature.get('level') === 'resource') {
                    return true;
                }
            });
            module.data.map.getTargetElement().style.cursor = hit ? 'pointer' : '';
        });
    }

    selectChange = function(){
        // tools.doGet(treeselectSecond+$('#treeselectContent').val(), {}, module.selectSecondChange , true);
        if ($('#treeselectContent').val() == 100){
            module.data.treeselectSecond = [{
                value:100,
                label:'全部'
            }]
            tools.doGet(treeselectSecond+'100', {}, module.useContent , true);
        }else{
            module.data.treeselectSecond = module.data.treeselect.filter(function (e) { return e.value == $('#treeselectContent').val(); })[0].children;
            tools.doGet(treeselectSecond+$('#treeselectContent').val(), {}, module.useContent , true);
        }
        var treeselectSecondData = template('treeselectSecondData', module.data);
        $("#treeselectSecondContent").html(treeselectSecondData);

        selectSecondChange();
    }

    selectSecondChange = function(){
        $('.page_s1').html('');
        module.data.propertyList = "";
        tools.doGet(assetresourceList, {
            deptId: $('#treeselectSecondContent').val(),
            translate_dict: 1,
            useType:$('#useTypeContent').val(),
            pageNum: 1,
            pageSize: 10,
        }, module.assetList , true);
        tools.doGet(treeselectSecond+$('#treeselectSecondContent').val(), {}, module.useContent , true);

        //资产列表
        // tools.doGet(assetList, {
        //     deptId: $('#treeselectSecondContent').val(),
        //     useType: $('#useTypeContent').val() == null ? 1 : $('#useTypeContent').val(),
        //     operationType: 1,
        //     translate_dict: 1,
        //     pageNum: 1,
        //     pageSize: 10,
        //     orderByColumn: 'code',
        //     isAsc: 'asc',
        // }, module.assetList , true);
    }

    useTypeChange = function () {
        $('.page_s1').html('');
        module.data.propertyList = "";
        tools.doGet(assetresourceList, {
            deptId: $('#treeselectSecondContent').val() == null ? 100 : $('#treeselectSecondContent').val(),
            useType:$('#useTypeContent').val(),
            translate_dict: 1,
            pageNum: 1,
            pageSize: 10,
        }, module.assetList , true);
    }

    turnThePage = function (pageNum) {
        tools.doGet(assetresourceList, {
            deptId: $('#treeselectSecondContent').val() == null ? 100 : $('#treeselectSecondContent').val(),
            useType:$('#useTypeContent').val(),
            translate_dict: 1,
            pageNum: pageNum,
            pageSize: 10,
        }, module.assetList , true);
    }

    openBig = function () {
        $("#open").css('display','none');
        $(".table_main").css('display','none');
        $(".pageNum").css('display','none');
        $("#close").css('display','block');
        $("#map_main").css({
            'height': '59vh',
            'position': 'absolute',
            'top': '1vh',
            'width': 'calc(100% - 2vh)',

        })
        $("#container").css('height','59vh')
        initMap(module.data.treeselectA);
        // 添加资源图层
        addResourceLayer(module.data.propertyList);
    }

    closeBig = function () {
        $("#open").css('display','block');
        $(".table_main").css('display','block');
        $(".pageNum").css('display','block');
        $("#close").css('display','none');
        $("#map_main").css({
            'height': '16vh',
            'position': 'relative',
            'width': '100%',
            'top': '0vh',
        })
        $("#container").css('height','16vh')
        initMap(module.data.treeselectA);
        // 添加资源图层
        addResourceLayer(module.data.propertyList);
    }

    return module;
});
