/**
 * chengj
 * 2020.10.28
 * 在途货物跟踪
 */
import { UPCLOUD_RDC_TMS_MAINDATA_SERVICE,UPCLOUD_RDC_TMS_BUSINESS_SERVICE,UPCLOUD_RDC_TMS_INTERFACE_SERVICE} from '@/config/serviceSettings.js';
import { getSelectGJ, querySysPicture } from '@/utils/prolog.ajax.js';


export default () => {
  // debugger;
  var map;
  var myGeo;
  // 获取默认时间
  var startTime = Prolog.formatDate(new Date(), "%YY-%MM") + "-01 00:00:00";
  var endTime = Prolog.formatDate(new Date()) + " 23:59:59";
  // 获取下拉框
  var dataSelect;
  getSelectGJ([
    { "objectcode": "URG_FLG" }, { "objectcode": "TMS_SHIP_BILLSTATUS" }, { "objectcode": "TMS_LOADING_BILLSTATUS" }, { "objectcode": "TMS_REF_BILLTYPE" }, { "objectcode": "TMS_SHIP_BILLTYPE" },
     { "objectcode": "TEMP_REQ" }
  ], function (data) {
    dataSelect = data.data;
    dataSelect.URG_FLG.unshift({ "value": "", "text": "" });
  });
  var opts = {
    //terrace显示全部，card分页显示
    skin: "card",
    columns: [
      { id: "shipbillno", name: "id", type: "ro", width: "100", hidden: true },
      { id: "branchname", name: "配送中心", type: "ro", width: 150 },
      {
        id: "status", name: "单据状态", type: "ro", width: 150, render: (v) => {
          return getSelectValue(dataSelect.TMS_SHIP_BILLSTATUS, v);
        }
      },
      {
        id: "shipbillno",
        name: "运单号",
        type: "ro",
        width: 100
      },
      { id: "billdate", name: "单据日期", type: "ro", width: 100 },
      { id: "refbillno", name: "业务单号", type: "ro", width: 100 },
      { id: "shiptoCustomerName", name: "客户名称", type: "ro", width: 130 },
      { id: "shiptoAddress", name: "客户地址", type: "ro", width: 100 },
      { id: "rsumcases", name: "件数", type: "ro", width: 100 },
      { id: "carriername", name: "承运商", type: "ro", width: 100 },
      { id: "driver1stname", name: "司机", type: "ro", width: 100 },
      { id: "voucherno", name: "车辆", type: "ro", width: 100 },
      { id: "memo", name: "备注", type: "ro", width: 100 }
    ],
    toolbar: [
      { type: "settings", labelWidth: 70, labelAlign: "right" },
      {
        type: "row",
        list: [
          { type: "calendar", className: "layui-col-md4", name: "startdate", label: "开始时间:", value: startTime, readonly: true },
          { type: "calendar", className: "layui-col-md4", name: "enddate", label: "结束时间:", value: endTime, readonly: true },
          { type: "input", name: "refbillno", className: "layui-col-md4", label: "业务单号:" },
          { type: "input", name: "shipbillno", className: "layui-col-md4", label: "运单号:" },
          {
            type: "block", className: "layui-col-md10 form_btn_left",
            list: [
              { type: "button", className: "btn-normal", name: "querywork", value: "查 询" },
              { type: "newcolumn" },
              { type: "button", name: "work_Reset", className: "normal", value: "重 置" }
            ]
          },
          {
            type: "block", className: "layui-col-md2 ",
            list: [
              { type: "button", name: "car_export", className: "btn-normal", value: "导 出" }
            ]
          }
        ]
      }],
    url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/report/onThewayGoodsQuery", //数据接口
    type: "post", //数据提交方式，默认为get
    contentType: "application/json",
    params: JSON.stringify({ startdate: startTime, enddate: endTime }), //查询提交参数，分页参数默认为pageNum,pageSize
    page: true, //是否启用分页
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };
  //分页参数 pageSize pageNum
  grid = new PlgGrid(opts);
  grid.renderTo("onThewayGoodsQuery_div2A");
  //分组拆分条件查询
  grid.loadData();

  //按钮添加方法
  grid.attachToolBarEvent("onButtonClick", function (name) {
    //查询
    if (name == "querywork") {
      var jsonData = grid.getToolBarForm().getFormData();
      if (jsonData.startdate == null) {
        jsonData.startdate = FormatDate(new Date()) + " 00:00:00";
      }
      else {
        jsonData.startdate = Prolog.formatDate(jsonData.startdate) + " 00:00:00";
      }
      if (jsonData.enddate == null) {
        jsonData.enddate = FormatDate(new Date()) + " 23:59:59";
      }
      else {
        jsonData.enddate = Prolog.formatDate(jsonData.enddate) + " 23:59:59";
      }
      if (jsonData.startdate > jsonData.enddate) {
        layer.msg("开始时间不能大于结束时间");
        return false;
      }
      grid.setParams(JSON.stringify(jsonData));
      grid.reload();
    }
    //重置
    if (name == "work_Reset") {
      grid.getToolBarForm().getDForm().setText("consignorcode1", "");
      grid.getToolBarForm().clear();
      grid.getToolBarForm().setFormData({ startdate: startTime, enddate: endTime });
    }
    //保存
    if (name == "work_Reset2") {
      layer.msg("成功");
    }
    //导出
    if (name == "car_export") {
      unfilledWorktime_export();
    }
  });
  //主界面导出事件
  function unfilledWorktime_export() {
    let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    if (grid.getRowsNum() <= 0) {
      PlgDialog.close(pload);
      PlgDialog.msg("没有要导出的数据");
      return;
    }
    let url = UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/report/onThewayGoodsExport";
    let name = "在途货物跟踪" + Prolog.formatDate(new Date(), "%YY%MM%DD") + ".xls";
    var jsonData = grid.getToolBarForm().getFormData();
    if (jsonData.startdate == null) {
      jsonData.startdate = FormatDate(new Date()) + " 00:00:00";
    }
    else {
      jsonData.startdate = Prolog.formatDate(jsonData.startdate) + " 00:00:00";
    }
    if (jsonData.enddate == null) {
      jsonData.enddate = FormatDate(new Date()) + " 23:59:59";
    }
    else {
      jsonData.enddate = Prolog.formatDate(jsonData.enddate) + " 23:59:59";
    }
    if (jsonData.startdate > jsonData.enddate) {
      PlgDialog.close(pload);
      layer.msg("开始时间不能大于结束时间");
      return false;
    }
    Prolog.exportFile(url, name, "application/json", "post", jsonData);
    PlgDialog.close(pload);

  }
  //单击事件
  grid.on("onRowSelect", function (rid) {
    let rd = grid.getRowData(rid);
    setPlace(rd.arriveAddress);
  });


  //初始化方法
  function loadData() {

  }

  //#region 百度地图相关代码
  function loadDefulatMap(callback) {
    var point = new BMap.Point(116.404, 39.915); // 创建点坐标
    map.centerAndZoom(point, 15); // 初始化地图，设置中心点坐标和地图级别
    map.addControl(new BMap.NavigationControl());
    map.addControl(new BMap.ScaleControl());
    map.addControl(new BMap.OverviewMapControl());
    //map.addControl(new BMap.MapTypeControl()); //不同类型的百度地图
    map.setCurrentCity("北京"); // 仅当设置城市信息时，MapTypeControl的切换功能才能可用
    //地图加载完成后加载数据
    callback();
  }
  //地图选点点击事件
  function clickCoordinate(e) {
    var point = e.point;
    // console.log(point);
    //请先选择省市区
    //var area = $(".store_Area").val();
    //if (area == null || area == "") {
    //    alert(baiduParam.SelectRegion_Error);
    //    return;
    //}
    createMarker(point);
  }
  function setPlace(value) {
    var local = new BMap.LocalSearch(map, { //智能搜索
      onSearchComplete: myFun
    });
    function myFun() {
      if (local.getResults().getPoi(0)) {
        var point = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
        createMarker(point);
      }
      else {
        alert("未搜索到结果，请重新输入");
      }
    }
    local.search(value);
  }

  var baiduParam = {
    oldPoint: null,//记录旧值,用于地图拖拽失败后回到原来位置
    Exceed_Error: "定位地址失败，您搜索或定位超出县级范围，请重新选择定位",
    SelectRegion_Error: "定位地址失败，您搜索或定位超出县级范围，请先选择省市区",
    Location_Div: "<div id='descConten'>已将坐标定位为<hr/>{address}<br/><small style='color: #858585;line-height: 24px;'>地址：{title}</small><br/><br/><input type='button' value='确定' id='saveLngLat' style=' background: rgb(135,205,208);border: none;color: white;height: 30px;width: 60px;border-radius: 4px;' ></div> ",
    Location_Sure_Div: "<img style='width:20px;top: 5px;position: relative;'  src='img/success.png' />已将坐标定位为<hr/>{address}<br/><small style='color: #858585;line-height: 24px;'>地址：{title}</small><br/><br/>"
  };

  function createMarker(point, isLoad) {
    //反向解析地址
    myGeo.getLocation(point, function (rs) {
      map.clearOverlays();//清除之前所有的标志

      //红点开始
      var marker = new BMap.Marker(point);// 创建标注
      map.addOverlay(marker); // 将标注添加到地图中
      marker.enableDragging();//可拖拽 自定义拖拽
      //拖拽前事件
      marker.addEventListener("dragstart", function (e) {
        baiduParam.oldPoint = e.point;
      });
      //拖拽完成事件
      marker.addEventListener("dragend", function (e) {
        createMarker(e.point);
      });
      //红点完成

      baiduParam.oldPoint = null;
      /******** 图层初始化 ********/
      /**图层样式文字处理开始**/
      var html = baiduParam.Location_Div;
      if (isLoad == true) {
        map.centerAndZoom(point, map.getZoom()); //重置地图位置
        html = baiduParam.Location_Sure_Div;
      }
      //解析地址
      var rsaddress = rs.address;
      var rstitle = rs.surroundingPois[0] != null ? rs.surroundingPois[0].title : "";
      html = html.replace("{address}", rsaddress).replace("{title}", rstitle);
      /**图层样式文字处理结束**/

      var infoWindow = new BMap.InfoWindow(html, { offset: { width: 0, height: -25 } });
      // 创建信息窗口对象
      map.openInfoWindow(infoWindow, point); //开启信息窗口
      //确定事件绑定
      infoWindow.addEventListener("open", function () {
        $("#saveLngLat").unbind("click");
        $("#saveLngLat").click(function () {
          infoWindow.setContent("<img style='width:20px;top: -2px;position: relative;' src='img/success.png' />已将坐标定位为<hr/>" + rs.address + "<br/><small style='color: #858585;line-height: 24px;'>地址：" + (rs.surroundingPois[0] != null ? rs.surroundingPois[0].title : "") + "</small><br/><br/>");
          $(".store_Lng").val(rs.point.lng);
          $(".store_Lat").val(rs.point.lat);
        });
      });
      infoWindow.redraw(function () {
        $("#saveLngLat").unbind("click");
        $("#saveLngLat").click(function () {
          infoWindow.setContent("<img style='width:20px;top: -2px;position: relative;'  src='img/success.png' />已将坐标定位为<hr/>" + rs.address + "<br/><small style='color: #858585;line-height: 24px;'>地址：" + (rs.surroundingPois[0] != null ? rs.surroundingPois[0].title : "") + "</small><br/><br/>");
          $(".store_Lng").val(rs.point.lng);
          $(".store_Lat").val(rs.point.lat);
        });
      });
      /******** 图层初始化 ********/
    });
  }
  //#region /****查询控件类****/
  function BigZoomControl() {
    // 设置默认停靠位置和偏移量
    this.defaultAnchor = BMAP_ANCHOR_TOP_RIGHT;
    this.defaultOffset = new BMap.Size(150, 20);
  }
  setTimeout(() => {
    // 通过JavaScript的prototype属性继承于BMap.Control
    BigZoomControl.prototype = new BMap.Control();
    // 自定义控件必须实现自己的initialize方法,并且将控件的DOM元素返回
    // 在本方法中创建个div元素作为控件的容器,并将其添加到地图容器中
    BigZoomControl.prototype.initialize = function (map) {
      // 创建一个DOM元素
      var div = document.createElement("div");
      // 设置样式
      div.style.cursor = "pointer";
      div.style.margin = "0 auto";
      div.style.backgroundColor = "white";
      div.innerHTML = "<div><input type='text' id = 'baiduAddress' name = 'baiduAddress' style='width: 350px;height: 33px;text-indent:1em;float:left;border: 1px solid #D2D2D2!important;border-right:none;' placeholder='输入门店详细地址, 越详细定位越精准' /><div  class='searchMap' style='border:1px solid #f50;background-color:#f50;width:60px;height:33px;float:left;'></div><img  class='searchMap' src='img/search.png' style='height: 22px;position: absolute;right: 18px;top: 7px;'/><div style='clear:both'></div></div>";
      // 添加DOM元素到地图中
      map.getContainer().appendChild(div);
      // 将DOM元素返回
      return div;
    };
    //#endregion
    //#endregion

    //#region 百度地图初始化
    /****************百度地图初始化开始****************/
    map = new BMap.Map("myMap");
    map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
    // 创建地址解析器实例
    myGeo = new BMap.Geocoder();
    loadDefulatMap(loadData);//初始化地图以及加载初始化数据
    // 创建控件
    var myZoomCtrl = new BigZoomControl();
    //// 查询控件类到地图当中
    map.addControl(myZoomCtrl);
    //查询控件的点击事件
    $(".searchMap").click(function () {
      setPlace($("#baiduAddress").val());
    });
    bindEvent();
    function bindEvent() {
      //查询百度地图
      map.addEventListener("click", clickCoordinate); //地图点击事件
    }
    /****************百度地图初始化完成****************/
  }, 1000);
};
