/**
 * Created by cp on 2018/7/2.
 */

import Style from 'ol/style/Style';
import Fill from 'ol/style/Fill';
import Stroke from 'ol/style/Stroke';
import Text from 'ol/style/Text';

import {addProjection, addCoordinateTransforms, transform} from 'ol/proj';

import WKT from 'ol/format/WKT';
import {circular} from 'ol/geom/Polygon';

import Icon from 'ol/style/Icon';
import Circle from 'ol/style/Circle';

// 定义类
class FeatureStyle {
  constructor(vueThis, mainMap) {
    this.vm = vueThis;//类中变量
    if (mainMap) {
      this.map = mainMap.getMap();//地图
      this.mainMap = mainMap;
    }
  }

  //缓存最近的一个feature
  setFeature(feature) {
    this.editFeature = feature;
  }

  getFeature() {
    return this.editFeature;
  }

  getFeatureStyle() {
    //在保存的时候提前获取样式信息进行保存
    let styleData = this.getFeature().get("currStyleData");
    if (!styleData) {
      //说明没有进行编辑
      styleData = JSON.parse(this.getFeature().get("data").style);
    }
    if (this.vm.featureType == this.vm.DRAW_CIRCLE) {
      //圆形  不能用普通的wkt坐转换  先转换成多边形进行存储
      styleData.center = this.editFeature.getGeometry().getCenter();
      styleData.radius = this.editFeature.getGeometry().getRadius();
    }
    return styleData;
  }


  modifyId() {
    if (!this.editFeature) {
      return null;
    }
    let feID = this.editFeature.getId();
    if (feID >= 0) {
      return feID;
    }
    return null;
  }

  getWkt() {
    if (!this.editFeature) {
      return null;
    }
    let format = new WKT();
    let wkt;

    wkt = format.writeGeometry(this.editFeature.getGeometry(), {
      featureProjection: 'EPSG:3857',
      dataProjection: 'EPSG:4326'
    });


    return wkt;
  }

// 弹出气泡方法  事件   obj 数据   layerName 图层名称
  popupWindow(type, evt, feature) {
    this.vm.featureType = type;
    this.setFeature(feature);
    let obj = feature.get("data");
    if (!obj) {
      obj = feature;//说明是外部被动调用
    }
    var coordinate;
    if (!evt) {
      //这时候需要定位  被动显示
      var endCenter4326 = [obj.lon, obj.lat];
      coordinate = transform(endCenter4326, 'EPSG:4326', 'EPSG:3857')
      this.mainMap.setCenterAndZoom(endCenter4326, null);
    } else {
      //点击地图触发
      coordinate = evt.event.coordinate;
    }
    this.mainMap.overlay.setPosition(coordinate);
  }

  popupModifyFeature(event, fe) {
    var coordinate;
    //点击地图触发
    coordinate = event.event.coordinate;
    if (!fe) {
      this.mainMap.overlay.setPosition(coordinate);
      return;
    }

    let feData = fe.get('data');
    this.vm.hotSpot = JSON.parse(JSON.stringify(feData));
    this.setFeature(fe);
    this.mainMap.overlay.setPosition(coordinate);

  }


  //关闭弹出框
  closePopupWindow() {
    this.mainMap.overlay.setPosition(undefined);
  }


  getFeatureStyleData(tempFeature) {
    let tempData = null;
    if (tempFeature) {
      //不存在的情况下使用初始的feature
      tempData = tempFeature.get("styleData");
    } else if (this.editFeature) {
      tempData = this.editFeature.get("styleData");
    }

    if (!tempData) {
      return false;
    }
  }

  //动态修改 feature样式
  setFeatureStyle() {

    let type = this.vm.hotSpot.type;

    let vueThis = this.vm;
    let styleData;
    if (type == vueThis.POINT_TYPE) {
      //点
      styleData = vueThis.hotSpot;
    } else if (type == vueThis.LINE_STRING_TYPE) {
      //线
      styleData = vueThis.lineStyle;
    } else {
      //其他的全是面  矩形圆形等等全是面
      styleData = vueThis.polygonStyle;

      if (type == vueThis.DRAW_CIRCLE) {
        styleData.center = this.editFeature.getGeometry().getCenter();
        styleData.radius = this.editFeature.getGeometry().getRadius();
      }
    }
    //把类型存储到数据库中
    styleData.type = type;
    styleData.icon = this.vm.hotSpot.imageUrl;
    let currFe = this.getFeature();
    //存储当前的样式数据
    currFe.set("currStyleData", JSON.parse(JSON.stringify(styleData)));
    let newStyle = this.getStyle(JSON.parse(JSON.stringify(styleData)));
    if (type == vueThis.DRAW_TEXT) {
      let textStyle = this.getTextStyle();
      currFe.setStyle(textStyle);
    } else {
      currFe.setStyle(newStyle);
    }
  }


