/**
 * smy
 * 2022.03.02
 * 中转站管理
    */
import { UPCLOUD_RDC_TMS_MAINDATA_SERVICE, UPCLOUD_RDC_TMS_BUSINESS_SERVICE, UPCLOUD_RDC_TMS_INTERFACE_SERVICE } from '@/config/serviceSettings.js';
import { getSelectGJ, querySysPicture, departmentDialog } from '@/utils/prolog.ajax.js';
import { SeniorSearch } from '../auth/seniorSearch.js';

export default () => {
  // 获取扩展字段
  let gird_opts_list = [], form_opts_list = [], date_list = [];
  utilSyncAjaxGJ(UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/extendedField/list", "post", JSON.stringify({ "extendedObjectCode": "10" }), function (res) {
    extendedFieldList({ list: res.data, className: "layui-col-md3" }, function (res) {
      gird_opts_list = res.gird_opts_list;
      form_opts_list = res.form_opts_list;
      date_list = res.date_list;
    });
  }, "application/json");

  var master_grid, edit_form_opts, edit_form, edit_grid_opts, edit_grid;

  // 跳转页面
  var carousel = layui.carousel;
  carousel.render({
    elem: "#trStMan",
    autoplay: false,
    index: 0,
    arrow: "none",
    indicator: "none",
    anim: "fade",
    width: "100%", // 设置容器宽度
    height: "100%"
  });
  // 切换页面
  function changePanel(name) {
    var slideList = ["#trStMan_main", "#trStMan_edit", "#trStMan_view", "#TSM_addressAnalysis"];
    for (var i = 0; i < slideList.length; i++) {
      if (slideList[i] == name) {
        $(name).css("display", "block");
      }
      else {
        $(slideList[i]).css("display", "none");
      }
    }
  }
  // 返回
  $("#trStMan_edit_return").on("click", function () {
    changePanel("#trStMan_main");
  });
  // 返回
  $("#trStMan_view_return").on("click", function () {
    changePanel("#trStMan_main");
  });
  let returnDiv;
  $("#TSM_addressAnalysis_return").on("click", function () {
    changePanel(returnDiv);
  });

  // 获取下拉框
  let dataSelect;

  getSelectGJ([
    { "objectcode": "TRANSFER_STATION_TYPE" },
    { "objectcode": "MAINDATA_STATUS" }
  ], function (data) {
    dataSelect = data.data;
    // dataSelect.TRANSFER_STATION_TYPE.unshift({ "value": "", "text": "" });
  });

  // 查询省
  let provinceEnums = [];
  utilSyncAjaxGJ(UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/zone/get-by-pid", "post", JSON.stringify({ "fatherid": "01" }), function (data) {
    provinceEnums = data.data;
    for (let x in provinceEnums) {
      provinceEnums[x].text = provinceEnums[x].keyvalue;
      provinceEnums[x].value = provinceEnums[x].zoneid;
    }
    provinceEnums.unshift({ "value": "", "text": "" });
  }, "application/json");

  // 仓库table
  var branchTable = {
    // terrace显示全部，card分页显示
    skin: "card",
    // renderer:"grid",
    columns: [
      { id: "id", name: "id", type: "ro", width: "130", hidden: true },
      { id: "code", name: "仓库编码", type: "ro", width: 150 },
      { id: "name", name: "仓库名称", type: "ro", width: 150 },
      { id: "provinceName", name: "省", type: "ro", width: 80 },
      { id: "cityName", name: "市", type: "ro", width: 80 },
      { id: "districtName", name: "区", type: "ro", width: 80 },
      { id: "address", name: "详细地址", type: "ro", width: 150 }
    ],
    multiselect: false,
    toolbar: [
      { type: "settings", position: "label-left", width: 200, labelWidth: 110 },
      {
        type: "block", id: "bk", blockOffset: 0, list: [
          { type: "input", name: "companycode", label: "查询条件:", placeholder: "请输入仓库名称", width: 120 },
          { type: "newcolumn" },
          { type: "button", name: "querycarr", value: "查询" },
          { type: "newcolumn" },
          { type: "button", name: "car_Reset", value: "重置" }
        ]
      }
    ],
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/tmsBaseBranch/queryBranchPopup",
    pagebar: { type: "simple" },
    type: "post", // 数据提交方式，默认为get
    params: JSON.stringify({ companytype: "S" }), // 查询提交参数，分页参数默认为pageNum,pageSize
    contentType: "application/json",
    page: true, // 是否启用分页
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };


  // 主页grid
  let master_grid_opts_columns = [
    { id: "id", name: "id", type: "ro", width: "130", hidden: true },
    { id: "code", name: "中转站编码", type: "ro", width: "130" },
    { id: "name", name: "中转站名称", type: "ro", width: "130" },
    { id: "shortName", name: "中转站简称", type: "ro", width: "130" },
    { id: "departmentName", name: "所属部门", type: "ro", width: "130" },
    { id: "statusName", name: "状态", type: "ro", width: "130" },
    { id: "typeName", name: "类型", type: "ro", width: "130" },
    { id: "branchCode", name: "仓库编码", type: "ro", width: "130" },
    { id: "branchName", name: "仓库名称", type: "ro", width: "130" },
    { id: "contact", name: "联系人", type: "ro", width: "130" },
    { id: "phoneNumber", name: "手机号", type: "ro", width: "130" },
    { id: "landlineNumber", name: "座机号", type: "ro", width: "130" },
    { id: "email", name: "邮箱", type: "ro", width: "130" },
    { id: "postCode", name: "邮编", type: "ro", width: "130" },
    { id: "provinceName", name: "省", type: "ro", width: "130" },
    { id: "cityName", name: "市", type: "ro", width: "130" },
    { id: "districtName", name: "区", type: "ro", width: "130" },
    { id: "address", name: "详细地址", type: "ro", width: "130" },
    { id: "longitude", name: "经度", type: "ro", width: "130" },
    { id: "latitude", name: "纬度", type: "ro", width: "130" },
    { id: "memo", name: "备注", type: "ro", width: "130" }
  ];
  var master_grid_opts = {
    skin: "card",
    columns: master_grid_opts_columns.concat(gird_opts_list, [
      { id: "createperson", name: "创建人", type: "ro", width: "130" },
      { id: "createtime", name: "创建时间", type: "ro", width: "130" },
      { id: "updateperson", name: "修改人", type: "ro", width: "130" },
      { id: "updatetime", name: "修改时间", type: "ro", width: "150" },
      {
        id: "op", name: "操作", type: "button", align: "left", width: 150, fixed: "right", render: function (v, rd) {
          let result = "^trStMan_enable,查看^trStMan_view,修改^trStMan_edit,删除^trStMan_del";
          if (rd.status == "1") {
            result = "停用" + result;
          }
          else {
            result = "启用" + result;
          }
          return result;
        }
      }
    ]),
    toolbar: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md2", name: "code", label: "中转站编码:", placeholder: "请输入中转站编码" },
          { type: "input", className: "layui-col-md2", name: "name", label: "中转站名称:", placeholder: "请输入中转站名称" },

          {
            type: "block", className: "layui-col-md3 form_btn_left",
            list: [
              { type: "button", className: "btn-normal", name: "master_search", value: "查 询" },
              { type: "newcolumn" },
              { type: "button", name: "master_reset", value: "重 置" },
              // { type: "newcolumn" },
              // { type: "button", className: "btn-normal", name: "master_seniorSearch", value: "高级查询" }
            ]
          },
          {
            type: "block", className: "layui-col-md5 right",
            list: [
              { type: "button", className: "btn-normal", name: "master_add", value: "<i class='layui-icon layui-icon-add-1'></i>新 增" },
              { type: "newcolumn" },
              { type: "button", className: "btn-danger", name: "master_del", value: "删除" },
              { type: "newcolumn" },
              { type: "button", className: "btn-danger", name: "master_enable", value: "启用" },
              { type: "newcolumn" },
              { type: "button", className: "btn-danger", name: "master_deactivate", value: "停用" },
              { type: "newcolumn" },

              { type: "newcolumn" },
              { type: "button", className: "btn-normal", name: "master_resolution", value: "地址解析" }
            ]
          }
        ]
      }
    ],
    fixedLast: true, // 开启固定列，固定最后一行，倒数第二列不能隐藏
    multiselect: true, // 是否支持多选
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/transferStation/query", // 数据接口
    type: "post", // 数据提交方式，默认为get
    params: "{}", // 查询提交参数，分页参数默认为pageNum,pageSize
    page: true, // 是否启用分页
    contentType: "application/json",
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  master_grid = new PlgGrid(master_grid_opts);
  master_grid.renderTo("trStMan_master");
  master_grid.loadData();
  // let seniorSearch = new SeniorSearch("ImportQuery", master_grid);
  // seniorSearch.listAll();

  master_grid.attachToolBarEvent("onButtonClick", function (name) {
    switch (name) {
      case "master_search":
        var request = master_grid.getToolBarForm().getFormData();
        master_grid.setParams(JSON.stringify(request));
        master_grid.reload();
        break;
      case "master_reset":
        master_grid.getToolBarForm().clear();
        break;
      case "master_seniorSearch":
        seniorSearch.dialog();
        break;
      case "master_add":
        changePanel("#trStMan_edit");
        $("#trStMan_edit_form").html("");
        editFormCreated();
        $("#trStMan_edit_title").html("新增");
        break;
      case "master_del":
        var ids0 = master_grid.getCheckedIds();
        if (!ids0) {
          layer.msg("请选择数据");
          return false;
        }
        var idsArr0 = ids0.split(",");
        var checkedIds0 = [];
        idsArr0.forEach(v => {
          checkedIds0.push(
            { id: v }
          );
        });
        templet_delete(checkedIds0);
        break;

      case "master_enable":
        var ids = master_grid.getCheckedIds();
        if (!ids) {
          layer.msg("请选择数据");
          return false;
        }
        var idsArr = ids.split(",");
        var checkedIds = [];
        idsArr.forEach(v => {
          let rd = master_grid.getRowData(v);
          checkedIds.push(
            { id: v, status: rd.status }
          );
        });
        layer.open({
          title: "启用",
          content: "是否启用？",
          btn: ["确认", "取消"],
          yes: function () {
            enable(checkedIds, "/transferStation/enable");
          }
        });
        break;

      // 停用
      case "master_deactivate":
        var ids2 = master_grid.getCheckedIds();
        if (!ids2) {
          layer.msg("请选择数据");
          return false;
        }
        var idsArr2 = ids2.split(",");
        var checkedIds2 = [];
        idsArr2.forEach(v => {
          let rd = master_grid.getRowData(v);
          checkedIds2.push(
            { id: v, status: rd.status }
          );
        });

        layer.open({
          title: "停用",
          content: "是否停用？",
          btn: ["确认", "取消"],
          yes: function () {
            enable(checkedIds2, "/transferStation/disable");
          }
        });
        break;
      case "master_resolution":
        var ids3 = master_grid.getCheckedIds();
        if (!ids3) {
          layer.msg("请选择数据");
          return false;
        }
        var list = ids3.split(",");
        returnDiv = "#trStMan_main";
        addressAnalysis(returnDiv, list);
        break;
    }
  });

  // 启用停用公用方法
  function enable(par, url) {
    let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + url,
      type: "post",
      contentType: "application/json",
      data: JSON.stringify(par),
      success: function (data) {
        PlgDialog.close(pload);
        if (data.success) {
          layer.closeAll();
          PlgDialog.msg(data.message);
          master_grid.reload();
          return true;
        }
        setTimeout(() => { PlgDialog.alert(data.message || "接口调用失败"); }, 300);
        return false;

      }, error: function () { PlgDialog.close(pload); return false; }
    });
  }
  // 启用/停用单行点击
  window.trStMan_enable = function (rid, rdata) {
    let text = rdata.status === 1 ? "停用" : "启用";
    let url = rdata.status === 1 ? '/transferStation/disable' : '/transferStation/enable'
    layer.open({
      title: text,
      content: "是否" + text + "？",
      btn: ["确认", "取消"],
      yes: function () {
        enable([
          {
            id: rid, status: rdata.status
          }
        ], url);
      }
    });


  };


  // 单个删除
  window.trStMan_del = function (rid) {
    let arr = [
      {
        id: rid
      }
    ];
    templet_delete(arr);
  };
  // 删除方法
  function templet_delete(ids) {
    layer.open({
      title: "删除",
      content: "是否删除？",
      btn: ["确认", "取消"],
      yes: function () {
        let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
        Prolog.ajax({
          url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/transferStation/delete",
          type: "post",
          contentType: "application/json",
          data: JSON.stringify(ids),
          success: function (data) {
            PlgDialog.close(pload);
            if (data.success) {
              layer.closeAll();
              PlgDialog.msg(data.message);
              master_grid.reload();
              return true;
            }
            return false;

          }, error: function () { PlgDialog.close(pload); return false; }
        });
      }
    });
  }

  // 修改
  window.trStMan_edit = function (rid, rdata) {
    changePanel("#trStMan_edit");
    $("#trStMan_edit_form").html("");
    editFormCreated(rdata);
    $("#trStMan_edit_title").html("修改");
  };

  // 查看
  window.trStMan_view = function (rid, rdata) {
    changePanel("#trStMan_view");

    let arr = [], view_list = gird_opts_list.map(item => {
      return { label: item.name, value: rdata[item.id] };
    });
    if (rdata.type == "1") {
      arr = [
        [
          { label: "中转站编码", value: rdata.code },
          { label: "中转站名称", value: rdata.name },
          { label: "中转站简称", value: rdata.shortName },
          { label: "所属组织", value: rdata.organizationName },
          { label: "所属部门", value: rdata.departmentName },
          { label: "状态", value: rdata.statusName },
          { label: "类型", value: rdata.typeName },
          { label: "仓库编码", value: rdata.branchCode },
          { label: "仓库名称", value: rdata.branchName },
          { label: "联系人", value: rdata.contact },
          { label: "手机号", value: rdata.phoneNumber },
          { label: "座机号", value: rdata.tel },
          { label: "邮箱", value: rdata.email },
          { label: "邮编", value: rdata.postCode },
          { label: "省", value: rdata.provinceName },
          { label: "市", value: rdata.cityName },
          { label: "区/县", value: rdata.districtName },
          { label: "详细地址", value: rdata.address },
          { label: "经度", value: rdata.longitude },
          { label: "纬度", value: rdata.latitude },
          { label: "备注", value: rdata.memo }
        ]
      ].concat([view_list]);
    }
    else {
      arr = [
        [
          { label: "中转站编码", value: rdata.code },
          { label: "中转站名称", value: rdata.name },
          { label: "中转站简称", value: rdata.shortName },
          { label: "状态", value: rdata.statusName },
          { label: "类型", value: rdata.typeName },
          { label: "联系人", value: rdata.contact },
          { label: "手机号", value: rdata.phoneNumber },
          { label: "座机号", value: rdata.landlineNumber },
          { label: "邮箱", value: rdata.email },
          { label: "邮编", value: rdata.postCode },
          { label: "省", value: rdata.provinceName },
          { label: "市", value: rdata.cityName },
          { label: "区/县", value: rdata.districtName },
          { label: "详细地址", value: rdata.address },
          { label: "经度", value: rdata.longitude },
          { label: "纬度", value: rdata.latitude },
          { label: "备注", value: rdata.memo }
        ]
      ].concat([view_list]);
    }


    new PlgPanel({
      renderer: "trStMan_view_form",
      skin: 2,
      header: {
        isShow: true,
        title: "基本信息"
      },
      defaultBody: {
        layoutCol: 4,
        valueBj: true,
        cols: arr
      }
    });
  };

  // 详情form
  edit_form_opts = {
    renderer: "trStMan_edit_form",
    items: [
      { type: "settings", labelAlign: "left", labelWidth: 90 },
      {
        type: "row",
        list: [
          { type: "hidden", className: "layui-col-md3", name: "id", label: "中转站ID:" },
          { type: "input", className: "layui-col-md3", name: "code", label: "中转站编码:", required: true },
          { type: "input", className: "layui-col-md3", name: "name", label: "中转站名称:", required: true },
          { type: "input", className: "layui-col-md3", name: "shortName", label: "中转站简称:", required: true },
          { type: "input", className: "layui-col-md3", name: "departmentName", label: "部门:", placeholder: "请选择部门", readonly: true, required: true },
          { type: "hidden", name: "departmentId" },
          { type: "hidden", name: "departmentCode" },
        ]
      },
      {
        type: "row",
        list: [
          { type: "combo", className: "layui-col-md3", name: "status", label: "状态:", options: dataSelect.MAINDATA_STATUS, readonly: true, required: true },
          { type: "combo", className: "layui-col-md3", name: "type", label: "类型:", options: dataSelect.TRANSFER_STATION_TYPE, readonly: true },
          {
            className: "layui-col-md3",
            type: "selectTable",
            placeholder: "请选择仓库",
            readonly: false,
            table: branchTable,
            tableWidth: 500,
            tableHeight: 400,
            fieldText: "code",
            fieldValue: "id",
            name: "branchList",
            label: "仓库编码:",
            listener: function (TSMGrid) {
              setMethod(TSMGrid, branchTable, function (data) {
                var datad = {};
                datad.branchId = data.id;
                datad.branchCode = data.code;
                datad.branchName = data.name;
                datad.contact = data.contact;
                datad.province = data.province;
                datad.provinceName = data.provinceName;
                datad.city = data.city;
                datad.cityName = data.cityName;
                datad.district = data.district;
                datad.districtName = data.districtName;
                datad.address = data.address;

                data.city && getByPid(data.province, "city", data.city);
                data.district && getByPid(data.city, "district", data.district);

                edit_form.setFormData(datad);
              });
            }
          },
          { type: "hidden", className: "layui-col-md3", name: "branchCode", label: "仓库编码:" },
          { type: "input", className: "layui-col-md3", name: "branchName", label: "仓库名称:" },

        ]
      },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md3", name: "contact", label: "联系人:" },
          { type: "input", className: "layui-col-md3", name: "phoneNumber", label: "手机号:" },
          { type: "input", className: "layui-col-md3", name: "landlineNumber", label: "座机号:" },
          { type: "input", className: "layui-col-md3", name: "email", label: "邮箱:" },
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md3", name: "postCode", label: "邮编:" },
          { type: "combo", readonly: true, name: "province", label: "省:", className: "layui-col-md3", options: provinceEnums },
          { type: "combo", readonly: true, name: "city", label: "市:", className: "layui-col-md3" },
          { type: "combo", readonly: true, name: "district", label: "区/县:", className: "layui-col-md3" },
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md6", name: "address", label: "详细地址:" },
          { type: "input", className: "layui-col-md6", name: "memo", label: "备注:" }
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md3", name: "longitude", label: "经度:" },
          { type: "input", className: "layui-col-md3", name: "latitude", label: "纬度:" },
          {
            type: "block", className: "layui-col-md3 form_btn_left",
            list: [
              { type: "button", className: "btn-normal", name: "master_resolution", value: "地址解析" }
            ]
          },
        ]
      },
      {
        type: "row",
        list: form_opts_list
      }
    ]
  };
  // 创建form
  function editFormCreated(rdata) {
    edit_form = new PlgForm(edit_form_opts);

    if (rdata) {

      rdata.city && getByPid(rdata.province, "city", rdata.city);
      rdata.district && getByPid(rdata.city, "district", rdata.district);

      // 数字转字符串回显status
      rdata.status = rdata.status + "";
      edit_form.setFormData(rdata);


      if (rdata.type == "2") {
        edit_form.hideItem("branchList");
        edit_form.hideItem("branchName");
      }
      else {
        edit_form.setText("branchList", rdata.branchName);

      }

      edit_form.disableItem("code");
      edit_form.disableItem("name");
    }
    else {
      edit_form.enableItem("");
      edit_form.getCombo("status").setComboValue("1");
    }

    edit_form.attachComboEvent("type", "onChange", function (id) {
      if (id == "1") {
        edit_form.showItem("branchList");
        edit_form.showItem("branchName");
      }
      else {
        edit_form.hideItem("branchList");
        edit_form.hideItem("branchName");
        edit_form.setFormData({
          branchCode: "",
          branchName: ""
        });

      }
    });

    edit_form.attachComboEvent("province", "onChange", function (id) {
      edit_form.getCombo("city").clearAll();
      edit_form.getCombo("city").setComboText("");
      if (id) {
        edit_form.loadComboData("city", { url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/zone/get-by-pid", type: "post", contentType: "application/json", data: JSON.stringify({ "fatherid": id }), valueField: "zoneid", textField: "keyvalue" });
      }
    });
    edit_form.attachComboEvent("city", "onChange", function (id) {
      edit_form.getCombo("district").clearAll();
      edit_form.getCombo("district").setComboText("");
      if (id) {
        edit_form.loadComboData("district", { url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/zone/get-by-pid", type: "post", contentType: "application/json", data: JSON.stringify({ "fatherid": id }), valueField: "zoneid", textField: "keyvalue" });
      }
    });

    edit_form.attachEvent("onButtonClick", function () {
      let { address, longitude, latitude } = edit_form.getFormData();
      returnDiv = "#trStMan_edit";
      addressAnalysis(returnDiv, { address, longitude, latitude });
    });

    // 部门弹窗
    departmentDialog("#trStMan_edit_form", edit_form)
  }

  // 省市区联动
  function getByPid(fatherid, comboName, value) {
    Prolog.ajax({
      url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/zone/get-by-pid",
      type: "post",
      contentType: "application/json",
      data: JSON.stringify({ fatherid }),
      success: function (res) {
        if (res.success) {
          let list = res.data.map(item => {
            return {
              value: item.zoneid,
              text: item.keyvalue
            };
          });
          // 给combo赋下拉框数据
          edit_form.getCombo(comboName).addOption(list);
          // 给combo赋值
          const nextData = {};
          nextData[comboName] = value;
          edit_form.setFormData(nextData);
          return true;
        }
        return false;
      },
      error: function () { PlgDialog.close(pload); return false; }
    });
  }

  // 保存
  $("#trStMan_edit_save").on("click", function () {
    setTimeout(() => {
      // console.log(edit_form.getFormData(), 333);
      // return;
      let feik = edit_form.validate();
      if (!feik) return;
      let formData = edit_form.getFormData();
      date_list.forEach(item => {
        formData[item] = FormatDateTime(formData[item]);
      });
      delete formData.branchList;

      formData.provinceName = edit_form.getCombo("province").getComboText();
      formData.cityName = edit_form.getCombo("city").getComboText();
      formData.districtName = edit_form.getCombo("district").getComboText();

      formData.organizationId = "";
      formData.organizationCode = "";
      formData.organizationName = "";

      let url = $("#trStMan_edit_title").html() === "新增" ? UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/transferStation/save" : UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/transferStation/update";
      let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
      Prolog.ajax({
        url, type: "post", contentType: "application/json", data: JSON.stringify(formData),
        success: function (res) {
          PlgDialog.close(pload);
          if (res.success) {
            PlgDialog.msg(res.message);
            changePanel("#trStMan_main");
            master_grid.reload();
            return true;
          }
          return false;
        }, error: function () { PlgDialog.close(pload); return false; }
      });
    }, 200);
  });

  let PoSingle_from1, ids = [];

  var opts = {
    //terrace显示全部，card分页显示
    skin: "card",
    columns: [
      { id: "id", name: "id", type: "ro", width: "100", hidden: true },
      { id: "name", 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 }
    ],
    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: "保存" }
            ]
          }
        ]
      }
    ],

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

  //按钮添加方法
  grid.attachToolBarEvent("onButtonClick", function (name) {
    //查询
    if (name == "querywork") {
      var { search } = grid.getToolBarForm().getFormData();
      grid.setParams(JSON.stringify({ search, ids }));
      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;
      formData.id = id;
      let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
      Prolog.ajax({
        url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/transferStation/parsing", type: "post", contentType: "application/json", data: JSON.stringify(formData),
        success: function (res) {
          PlgDialog.close(pload);
          if (res.success) {
            PlgDialog.msg(res.message);
            grid.reload();
            PoSingle_from1.clear();
            return true;
          }
          return false;
        }, error: function () { PlgDialog.close(pload); return false; }
      });
    }
  });

  let PoSingle_div1 = {
    renderer: "addressAnalysisTSM_div2B",
    items: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          { type: "input", name: "longitude", label: "当前经度:", className: "layui-col-md5", readonly: true },
          { type: "input", name: "latitude", label: "当前纬度:", className: "layui-col-md5", readonly: true }
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", name: "address", label: "当前地址:", className: "layui-col-md10", readonly: true }
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", name: "newLongitude", label: "新经度:", className: "layui-col-md5", readonly: true },
          { type: "input", name: "newLatitude", label: "新纬度:", className: "layui-col-md5", readonly: true }
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", name: "newAddress", label: "新地址:", className: "layui-col-md10", readonly: true },
          { type: "hidden", name: "province", label: "省:" },
          { type: "hidden", name: "city", label: "市:" },
          { type: "hidden", name: "district", label: "区:" },
          { type: "hidden", name: "town", label: "县:" }
        ]
      },
      {
        type: "block", className: "layui-col-md12 form_btn_left",
        list: [
          { type: "button", className: "btn-normal", name: "master_addressAnalysis", value: "地址解析" }
        ]
      }
    ]
  };
  PoSingle_from1 = new PlgForm(PoSingle_div1);
  PoSingle_from1.attachEvent("onButtonClick", function (name) {
    if (name === "master_addressAnalysis") {
      changePanel("#trStMan_edit");
      let { newLongitude, newLatitude } = PoSingle_from1.getFormData();
      edit_form.setFormData({ longitude: newLongitude, latitude: newLatitude });
    }
  });

  // 单击事件
  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("addressAnalysisTSMmyMap", {
    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;
  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;
        let newAddress = regeocode.formattedAddress.split(regeocode.addressComponent.district)[1];
        PoSingle_from1.setFormData({
          newLongitude: lnglat[0],
          newLatitude: lnglat[1],
          newAddress: newAddress,
          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: "TSM_addressAnalysis_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]);
    });

    geocoder = new AMap.Geocoder({
      city: "010", //城市设为北京，默认：“全国”
      radius: 1000 //范围，默认：500
    });
  });

  function addressAnalysis(returnDiv, data) {
    changePanel("#TSM_addressAnalysis");
    PoSingle_from1.clear();

    if (returnDiv === "#trStMan_main") {
      ids = data;
      $("#addressAnalysisTSM_div2A").show();
      PoSingle_from1.hideItem("master_addressAnalysis");
      grid.clearAll();
      grid.getToolBarForm().clear();
      grid.setParams(JSON.stringify({ ids }));
      grid.reload();
    }
    else {
      $("#addressAnalysisTSM_div2A").hide();
      PoSingle_from1.showItem("master_addressAnalysis");
      let { address, longitude, latitude } = data;
      PoSingle_from1.setFormData({ address, longitude, latitude });
      if (longitude && latitude) {
        regeoCode([longitude, latitude]);
      }
      else if (address) {
        PoSingle_from1.setFormData({ address, longitude, latitude });
        $("#addressAnalysisTSM_tip input").val(address);
        setTimeout(() => {
          var placeSearch = new AMap.PlaceSearch({
            map: myMap
          });
          placeSearch.search(address);
          AMap.Event.addListener(placeSearch, "markerClick", function (e) {
            regeoCode([e.data.location.lng, e.data.location.lat]);
          });
        }, 100);
      }
    }
  }
};