/**
 * guoj
 * 2020.05.27
 * 客户坐标维护
    */
    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 () => {
      let PoSingle_from1, cargoOwnerIds = [];
  eve.on("setAnalysisList_consignor", getAnalysisList_consignor);

  var opts = {
    //terrace显示全部，card分页显示
    skin: "card",
    columns: [
      { id: "cargoOwnerId", name: "id", type: "ro", width: "100", hidden: true },
      { id: "cargoOwnerName", name: "货主名称", type: "ro", width: 150 },
      { id: "address", name: "货主地址", type: "ro", width: 150 },
      { id: "longitude", name: "经度", type: "ro", width: 100 },
      { id: "latitude", name: "纬度", type: "ro", width: 100 },
      { id: "memo", name: "备注", type: "ro", width: 130 }
    ],
    toolbar: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md12", name: "search", label: "查询条件:", placeholder: "请输入货主名称" },
          {
            type: "block", className: "layui-col-md6 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-md6 right",
            list: [
              { type: "button", className: "btn-normal", name: "work_Reset2", offsetLeft: 10, value: "保存" },
              { type: "newcolumn" },
              { type: "button", className: "btn-normal", name: "master_addressAnalysis", value: "地址解析" }
            ]
          }
        ]
      }
    ],

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/cargo_owner/byIds", //数据接口
    type: "post", //数据提交方式，默认为get
    contentType: "application/json",
    params: "{}", //查询提交参数，分页参数默认为pageNum,pageSize
    page: true, //是否启用分页
    multiselect: false,
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };
  //分页参数 pageSize pageNum
  grid = new PlgGrid(opts);
  grid.renderTo("customerCoordinatesGD_div2A");
  //分组拆分条件查询
  // grid.loadData();

  //按钮添加方法
  grid.attachToolBarEvent("onButtonClick", function (name) {
    //查询
    if (name == "querywork") {
      var { search } = grid.getToolBarForm().getFormData();
      grid.setParams(JSON.stringify({ search, cargoOwnerIds }));
      grid.reload();
    }
    //重置
    if (name == "work_Reset") {
      grid.getToolBarForm().clear();
    }
    //保存
    if (name == "work_Reset2") {
      let id = grid.getSelectedRowId();
      if (!id) {
        layer.msg("请选择一行数据");
        return;
      }
      let formData = PoSingle_from1.getFormData();
      formData.longitude = formData.newLongitude;
      formData.latitude = formData.newLatitude;
      formData.address = formData.newAddress;
      let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
      Prolog.ajax({
        url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/cargo_owner/modify", type: "post", contentType: "application/json", data: JSON.stringify(formData),
        success: function (res) {
          PlgDialog.close(pload);
          if (res.success) {
            PlgDialog.msg(res.message);
            return true;
          }
                    return false;
        }, error: function () { PlgDialog.close(pload); return false; }
      });
    }
    if (name === "master_addressAnalysis") {
      let { newLongitude, newLatitude } = PoSingle_from1.getFormData();
      eve.emit("setAnalysis_consignor", { longitude: newLongitude, latitude: newLatitude });
      addressAnalysis_consignor_return();
    }
  });

  let PoSingle_div1 = {
    renderer: "customerCoordinatesGD_div2B",
    items: [
      { type: "settings", PoSingle: "label-left", labelWidth: 90 },
      { type: "input", name: "longitude", label: "当前经度:", width: 175, readonly: true },
      { type: "newcolumn" },
      { type: "input", name: "latitude", label: "当前纬度:", width: 175, readonly: true },
      { type: "newcolumn" },
      { type: "input", name: "address", label: "当前地址:", width: 448, readonly: true },
      { type: "newcolumn" },
      { type: "input", name: "newLongitude", label: "新经度:", width: 175, readonly: true },
      { type: "newcolumn" },
      { type: "input", name: "newLatitude", label: "新纬度:", width: 175, readonly: true },
      { type: "newcolumn" },
      { type: "input", name: "newAddress", label: "新地址:", width: 448, readonly: true },
      { type: "hidden", name: "province", label: "省:" },
      { type: "hidden", name: "city", label: "市:" },
      { type: "hidden", name: "district", label: "区:" },
      { type: "hidden", name: "town", label: "县:" }
    ]
  };
  PoSingle_from1 = new PlgForm(PoSingle_div1);

  // 高德地图
  setTimeout(() => {
    //单击事件
    grid.on("onRowSelect", function (rid) {
      let rd = grid.getRowData(rid);
      PoSingle_from1.setFormData(rd);
      if (rd.longitude && rd.latitude) {
        regeoCode([rd.longitude, rd.latitude]);
      }
    });

    var myMap = new AMap.Map("customerCoordinatesGDmyMap", {
      resizeEnable: true,
      center: [116.397428, 39.90923],
      zoom: 15,
      keyboardEnable: false
    });

    function showInfoClick(e) {
      // myMap.clearMap(); // 清空其他标记
      // var text = "您在 [ " + e.lnglat.getLng() + "," + e.lnglat.getLat() + " ] 的位置单击了地图！";
      regeoCode([e.lnglat.getLng(), e.lnglat.getLat()]);
    }
    myMap.on("click", showInfoClick);

    // 将经纬度转换为地址
    var geocoder = new AMap.Geocoder({
      city: "010", //城市设为北京，默认：“全国”
      radius: 1000 //范围，默认：500
    });
    var marker;
    function regeoCode(lnglat) {
      marker && myMap.remove(marker);
      marker = new AMap.Marker({
        position: new AMap.LngLat(lnglat[0], lnglat[1])
      });
      myMap.add(marker);
      myMap.setCenter(lnglat);

      geocoder.getAddress(lnglat, function (status, result) {
        if (status === "complete" && result.regeocode) {
          var regeocode = result.regeocode;
          PoSingle_from1.setFormData({
            newLongitude: lnglat[0],
            newLatitude: lnglat[1],
            newAddress: regeocode.formattedAddress,
            newProvince: regeocode.addressComponent.province,
            newCity: regeocode.addressComponent.city || regeocode.addressComponent.province,
            newDistrict: regeocode.addressComponent.district,
            newAddresszone4: regeocode.addressComponent.adcode,
            newTown: regeocode.addressComponent.township,
            newStreet: regeocode.addressComponent.streetNumber.street
          });
          let info = [];
          info.push("地址：" + regeocode.formattedAddress);
          var infoWindow = new AMap.InfoWindow({
            content: info.join("<br/>"),
            offset: new AMap.Pixel(0, -25)
          });
          infoWindow.open(myMap, lnglat);
        }
        else {
          layer.msg("根据经纬度查询地址失败");
        }
      });
    }

    // 查询输入框
    AMap.plugin(["AMap.AutoComplete", "AMap.PlaceSearch"], function () {
      var autoOptions = {
        input: "keyword"//使用联想输入的input的id
      };
      var autocomplete = new AMap.AutoComplete(autoOptions);
      var placeSearch = new AMap.PlaceSearch({
        map: myMap
      });
      AMap.Event.addListener(autocomplete, "select", function (e) {
        // 针对选中的poi实现自己的功能
        placeSearch.setCity(e.poi.adcode);
        placeSearch.search(e.poi.name);
      });
      AMap.Event.addListener(placeSearch, "markerClick", function (e) {
        regeoCode([e.data.location.lng, e.data.location.lat]);
      });
    });
  }, 1000);

  function getAnalysisList_consignor(list) {
    cargoOwnerIds = list;
    grid.clearAll();
    grid.getToolBarForm().clear();
    grid.setParams(JSON.stringify({ cargoOwnerIds }));
    grid.reload();
    // grid.loadData({ data: { list } });
    // eve.off("setAnalysisList_consignor", getAnalysisList_consignor);
  }
};