  getTextStyle() {
    let vueThis = this.vm;
    let data = vueThis.textStyle;
    // let name =data.name;
    // let cWidth=name.length*30;
    // let cH=30+5;
    // var canvas=document.createElement('canvas');
    // canvas.width=cWidth;
    // canvas.height=cH;
    // canvas.x=0;
    // canvas.y=0;
    // var ctx=canvas.getContext("2d");
    // ctx.font="20px Georgia";
    // ctx.fillText("Hello World!",0,0);
//     ctx.font="30px Verdana";
// // 创建渐变
//     var gradient=ctx.createLinearGradient(0,0,canvas.width,0);
//     gradient.addColorStop("0","magenta");
//     gradient.addColorStop("0.5","blue");
//     gradient.addColorStop("1.0","red");
// // 用渐变填色
//     ctx.fillStyle=gradient;
//     ctx.fillText(name.name,0,0);


    //
    // var canvas =document.createElement('canvas');
    // canvas.width = 20;
    // canvas.height = 20;
    // var context = canvas.getContext("2d");
    // context.strokeStyle = "red";
    // context.lineWidth = 1;
    // context.beginPath();
    // context.moveTo(0, 0);
    // context.lineTo(20, 10);
    // context.lineTo(0, 20);
    // context.lineTo(10, 10);
    // context.lineTo(0, 0);
    // context.stroke();

    //
    // let imageSize=[canvas.width, canvas.height];
    // let drawStyle= new Style({
    //   image: new Icon(/** @type {olx.style.IconOptions} */ ({
    //     anchor: [0.5,0.5],
    //     img: canvas,
    //     imgSize: imageSize,
    //     opacity:1
    //   }))
    // });

    let textStyle = this.createTextStyle(data);
    let drawStyle = new Style({
      text: textStyle
    })
    return drawStyle;
  }

//赋予文字信息
  createTextStyle(data) {
    let textLabel = data.name;
    if (!textLabel || textLabel == "") {
      return null;
    }
    // var fezoom=data.maxZoom;
    // if(fezoom){
    //   var mapRe=map.getView().getResolution();
    //   var feRe=mapResoultion[fezoom]
    //   if(mapRe<feRe){
    //   }  else{
    //     textLabel="";
    //   }
    // }

    let textFont = data.weight + ' ' + data.size + "px" + ' ' + data.font;

    return new Text({
      textAlign: data.align,
      textBaseline: data.baseline,
      font: textFont,
      text: textLabel,
      fill: new Fill({color: data.fillColor}),
      stroke: new Stroke({color: data.outlineColor, width: data.outlineWidth}),
      offsetX: data.offsetX,
      offsetY: data.offsetY,
      rotation: data.rotation
    });
  };


//面的样式
  getStyle(styleData) {
    let vueThis = this.vm;
    let ol = this.ol;
    if (styleData.fillColor) {
      styleData.fillColor = styleData.fillColor.colorRgba(styleData.fillAlpha);
    }
    if (styleData.strokeColor) {
      styleData.strokeColor = styleData.strokeColor.colorRgba(styleData.strokeAlpha);
    }
    var tempPointStyle;
    //如果是点;
    let type = this.vm.hotSpot.type;
    let drawStyle;

    if (type == vueThis.POINT_TYPE) {
      if (styleData.icon && styleData.icon != "") {
        tempPointStyle = new Icon(({
          anchor: [0.5, 0.5],
          src: styleData.icon,
          opacity: 1
        }));
      } else {
        tempPointStyle = new Circle({
          radius: styleData.fileRadio,
          fill: new Fill({
            color: styleData.fillColor
          }),
          stroke: new Stroke({
            color: styleData.strokeColor,
            width: styleData.strokeWeight
          })
        })
      }

      drawStyle = new Style({
        image: tempPointStyle
      })
    } else {


      let storkobj = {};
      storkobj.color = styleData.strokeColor;
      storkobj.width = styleData.strokeWeight;
      if (styleData.lineDash && styleData.lineDash != null) {
        storkobj.lineDash = this.getLineDash(styleData.lineDash);
      }

      storkobj.lineCap = "round";

      // lineCap	string	'round'
      // Line cap style: butt, round, or square.
      //   lineJoin	string	'round'
      // Line join style: bevel, round, or miter.


      drawStyle = new Style({
        stroke: new Stroke(storkobj),
        fill: new Fill({
          color: styleData.fillColor
        }),
        // text:createTextStyle(pname,data)
      })
    }
    return drawStyle;
  }


