var colorArray = [
    "#54211d",
    "#6d5826",
    "#70a19f",
    "#f2eada",
    "#999d9c",
    "#f36c21",
    '#826858',
    '#78a355',
    '#afb4db',
    '#9b95c9',
    '#6f60aa',
    '#867892',
    '#225a1f',
    '#367459',
    '#007947',
    '#00ae9d',
    '#50b7c1',
    '#008792',
    '#11264f',
    '#cbc547',
    '#ffe600',
    '#f3704b',
    '#1b315e',
    '#1d1626',
    '#a3cf62',
    '#181d4b'
];

var flashStyle1 = new ol.style.Style({
    //边框样式
    stroke: new ol.style.Stroke({
        color: 'red',
        width: 2
    }),
    //填充样式
    fill: new ol.style.Fill({
        color: 'rgba(255, 255, 0, 0.3)',
    }),
})
var flashStyle2 = new ol.style.Style({
    //边框样式
    stroke: new ol.style.Stroke({
        color: 'blue',
        width: 2
    }),
    //填充样式
    fill: new ol.style.Fill({
        color: 'rgba(0, 0, 255, 0.3)',
    }),
})

var colorStyle = function(feature) {
    var values = feature.getProperties();
    return new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: 'black',
            lineDash: [4],
            width: 0.5
        }),
        fill: new ol.style.Fill({
            color: colorArray[values.objectid % (colorArray.length - 1)]
        })
    })
};


function Analyse(option){
    this.layer = option.layer
    this.tabs = option.tabs
    this.url = option.url
    this.featureMap = {}
    this.tabIndex = option.tabIndex || 0;
    this.resultData = null
}
Analyse.prototype = {
    layoutHtml(){
        var html='<div style="margin: 0 0 0 0" class="layui-tab layui-tab-brief" lay-filter="docDemoTabBrief"><ul class="layui-tab-title">'
        for(var i=0;i < this.tabs.length;i++){
            let tabs = this.tabs[i];
            var title = tabs.title;
            html +='<li data-value="'+i+'" class="analyse_tabs ' + (i == this.tabIndex ? 'layui-this' : '') + '" ><a>'+title+'</a></li>';
        }
        html +='</ul>';
        html +='<div style="text-align: center;margin-top: 12px;"><input type="radio"  name="showType" value="1"  checked="true">表格&nbsp&nbsp<input type="radio" type="showType" name="showType" value="2" title="饼状图" >饼状图</div>'

        html += '<div id="analyse_table_content"  class="layui-tab-content">'

        html+=' </div><div style="padding-left: 10px;padding-bottom:10px;">分析总面积:<label id="sumArea"></label></div></div>'
        return html;
    },
    load(feature){
        var that = this;
        $(".analyse_tabs").on("click", function(e){
            that.tabIndex = $(e.currentTarget).attr("data-value")
            that.resultData = that._send(feature)
            that._drawing()
        })
        $("input[name='showType']").on("click", function(e){
            that._drawing()
        })
        this.resultData = this._send(feature)
        this._drawing()
    },
    _drawing(){
        var data = this.resultData;
        var tap = this.tabs[this.tabIndex];
        if(data.code != 0){
            layui.notice.error(data.msg);
            return;
        }
        this._writeBody(data.data, tap)
        this._drawGraph(data.data)
    },
    _writeBody(analyseTable, tap){
        var val = 1
        for(var check of $("input[name='showType']"))
            if(check.checked)
                val = check.value
        this._writeSumArea(analyseTable["sumArea"])
        if(val == 1)
            this._writeBody_table(analyseTable, tap)
        else if(val == 2)
            this._writeBody_cake(analyseTable, tap)

    },
    _writeSumArea(sumArea){
        $("#sumArea").text(sumArea+"亩")
    },
    _writeBody_table(analyseTable, tap){
        var table ='<table class="layui-table"><thead>';
        for(let col of tap.cols){
            table += '<th>'+ col.title + '</th>'
        }
        table += '</thead><tbody>'
        for(let analyseRow of analyseTable.analyseRows){
            table += '<tr class="analyse_rows" data-value="' + analyseRow.values["objectid"] + '">'
            for(let col of tap.cols) {
                if(col.filter){
                    table += '<td>' + col.filter(analyseRow.values) + '</td>'
                }else{
                    table += '<td>' + analyseRow.values[col.field] + '</td>'
                }
            }
            table += '</tr>'
        }
        table+=' </tbody></table>'
        $("#analyse_table_content").html(table)
        var that = this
        $(".analyse_rows").on("click", function(e){
            var objectid = $(e.currentTarget).attr("data-value")
            that.shine(objectid)
        })
    },
    _writeBody_cake(analyseTable, tap){
        var that = this
        $("#analyse_table_content").html('<div id ="chartdiv" style="width: 100%;height:350px;"></div>')
        var data = new Array()
        var colors = new Array()
        for(let analyseRow of analyseTable.analyseRows){
            data.push({
                "objectid": analyseRow.values["objectid"],
                "name": analyseRow.values["name"],
                "value":analyseRow.values["percent"],
                "area":analyseRow.values["area"]+"(平方米)",
            })
            colors.push(colorArray[analyseRow.values.objectid % (colorArray.length - 1)])
        }
        var chartDom = document.getElementById('chartdiv');
        var myChart = echarts.init(chartDom);
        var option = {
            title: {
                show:false
            },
            tooltip: {
                trigger: 'item'
            },
            legend: {
                orient: 'horizontal',
                left: 'left'
            },
            series: [
                {
                    name: '名称   占比（%）',
                    type: 'pie',
                    radius: '50%',
                    data: data,
                    colorBy:'color',
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ],
            color:colors
        };
        myChart.on('click', {}, function (e) {
            var objectid = e.data["objectid"]
            that.shine(objectid)
        });
        option && myChart.setOption(option);
    },
    _drawGraph(analyseTable){
        this.clear()
        var features = new Array()
        for(let row of analyseTable.analyseRows){
            var feature = (new ol.format.GeoJSON()).readFeature(row.featureJson);
            features.push(feature)
            this.featureMap[row.values["objectid"]] = feature;
        }
        this.layer.getSource().addFeatures(features)
    },
    _send(feature){
        var tap = this.tabs[this.tabIndex];
        return layui.tool.postSync(this.url, {type: tap.type,wkt: this._format(feature)});
    },
    _format(feature){
        var wkt_c = new ol.format.WKT();
        var wkt =wkt_c.writeFeature(feature)
        console.log(wkt)
        return wkt;
    },
    clear(){
        this.layer.getSource().clear()
        this.featureMap = {}
    },
    _interval: null,

    shine(objectid){
        var feature = this.featureMap[objectid]
        //停止闪烁的标志
        let flag = 0;
        //闪烁方法对象
        this._interval = setInterval(
            function () {
                //闪烁次数
                if (flag <= 3) {
                    if (flag % 2 == 0) {
                        feature.setStyle(flashStyle1);
                    } else {
                        feature.setStyle(flashStyle2);
                    }
                    flag++;
                } else {
                    //停止闪烁,还原样式,删除间隔对象
                    feature.setStyle(colorStyle(feature));
                    window.clearInterval(this._interval);
                }
                //间隔时间
            }, 200);

    }

}
