/**
 * zzx
 * 2022.03.07
 * 承运商管理
    */
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';

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

  let master_grid, edit_form, master_form_opts, editType;

  // 跳转页面
  let carousel = layui.carousel;
  carousel.render({
    elem: "#carriers",
    autoplay: false,
    index: 0,
    arrow: "none",
    indicator: "none",
    anim: "fade",
    width: "100%", //设置容器宽度
    height: "100%"
  });
  let viewList = ["#carriers_edit", "#carriers_main", "#carriers_view", "#carriers_addressAnalysis"];
  let returnDiv;
  function changePanel(name) {
    for (let i = 0; i < viewList.length; i++) {
      if (name == viewList[i]) {
        $(name).css("display", "block");
      }
      else {
        $(viewList[i]).css("display", "none");
      }
    }
  }
  // 返回
  $(".carriers_return").on("click", function () {
    changePanel("#carriers_main");
  });
  $("#carriers_addressAnalysis_return").on("click", function () {
    changePanel(returnDiv);
  });

  // 获取下拉框
  let dataSelect;
  getSelectGJ([
    { "objectcode": "MAINDATA_STATUS" },
    { "objectcode": "COOPERATIVE_NATURE" },
    { "objectcode": "BANK" },
    { "objectcode": "ENABLE_STATUS" }
  ], function (data) {
    data.data.COOPERATIVE_NATURE.unshift({ "text": "", "value": "" });
    data.data.BANK.unshift({ "text": "", "value": "" });
    dataSelect = data.data;
  });
  // 查询省
  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
  let master_grid_opts_columns = [
    { id: "id", name: "id", type: "ro", width: 120, hidden: true },
    { id: "code", name: "承运商编码", type: "ro", width: 120 },
    { id: "name", name: "承运商名称", type: "ro", width: 120 },
    { id: "shortName", name: "承运商简称", type: "ro", width: 120 },
    { id: "departmentName", name: "所属部门", type: "ro", width: 120 },
    { id: "cooperativeNatureName", name: "合作性质", type: "ro", width: 120 },
    { id: "statusName", name: "状态", type: "ro", width: 120 },
    { id: "taxRegisterNumber", name: "税务登记号", type: "ro", width: 120 },
    { id: "businessLicenseNumber", name: "营业执照号", type: "ro", width: 120 },
    { id: "roadPermit", name: "道路许可证", type: "ro", width: 120 },
    { id: "memo", name: "备注", type: "ro", width: 120 },
    { id: "contact", name: "联系人", type: "ro", width: 120 },
    { id: "phoneNumber", name: "手机号", type: "ro", width: 120 },
    { id: "landlineNumber", name: "座机号", type: "ro", width: 120 },
    { id: "email", name: "邮箱", type: "ro", width: 120 },
    { id: "postCode", name: "邮编", type: "ro", width: 120 },
    { id: "provinceName", name: "省", type: "ro", width: 120 },
    { id: "cityName", name: "市", type: "ro", width: 120 },
    { id: "districtName", name: "区", type: "ro", width: 120 },
    { id: "address", name: "详细地址", type: "ro", width: 120 },
    { id: "longitude", name: "经度", type: "ro", width: 120 },
    { id: "latitude", name: "纬度", type: "ro", width: 120 },
    { id: "legalman", name: "法人代表", type: "ro", width: 120 },
    { id: "invoice", name: "发票抬头", type: "ro", width: 120 },
    { id: "invoiceTaxNumber", name: "税号", type: "ro", width: 120 },
    { id: "registeredCapital", name: "注册资金", type: "ro", width: 120 },
    { id: "bank", name: "开户行", type: "ro", width: 120, render: function (v) { return getSelectValue(dataSelect.BANK, v); } },
    { id: "bankAccount", name: "银行账号", type: "ro", width: 120 },
    { id: "established", name: "成立时间", type: "ro", width: 120 },
    { id: "registeredAddress", name: "注册地址", type: "ro", width: 120 },
    { id: "pickUpSign", name: "提货签到", type: "ro", width: 120, render: function (v) { return getSelectValue(dataSelect.ENABLE_STATUS, v); } },
    { id: "pickUpPicture", name: "提货图片", type: "ro", width: 120, render: function (v) { return getSelectValue(dataSelect.ENABLE_STATUS, v); } },
    { id: "defaultPickUpRail", name: "默认提货围栏", type: "ro", width: 120, render: function (v) { return v ? v + "KM" : ""; } },
    { id: "deliverySign", name: "送达签到", type: "ro", width: 120, render: function (v) { return getSelectValue(dataSelect.ENABLE_STATUS, v); } },
    { id: "deliveryPicture", name: "送达图片", type: "ro", width: 120, render: function (v) { return getSelectValue(dataSelect.ENABLE_STATUS, v); } },
    { id: "defaultDeliveryRail", name: "默认送达围栏", type: "ro", width: 120, render: function (v) { return v ? v + "KM" : ""; } },
    { id: "returnOrderFlag", name: "是否要求回单", type: "ro", width: 120, render: function (v) { return getSelectValue(dataSelect.ENABLE_STATUS, v); } },
    { id: "returnOrderDeadline", name: "回单期限", type: "ro", width: 120, render: function (v) { return v ? v + "天" : ""; } }
  ];
  let master_grid_opts = {
    skin: "card",
    columns: master_grid_opts_columns.concat(gird_opts_list, [
      { id: "createperson", name: "创建人", type: "ro", width: 120 },
      { id: "createtime", name: "创建时间", type: "ro", width: 120 },
      { id: "updateperson", name: "修改人", type: "ro", width: 120 },
      { id: "updatetime", name: "修改时间", type: "ro", width: 200 },
      {
        id: "op", name: "操作", type: "button", align: "center", fixed: "right", width: 200, render: function (v, rd) {
          let result = "查看^carriers_view";
          if (rd.status == "10") {
            result += ",停用^customer_enOrDis";
          }
          else if (rd.status == "0") {
            result += ",启用^customer_enOrDis";
          }
          if (rd.status != "5") {
            result += ",复制^carriers_copy,修改^carriers_edit,删除^carriers_del";
          }
          return result;
        }
      }
    ]),
    toolbar: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md3", name: "carrierCode", label: "承运商编码:" },
          { type: "input", className: "layui-col-md3", name: "carrierName", label: "承运商名称:" },
          {
            type: "block", className: "layui-col-md6 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_add", value: "<i class='layui-icon layui-icon-add-1'></i>新 增" },
              { type: "newcolumn" },
              { type: "button", className: "btn-normal", name: "master_en", value: "启用" },
              { type: "newcolumn" },
              { type: "button", className: "btn-danger", name: "master_dis", value: "停用" },
              { type: "newcolumn" },
              { type: "button", className: "btn-danger", name: "master_del", value: "删除" },
              { type: "newcolumn" },
              { type: "button", className: "btn-normal", name: "master_addressAnalysis", value: "地址解析" },
              { type: "newcolumn" },
              { type: "button", className: "btn-normal", name: "master_import", value: "导入" }
            ]
          }
        ]
      }
    ],
    multiselect: true,
    fixedLast: true,

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/carrier/page",
    type: "post",
    contentType: "application/json",
    params: "{}",
    page: true,
    totalCount: "totalCount"
  };
  master_grid = new PlgGrid(master_grid_opts);
  master_grid.renderTo("carriers_master");
  master_grid.loadData();

  master_grid.attachToolBarEvent("onButtonClick", function (name) {
    if (name === "master_search") {
      let request = master_grid.getToolBarForm().getFormData();
      master_grid.setParams(JSON.stringify(request));
      master_grid.reload();
    }
    else if (name === "master_reset") {
      master_grid.getToolBarForm().clear();
    }
    else if (name === "master_add") {
      changePanel("#carriers_edit");
      $("#carriers_edit_title").html("新增");
      editType = "add";
      editFormInit();
    }
    else if (name === "master_addressAnalysis") {
      let ids = master_grid.getCheckedIds();
      if (!ids) {
        layer.msg("请选择数据");
        return false;
      }
      let list = ids.split(",");
      returnDiv = "#carriers_main";
      addressAnalysis(returnDiv, list);
    }
    else if (name === "master_en" || name === "master_dis") {
      let ids = master_grid.getCheckedIds();
      let Interface = name === "master_en" ? "enable" : "disable";
      if (!ids) {
        layer.msg("请选择数据");
        return false;
      }
      let list = ids.split(",");
      let statusList = list.map(item => Number(master_grid.getRowData(item).status))
      if (statusList.includes(5)) {
        layer.msg("审核中的数据不能编辑")
        return false
      }
      deleteCarriers(list, Interface);
    }
    else if (name === "master_del") {
      let ids = master_grid.getCheckedIds();
      if (!ids) {
        layer.msg("请选择数据");
        return false;
      }
      let list = ids.split(",").map(item => {
        return { id: item };
      });
      let statusList = list.map(item => Number(master_grid.getRowData(item.id).status))
      if (statusList.includes(5)) {
        layer.msg("审核中的数据不能编辑")
        return false
      }
      deleteCarriers(list, "delete");
    }
    else if (name === "master_import") {
      importDialog({ id: "import", importUrl: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/carrier/import", downloadUrl: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/carrier/download_template", downloadName: "承运商管理模板" });
    }
  });

  // 停用/启用
  window.customer_enOrDis = function (rid, rdata) {
    let Interface = rdata.status == "10" ? "disable" : "enable";
    deleteCarriers([rid], Interface);
  };
  // 删除
  window.carriers_del = function (rid) {
    deleteCarriers([{ id: rid }], "delete");
  };
  // 删除方法
  function deleteCarriers(idList, Interface) {
    let text = Interface === "enable" ? "启用" : Interface === "disable" ? "停用" : "删除";
    layer.open({
      title: text,
      content: "是否" + text + "？",
      btn: ["确认", "取消"],
      yes: function () {
        let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
        Prolog.ajax({
          url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/carrier/" + Interface, type: "post", contentType: "application/json", data: JSON.stringify(idList),
          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.carriers_copy = function (rid, rdata) {
    changePanel("#carriers_edit");
    $("#carriers_edit_title").html("复制");
    editType = "copy";
    editFormInit(rdata);
  };
  // 修改
  window.carriers_edit = function (rid, rdata) {
    changePanel("#carriers_edit");
    $("#carriers_edit_title").html("修改");
    editType = "modify";
    editFormInit(rdata);
  };
  // 详情
  window.carriers_view = function (rid, rdata) {
    changePanel("#carriers_view");
    $("#carriers_view_form_1").html("");
    $("#carriers_view_form_2").html("");
    $("#carriers_view_form_3").html("");
    $("#carriers_view_form_4").html("");

    let carriers_view_form_1_cols = [
      [
        { label: "承运商编码", value: rdata.code },
        { label: "承运商名称", value: rdata.name },
        { label: "承运商简称", value: rdata.shortName },
        { label: "所属部门", value: rdata.departmentName },
        { label: "合作性质", value: rdata.cooperativeNatureName },
        { label: "状态", value: rdata.statusName },
        { label: "税务登记号", value: rdata.taxRegisterNumber },
        { label: "营业执照号", value: rdata.businessLicenseNumber },
        { label: "道路许可证", value: rdata.roadPermit },
        { label: "备注", value: rdata.memo }
      ]
    ];
    let list = [];
    gird_opts_list.forEach(item => list.push({ label: item.name, value: rdata[item.id] }));
    carriers_view_form_1_cols.push(list);

    new PlgPanel({
      renderer: "carriers_view_form_1",
      skin: 2,
      header: {
        isShow: true,
        title: "基本信息"
      },
      defaultBody: {
        layoutCol: 3,
        valueBj: true,
        cols: carriers_view_form_1_cols
      }
    });
    new PlgPanel({
      renderer: "carriers_view_form_2",
      skin: 2,
      header: {
        isShow: true,
        title: "联系信息"
      },
      defaultBody: {
        layoutCol: 3,
        valueBj: true,
        cols: [
          [
            { 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 }
          ]
        ]
      }
    });
    new PlgPanel({
      renderer: "carriers_view_form_3",
      skin: 2,
      header: {
        isShow: true,
        title: "开户信息"
      },
      defaultBody: {
        layoutCol: 3,
        valueBj: true,
        cols: [
          [
            { label: "法人代表", value: rdata.legalman },
            { label: "发票抬头", value: rdata.invoice },
            { label: "税号", value: rdata.invoiceTaxNumber },
            { label: "注册资金", value: rdata.registeredCapital }
          ],
          [
            { label: "开户行", value: getSelectValue(dataSelect.BANK, rdata.bank) },
            { label: "银行帐号", value: rdata.bankAccount },
            { label: "成立时间", value: rdata.established },
            { label: "注册地址", value: rdata.registeredAddress }
          ]
        ]
      }
    });
    new PlgPanel({
      renderer: "carriers_view_form_4",
      skin: 2,
      header: {
        isShow: true,
        title: "业务信息"
      },
      defaultBody: {
        layoutCol: 3,
        valueBj: true,
        cols: [
          [
            { label: "提货签到", value: getSelectValue(dataSelect.ENABLE_STATUS, rdata.pickUpSign) },
            { label: "自动签到", value: getSelectValue(dataSelect.ENABLE_STATUS, rdata.autoPickUpSign) },
            { label: "提货图片", value: getSelectValue(dataSelect.ENABLE_STATUS, rdata.pickUpPicture) },
            { label: "默认提货围栏", value: rdata.defaultPickUpRail + "KM" }
          ],
          [
            { label: "送达签到", value: getSelectValue(dataSelect.ENABLE_STATUS, rdata.deliverySign) },
            { label: "自动签到", value: getSelectValue(dataSelect.ENABLE_STATUS, rdata.autoDeliverySign) },
            { label: "送货图片", value: getSelectValue(dataSelect.ENABLE_STATUS, rdata.deliveryPicture) },
            { label: "默认送货围栏", value: rdata.defaultDeliveryRail + "KM" }
          ],
          [
            { label: "是否要求回单", value: getSelectValue(dataSelect.ENABLE_STATUS, rdata.returnOrderFlag) },
            { label: "回单期限", value: rdata.returnOrderDeadline + "天" }
          ]
        ]
      }
    });
  };

  // 承运商编辑form
  master_form_opts = {
    renderer: "carriers_edit_form",
    items: [
      {
        type: "fieldset", name: "basic", label: "基本信息", list: [
          { type: "settings", labelAlign: "right", labelWidth: 90 },
          {
            type: "row",
            list: [
              { 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: "承运商简称:" },
              { 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: "cooperativeNature", label: "合作性质:", options: dataSelect.COOPERATIVE_NATURE, readonly: true },
              { type: "input", className: "layui-col-md3", name: "taxRegisterNumber", label: "税务登记号:" },
              { type: "input", className: "layui-col-md3", name: "businessLicenseNumber", label: "营业执照号:" },
              { type: "input", className: "layui-col-md3", name: "roadPermit", label: "道路许可证:" }
            ]
          },
          {
            type: "row",
            list: [
              { type: "input", className: "layui-col-md6", name: "memo", label: "备注:" }
            ]
          },
          {
            type: "row",
            list: form_opts_list
          }
        ]
      },
      {
        type: "fieldset", name: "contactInfo", label: "联系信息", list: [
          { type: "settings", labelAlign: "right", labelWidth: 90 },
          {
            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", className: "layui-col-md3", name: "province", label: "省:", options: provinceEnums, readonly: true },
              { type: "combo", className: "layui-col-md3", name: "city", label: "市:", readonly: true },
              { type: "combo", className: "layui-col-md3", name: "district", label: "区:", readonly: true }
            ]
          },
          {
            type: "row",
            list: [
              { type: "input", className: "layui-col-md6", name: "address", label: "详细地址:" }
            ]
          },
          {
            type: "row",
            list: [
              { type: "input", className: "layui-col-md3", name: "longitude", label: "经度:", readonly: true },
              { type: "input", className: "layui-col-md3", name: "latitude", label: "纬度:", readonly: true },
              {
                type: "block", className: "layui-col-md3 form_btn_left",
                list: [
                  { type: "button", className: "btn-normal", name: "addressAnalysis", value: "地址解析" }
                ]
              }
            ]
          }
        ]
      },
      {
        type: "fieldset", name: "bankInfo", label: "开户信息", list: [
          { type: "settings", labelAlign: "right", labelWidth: 90 },
          {
            type: "row",
            list: [
              { type: "input", className: "layui-col-md3", name: "legalman", label: "法人代表:" },
              { type: "input", className: "layui-col-md3", name: "invoice", label: "发票抬头:" },
              { type: "input", className: "layui-col-md3", name: "invoiceTaxNumber", label: "税号:" },
              { type: "input", className: "layui-col-md3", name: "registeredCapital", label: "注册资金:" }

            ]
          },
          {
            type: "row",
            list: [
              { type: "combo", className: "layui-col-md3", name: "bank", label: "开户行:", options: dataSelect.BANK, readonly: true },
              { type: "input", className: "layui-col-md3", name: "bankAccount", label: "银行帐号:" },
              { type: "calendar", className: "layui-col-md3", name: "established", label: "成立时间:", readonly: true },
              { type: "input", className: "layui-col-md3", name: "registeredAddress", label: "注册地址:" }
            ]
          }
        ]
      },
      {
        type: "fieldset", name: "business", label: "业务信息", list: [
          { type: "settings", labelAlign: "right", labelWidth: 90 },
          {
            type: "row",
            list: [
              {
                type: "row", className: "layui-col-md6 form_btn_left",
                list: [
                  { type: "checkbox", className: "layui-col-md4", name: "pickUpSign", label: "提货签到:" },
                  { type: "checkbox", className: "layui-col-md4", name: "autoPickUpSign", label: "自动签到:" },
                  { type: "checkbox", className: "layui-col-md4", name: "pickUpPicture", label: "提货图片:" }
                ]
              },
              { type: "input", className: "layui-col-md3", name: "defaultPickUpRail", label: "默认提货围栏:" },
              { type: "label", className: "layui-col-md1", label: "KM" }
            ]
          },
          {
            type: "row",
            list: [
              {
                type: "row", className: "layui-col-md6 form_btn_left",
                list: [
                  { type: "checkbox", className: "layui-col-md4", name: "deliverySign", label: "送达签到:" },
                  { type: "checkbox", className: "layui-col-md4", name: "autoDeliverySign", label: "自动签到:" },
                  { type: "checkbox", className: "layui-col-md4", name: "deliveryPicture", label: "送货图片:" }
                ]
              },
              { type: "input", className: "layui-col-md3", name: "defaultDeliveryRail", label: "默认送货围栏:" },
              { type: "label", className: "layui-col-md1", label: "KM" }
            ]
          },
          {
            type: "row",
            list: [
              {
                type: "row", className: "layui-col-md6 form_btn_left",
                list: [
                  { type: "checkbox", className: "layui-col-md4", name: "returnOrderFlag", label: "是否要求回单:" }
                ]
              },
              { type: "input", className: "layui-col-md3", name: "returnOrderDeadline", label: "回单期限:", validate: "ValidNumeric" },
              { type: "label", className: "layui-col-md1", label: "天" }
            ]
          }
        ]
      }
    ]
  };

  // 创建form
  function editFormInit(rdata) {
    $("#carriers_edit_form").html("");
    edit_form = new PlgForm(master_form_opts);

    if (rdata) {
      edit_form.setFormData(rdata);
      rdata.city && getByPid(rdata.province, "city", rdata.city);
      rdata.district && getByPid(rdata.city, "district", rdata.district);
    }
    if (editType === "modify" || editType === "updateCarriersReceiver") {
      edit_form.disableItem("code");
      edit_form.disableItem("name");
    }
    else {
      edit_form.enableItem("code");
      edit_form.enableItem("name");
      if (editType === "copy") {
        edit_form.setItemValue("code", "");
        edit_form.setItemValue("name", "");
      }
    }

    edit_form.attachComboEvent("province", "onChange", function (id) {
      edit_form.setFormData({ shipmentProvinceName: edit_form.getCombo("province").getComboText() });
      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.setFormData({ shipmentCityName: edit_form.getCombo("city").getComboText() });
      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 = "#carriers_edit";
      addressAnalysis(returnDiv, { address, longitude, latitude });
    });

    // 部门弹窗
    departmentDialog("#carriers_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; }
    });
  }

  // 保存
  $("#carriers_save").on("click", function () {
    let feik = edit_form.validate();
    if (!feik) return;
    let formData = edit_form.getFormData();

    if (formData.returnOrderDeadline < 0 || formData.returnOrderDeadline > 100) {
      layer.msg("回单期限只能为0~100的数字")
      return false
    }

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

    date_list.forEach(item => {
      formData[item] = FormatDateTime(formData[item]);
    });

    dealNullQueryCondition(formData);

    let url = UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/carrier/" + editType;
    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("#carriers_main");
          master_grid.reload();
          return true;
        }
        return false;
      }, error: function () { PlgDialog.close(pload); return false; }
    });
  });

  let PoSingle_from1, cargoOwnerIds = [];

  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: "name", 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 + "/carrier/page_by_id", //数据接口
    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("addressAnalysisCarriers_div2A");
  //分组拆分条件查询
  // grid.loadData();

  //按钮添加方法
  grid.attachToolBarEvent("onButtonClick", function (name) {
    //查询
    if (name === "querywork") {
      var request = grid.getToolBarForm().getFormData();
      grid.setParams(JSON.stringify({ name: request.name, ids: 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 + "/carrier/modify", 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: "addressAnalysisCarriers_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("#carriers_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("addressAnalysisCarriersmyMap", {
    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", "AMap.Geocoder"], function () {
    var autoOptions = {
      input: "carriers_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("#carriers_addressAnalysis");
    PoSingle_from1.clear();

    if (returnDiv === "#carriers_main") {
      cargoOwnerIds = data;
      $("#addressAnalysisCarriers_div2A").show();
      PoSingle_from1.hideItem("master_addressAnalysis");
      grid.clearAll();
      grid.getToolBarForm().clear();
      grid.setParams(JSON.stringify({ ids: cargoOwnerIds }));
      grid.reload();
    }
    else {
      $("#addressAnalysisCarriers_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) {
        $("#addressAnalysisCarriers_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);
      }
    }
  }
};