  getLineDash(dashType) {
    // let vueThis= this.vm;
    // let endArr=[0];
    // vueThis.lineDashArr.forEach(function(item,index){
    //   if(dashType==item.type){
    //     endArr=item.dashArr;
    //     return  false ;
    //   }
    // })
    return false;
  }

  setToken(tempToken) {
    this.token = tempToken;
  }

//新增修改删除方法

  //类中函数
  getFeaturePageByLayerId(layerId, param, succFunc, failFunc) {
    let vm = this.vm;
    var tempToken = this.token;
    vm.$https({
      url: 'hotSpot/getListByBranchId?bankBranchId=' + layerId,
      method: 'get', authType: tempToken,
    }, param).then((res) => {
      if (succFunc) {
        succFunc(res.data);
      }
    }, (error) => {
      vm.$message({message: res.data.message, type: 'error'});
      if (failFunc) {
        failFunc();
      }
    })
  }


  //获取所有的图层数据
  getFeatureByLayerId(layerId, param, succFunc, failFunc) {
    param.layerId = layerId;
    let vm = this.vm;
    var tempToken = this.token;

    param = vm.$querystring.stringify(param);
    vm.$https({
      url: 'features/getFeatureList?',
      method: 'post', authType: tempToken,
    }, param).then((res) => {
      if (succFunc) {
        succFunc(res.data.data);
      }
    }, (error) => {
      vm.$message({message: res.data.message, type: 'error'});
      if (failFunc) {
        failFunc();
      }
    })
  }


  deleteFeatureFromLayer(featureId, succFunc) {
    //删除图层与feature的关系  目前是这样设计  后续是否可行在看
    let vm = this.vm;
    var tempToken = this.token;
    //删除活动事件
    vm.$confirm('此操作将删除该元素, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      vm.$https({
        url: 'hotSpot/delete?id=' + featureId,
        method: 'delete', authType: tempToken,
      }, {})
        .then((res) => {
            let data = res.data;
            //重新查询数据
            if (res.data.status == 200 || res.data.status == 201 || res.data.status == 203 || res.data.status == 204) {
              vm.$message({
                type: 'success',
                message: '删除成功!'
              });
              if (succFunc) {
                succFunc();
              }
            } else {
              vm.$message({
                type: 'fail',
                message: data
              });
            }
          }, (error) => {
            vm.$message({
              type: 'fail',
              message: "删除失败!" + error.response.data
            });
          }
        )


    }).catch(() => {
      this.$message({
        type: 'info',
        message: '已取消删除'
      });
    });
  }


  addFeature(searchObj, succFunc, failFunc) {
    var vm = this.vm;
    var param = vm.$querystring.stringify(searchObj);
    var tempToken = this.token;
    if (searchObj.id && searchObj.id != "") {
      vm.$https({
        url: 'hotSpot/edit',
        method: 'put', authType: tempToken,
      }, param)
        .then((res) => {
            if (res.data.status == 200 || res.data.status == 201) {
              vm.$message({message: res.data.message, type: 'success'});
            } else {
              vm.$message({message: res.data.message, type: 'error'});
            }
            if (succFunc) {
              succFunc(res);
            }
          }, (error) => {
            vm.$message({message: error.data.message, type: 'error'});
            if (failFunc) {
              failFunc(error);
            }
          }
        )
    } else {
      vm.$https({
        url: 'hotSpot/add',
        method: 'post', authType: tempToken,
      }, param)
        .then((res) => {
            if (res.data.status == 200 || res.data.status == 201) {
              vm.$message({message: res.data.message, type: 'success'});
            } else {
              vm.$message({message: res.data.message, type: 'error'});
            }
            if (succFunc) {
              succFunc(res);
            }
          }, (error) => {
            vm.$message({message: error.data.message, type: 'error'});
            if (failFunc) {
              failFunc(error);
            }
          }
        )
    }

  }


}

// FeatureStyle.para = 'Allen'; 静态变量
export {FeatureStyle};