/**
 * zzx
 * 2022.02.17
 * 客户管理
    */
import { UPCLOUD_RDC_TMS_MAINDATA_SERVICE, UPCLOUD_RDC_TMS_BUSINESS_SERVICE, UPCLOUD_RDC_TMS_INTERFACE_SERVICE, SERVICE_PLATFORM_POWER_BASE } from '@/config/serviceSettings.js';
import { getSelectGJ, querySysPicture, departmentDialog } from '@/utils/prolog.ajax.js';
export default () => {
  let master_grid, edit_form, master_form_opts, consignee_grid, consignee_form_opts, editType;
  let selectCustomerId, selectCustomerCode, selectCustomerName;

  // 获取扩展字段
  let gird_opts_list = [], form_opts_list = [], date_list = [];
  let consignee_gird_opts_list = [], consignee_form_opts_list = [], consignee_date_list = [];
  utilSyncAjaxGJ(UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/extendedField/list", "post", JSON.stringify({ "extendedObjectCode": "4" }), 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");
  utilSyncAjaxGJ(UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/extendedField/list", "post", JSON.stringify({ "extendedObjectCode": "5" }), function (res) {
    extendedFieldList({ list: res.data, className: "layui-col-md3" }, function (res) {
      consignee_gird_opts_list = res.gird_opts_list;
      consignee_form_opts_list = res.form_opts_list;
      consignee_date_list = res.date_list;
    });
  }, "application/json");

  // 跳转页面
  let carousel = layui.carousel;
  carousel.render({
    elem: "#customer",
    autoplay: false,
    index: 0,
    arrow: "none",
    indicator: "none",
    anim: "fade",
    width: "100%", //设置容器宽度
    height: "100%"
  });
  let viewList = ["#customer_edit", "#customer_main", "#customer_view", "#customer_addressAnalysis", "#consignee_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");
      }
    }
  }
  // 返回
  $(".customer_return").on("click", function () {
    changePanel("#customer_main");
  });
  $("#customer_addressAnalysis_return").on("click", function () {
    changePanel(returnDiv);
  });
  $("#consignee_addressAnalysis_return").on("click", function () {
    changePanel(returnDiv);
  });

  // 获取下拉框
  let dataSelect;
  getSelectGJ([
    { "objectcode": "MAINDATA_STATUS" },
    { "objectcode": "COOPERATIVE_NATURE" },
    { "objectcode": "BANK" },
    { "objectcode": "ENABLE_STATUS" },
    { "objectcode": "LINE_CARRIER_TYPE" },
  ], 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
  var consignor_Table = {
    columns: [
      { id: "cargoOwnerId", name: "id", type: "ro", width: "130", hidden: true },
      { id: "cargoOwnerCode", name: "货主编号", type: "ro" },
      { id: "cargoOwnerName", name: "货主名称", type: "ro" },
      { id: "cargoOwnerShortName", name: "货主简称", type: "ro" }
    ],
    toolbar: [
      { type: "settings", labelAlign: "right", labelWidth: 65 },
      { type: "input", name: "cargoOwnerCode", label: "货主编码:", width: 150 },
      { type: "newcolumn" },
      { type: "input", name: "cargoOwnerName", label: "货主名称:", width: 150 },
      { type: "newcolumn" },
      { type: "button", name: "querycarr", value: "查询" },
      { type: "newcolumn" },
      { type: "button", name: "car_Reset", value: "重置" }
    ],
    multiselect: false,
    pagebar: { type: "simple" },

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/cargo_owner/popup", //数据接口
    type: "post", //数据提交方式，默认为get
    contentType: "application/json",
    params: "{}", //查询提交参数，分页参数默认为pageNum,pageSize
    page: true, //是否启用分页
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };
  // 承运商table
  var carrierTable = {
    columns: [
      { id: "id", name: "id", type: "ro", width: "130", hidden: true },
      { id: "code", name: "承运商编号", type: "ro" },
      { id: "name", name: "承运商名称", type: "ro" }
    ],
    // multiselect: true,
    toolbar: [
      { type: "settings", position: "label-left" },
      {
        type: "block", id: "bk", blockOffset: 0, list: [
          { type: "input", name: "carrierCode", label: "承运商编码:", width: 120 },
          { type: "newcolumn" },
          { type: "input", name: "carrierName", label: "承运商名称:", width: 120 },
          { type: "newcolumn" },
          { type: "button", name: "querycarr", value: "查询" },
          { type: "newcolumn" },
          { type: "button", name: "car_Reset", value: "重置" }
        ]
      }
    ],

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/carrier/page", //数据接口
    type: "post", //数据提交方式，默认为get
    pagebar: { type: "simple" },
    contentType: "application/json",
    params: "{}", //查询提交参数，分页参数默认为pageNum,pageSize
    page: true, //是否启用分页
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };
  // 司机table
  var driverTable = {
    columns: [
      { id: "id", name: "id", type: "ro", width: "130", hidden: true },
      { id: "code", name: "司机编号", type: "ro" },
      { id: "name", name: "司机名称", type: "ro" },
      { id: "phoneNumber", name: "手机号", type: "ro" },
      { id: "typeName", name: "归属", type: "ro" },
      { id: "affiliationName", name: "隶属机构", type: "ro" }
    ],
    // multiselect: true,
    toolbar: [
      { type: "settings", position: "label-left", width: 200, labelWidth: 60 },
      {
        type: "block", id: "bk", blockOffset: 0, list: [
          { type: "input", name: "code", label: "司机编号:", width: 120 },
          { type: "newcolumn" },
          { type: "input", name: "name", label: "司机名称:", width: 120 },
          { type: "newcolumn" },
          { type: "button", name: "querycarr", value: "查询" },
          { type: "newcolumn" },
          { type: "button", name: "car_Reset", value: "重置" }
        ]
      }
    ],

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/driver/popup", //数据接口
    type: "post", //数据提交方式，默认为get
    contentType: "application/json",
    pagebar: { type: "simple" },
    params: "{}", //查询提交参数，分页参数默认为pageNum,pageSize
    page: true, //是否启用分页
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };

  // 客户table
  let gird_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: "copPropertyName", 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: "cargoOwnerName", 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: gird_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 = "查看^customer_view,复制^customer_copy,修改^customer_edit,";
          if (rd.status == "1") {
            result += "停用^customer_enOrDis";
          }
          else {
            result += "启用^customer_enOrDis";
          }
          result += ",删除^customer_del";
          return result;
        }
      }
    ]),
    toolbar: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md4", name: "customerCode", label: "客户编码:" },
          { type: "input", className: "layui-col-md4", name: "customerName", label: "客户名称:" },
          { type: "input", className: "layui-col-md4", name: "cargoOwnerName", label: "所属货主:" },
          {
            type: "block", className: "layui-col-md12 right",
            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 + "/tmsBaseCustomer/queryCustomer",
    type: "post",
    contentType: "application/json",
    params: "{}",
    page: true,
    totalCount: "totalCount"
  };
  master_grid = new PlgGrid(master_grid_opts);
  master_grid.renderTo("customer_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();
      consignee_grid.clearAll();
      consignee_grid.loadData({ data: { list: [] } });
    }
    else if (name === "master_reset") {
      master_grid.getToolBarForm().clear();
    }
    else if (name === "master_add") {
      changePanel("#customer_edit");
      $("#customer_edit_title").html("新增");
      editType = "saveCustomer";
      editFormInit("master");
    }
    else if (name === "master_addressAnalysis") {
      let ids = master_grid.getCheckedIds();
      if (!ids) {
        layer.msg("请选择数据");
        return false;
      }
      let list = ids.split(",");
      returnDiv = "#customer_main";
      customer_addressAnalysis(returnDiv, list);
    }
    else if (name === "master_en" || name === "master_dis") {
      let ids = master_grid.getCheckedIds();
      let Interface = name === "master_en" ? "activeCustomer" : "deleteCustomer";
      if (!ids) {
        layer.msg("请选择数据");
        return false;
      }
      let list = ids.split(",");
      deleteCustomer(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 };
      });
      deleteCustomer(list, "neverDelete");
    }
    else if (name === "master_import") {
      importDialog({ id: "import", importUrl: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/tmsBaseCustomer/batchImportCustomer", downloadUrl: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/tmsBaseCustomer/customer_download_template", downloadName: "客户模板" });
    }
  });

  // 单击一行显示明细
  master_grid.on("onRowSelect", function (id) {
    let { code, name } = master_grid.getRowData(id);
    selectCustomerId = id;
    selectCustomerCode = code;
    selectCustomerName = name;
    consignee_grid.setParams({ customerId: id });
    consignee_grid.reload();
  });

  // 停用/启用
  window.customer_enOrDis = function (rid, rdata) {
    let Interface = rdata.status == "1" ? "deleteCustomer" : "activeCustomer";
    deleteCustomer([rid], Interface);
  };
  // 删除
  window.customer_del = function (rid) {
    deleteCustomer([{ id: rid }], "neverDelete");
  };
  // 删除方法
  function deleteCustomer(idList, Interface) {
    let text = Interface === "activeCustomer" ? "启用" : Interface === "deleteCustomer" ? "停用" : "删除";
    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 + "/tmsBaseCustomer/" + 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();
              consignee_grid.clearAll();
              consignee_grid.loadData({ data: { list: [] } });
              return true;
            }
            return false;

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

  // 复制
  window.customer_copy = function (rid, rdata) {
    changePanel("#customer_edit");
    $("#customer_edit_title").html("复制");
    editType = "copyCustomer";
    editFormInit("master", rdata);
  };
  // 修改
  window.customer_edit = function (rid, rdata) {
    changePanel("#customer_edit");
    $("#customer_edit_title").html("修改");
    editType = "updateCustomer";
    editFormInit("master", rdata);
  };
  // 详情
  window.customer_view = function (rid, rdata) {
    changePanel("#customer_view");
    $("#customer_view_form_1").html("");
    $("#customer_view_form_2").html("");
    $("#customer_view_form_3").html("");
    $("#customer_view_form_4").html("");
    new PlgPanel({
      renderer: "customer_view_form_1",
      skin: 2,
      header: {
        isShow: true,
        title: "基本信息"
      },
      defaultBody: {
        layoutCol: 3,
        valueBj: true,
        cols: [
          [
            { label: "客户编码", value: rdata.code },
            { label: "客户名称", value: rdata.name },
            { label: "客户简称", value: rdata.shortName },
            { label: "部门", value: rdata.departmentName },
          ],
          [
            { label: "合作性质", value: rdata.copPropertyName },
            { label: "状态", value: rdata.statusName },
            { label: "税务登记号", value: rdata.taxRegisterNumber },
            { label: "营业执照号", value: rdata.businessLicenseNumber },
          ],
          [
            { label: "道路许可证", value: rdata.roadPermit },
            { label: "所属货主", value: rdata.cargoOwnerName },
            { label: "备注", value: rdata.memo }
          ],
        ]
      }
    });
    new PlgPanel({
      renderer: "customer_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: "customer_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: "customer_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 + "%" }
          ]
        ]
      }
    });
    new PlgPanel({
      renderer: "customer_view_form_5",
      skin: 2,
      header: {
        isShow: true,
        title: "扩展信息"
      },
      defaultBody: {
        layoutCol: 3,
        valueBj: true,
        cols: [
          gird_opts_list.map(item => {
            return { label: item.name, value: rdata[item.id] };
          })
        ]
      }
    });
  };

  // 客户编辑form
  master_form_opts = {
    renderer: "customer_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, required: 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: [
              {
                className: "layui-col-md3",
                type: "selectTable",
                placeholder: "请选择货主",
                readonly: false,
                table: consignor_Table,
                tableWidth: 800,
                tableHeight: 600,
                fieldText: "cargoOwnerName",
                fieldValue: "cargoOwnerCode",
                name: "consignorList",
                label: "所属货主:<span class='dhxform_item_required'>*</span>",
                listener: {
                  "init": function (grid) {
                    setMethod(grid, consignor_Table, function () { });
                  },
                  "afterSelect": function (isSelected, selectId, sgrid) {
                    let sdata = sgrid.getRowData(selectId);
                    edit_form.setFormData({
                      cargoOwnerId: isSelected ? sdata.cargoOwnerId : "",
                      cargoOwnerCode: isSelected ? sdata.cargoOwnerCode : "",
                      cargoOwnerName: isSelected ? sdata.cargoOwnerName : ""
                    });
                  }
                }
              },
              { type: "hidden", name: "cargoOwnerId" },
              { type: "hidden", name: "cargoOwnerCode" },
              { type: "hidden", name: "cargoOwnerName" },
              { type: "input", className: "layui-col-md6", name: "memo", label: "备注:" }
            ]
          }
        ]
      },
      {
        type: "fieldset", name: "contact", 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: "formBtn_addressAnalysis", value: "地址解析" }
                ]
              }
            ]
          }
        ]
      },
      {
        type: "fieldset", name: "bankAccount", 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: "回单期限:" },
              { type: "label", className: "layui-col-md1", label: "%" }
            ]
          }
        ]
      },
      {
        type: "fieldset", name: "kuozhan", label: "扩展信息", list: [
          { type: "settings", labelAlign: "right", labelWidth: 90 },
          {
            type: "row",
            list: form_opts_list
          }
        ]
      },
    ]
  };

  // 创建form
  function editFormInit(type, rdata) {
    $("#customer_edit_form").html("");
    if (type === "master") {
      edit_form = new PlgForm(master_form_opts);
    }
    else {
      edit_form = new PlgForm(consignee_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 (type === "master") {
        rdata.consignorList = rdata.cargoOwnerCode ? JSON.stringify([rdata.cargoOwnerCode]) : "";
        edit_form.setText("consignorList", rdata.cargoOwnerName || "");
      }
    }
    if (editType === "updateCustomer" || editType === "updateCustomerReceiver") {
      edit_form.disableItem("code");
      edit_form.disableItem("name");
      if (editType === "updateCustomerReceiver") {
        if (rdata.carrierType === '2') {
          edit_form.hideItem("carrierList")
          edit_form.showItem("driverList")
          rdata.driverList = rdata.carrierCode ? JSON.stringify([rdata.carrierCode]) : "";
          edit_form.setText("driverList", rdata.carrierName || "");
        }
        else {
          edit_form.showItem("carrierList")
          edit_form.hideItem("driverList")
          rdata.carrierList = rdata.carrierCode ? JSON.stringify([rdata.carrierCode]) : "";
          edit_form.setText("carrierList", rdata.carrierName || "");
        }
      }
    }
    else {
      edit_form.enableItem("code");
      edit_form.enableItem("name");
      if (editType === "copyCustomer") {
        edit_form.setItemValue("code", "");
        edit_form.setItemValue("name", "");
      }
      if (type === "consignee") {
        // edit_form.getCombo("status").setComboValue("1");
        edit_form.showItem("carrierList")
        edit_form.hideItem("driverList")
      }
    }

    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 = "#customer_edit";
      customer_addressAnalysis(returnDiv, { address, longitude, latitude });
    });

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

    edit_form.attachComboEvent("carrierType", "onChange", function (id) {
      if (id === '1') {
        edit_form.showItem("carrierList")
        edit_form.hideItem("driverList")
      }
      else {
        edit_form.hideItem("carrierList")
        edit_form.showItem("driverList")
      }
      edit_form.setFormData({ carrierId: '', carrierCode: '', carrierName: '' })
    })
  }
  // 省市区联动
  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; }
    });
  }

  // 保存
  $("#customer_save").on("click", function () {
    let feik = edit_form.validate();
    if (!feik) return;
    let formData = edit_form.getFormData();
    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) : "";
    if (editType.includes("Customer")) {
      date_list.forEach(item => {
        formData[item] = FormatDateTime(formData[item]);
      });
    } else {
      consignee_date_list.forEach(item => {
        formData[item] = FormatDateTime(formData[item]);
      });
    }


    if (formData.phoneNumber && !Prolog.isMobileNo(formData.phoneNumber)) {
      PlgDialog.msg("请输入正确的手机号");
      return;
    }
    if (formData.landlineNumber && !Prolog.isLandlineNo(formData.landlineNumber)) {
      PlgDialog.msg("请输入正确的座机号");
      return;
    }
    if (formData.email && !Prolog.isEmail(formData.email)) {
      PlgDialog.msg("请输入正确的邮箱");
      return;
    }

    if (editType === "saveCustomer" || editType === "saveCustomerReceiver") {
      Save(formData);
    }
    else {
      layer.open({
        title: editType.includes("update") ? "修改" : "复制",
        content: "是否保存？",
        btn: ["确认", "取消"],
        yes: function () {
          Save(formData);
        }
      });
    }
  });
  function Save(formData) {
    if (editType === "saveCustomerReceiver" || editType === "updateCustomerReceiver") {
      formData.customerId = selectCustomerId;
      formData.customerCode = selectCustomerCode;
      formData.customerName = selectCustomerName;
    }

    let url = UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/tmsBaseCustomer/" + 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("#customer_main");
          if (editType.includes("Receiver")) {
            consignee_grid.reload();
          }
          else {
            master_grid.reload();
            consignee_grid.clearAll();
            consignee_grid.loadData({ data: { list: [] } });
          }
          return true;
        }
        return false;
      }, error: function () { PlgDialog.close(pload); return false; }
    });
  }

  let customer_map_form, customer_map_ids = [], customer_map_grid;

  var customer_map_grid_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 + "/tmsBaseCustomer/queryCustomerForAddress", //数据接口
    type: "post", //数据提交方式，默认为get
    contentType: "application/json",
    params: "{}", //查询提交参数，分页参数默认为pageNum,pageSize
    page: true, //是否启用分页
    multiselect: false,
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };
  //分页参数 pageSize pageNum
  customer_map_grid = new PlgGrid(customer_map_grid_opts);
  customer_map_grid.renderTo("addressAnalysisCustomer_div2A");

  //按钮添加方法
  customer_map_grid.attachToolBarEvent("onButtonClick", function (name) {
    //查询
    if (name === "querywork") {
      var request = customer_map_grid.getToolBarForm().getFormData();
      customer_map_grid.setParams(JSON.stringify({ name: request.name, ids: customer_map_ids }));
      customer_map_grid.reload();
    }
    //重置
    if (name === "work_Reset") {
      customer_map_grid.getToolBarForm().clear();
    }
    //保存
    if (name === "work_Reset2") {
      let id = customer_map_grid.getSelectedRowId();
      if (!id) {
        layer.msg("请选择一行数据");
        return;
      }
      let formData = customer_map_form.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 + "/tmsBaseCustomer/updateCustomer", type: "post", contentType: "application/json", data: JSON.stringify(formData),
        success: function (res) {
          PlgDialog.close(pload);
          if (res.success) {
            PlgDialog.msg(res.message);
            customer_map_grid.reload();
            customer_map_form.clear();
            return true;
          }
          return false;
        }, error: function () { PlgDialog.close(pload); return false; }
      });
    }
  });

  let customer_map_form_opts = {
    renderer: "addressAnalysisCustomer_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: "地址解析" }

        ]
      }
    ]
  };
  customer_map_form = new PlgForm(customer_map_form_opts);
  customer_map_form.attachEvent("onButtonClick", function (name) {
    if (name === "master_addressAnalysis") {
      changePanel("#customer_edit");
      let { newLongitude, newLatitude } = customer_map_form.getFormData();
      edit_form.setFormData({ longitude: newLongitude, latitude: newLatitude });
    }
  });

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

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

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

  // 将经纬度转换为地址
  var customer_geocoder;
  var customer_marker;
  function customer_regeoCode(lnglat) {
    customer_marker && customer_myMap.remove(customer_marker);
    customer_marker = new AMap.Marker({
      position: new AMap.LngLat(lnglat[0], lnglat[1])
    });
    customer_myMap.add(customer_marker);
    customer_myMap.setCenter(lnglat);

    customer_geocoder.getAddress(lnglat, function (status, result) {
      if (status === "complete" && result.regeocode) {
        var regeocode = result.regeocode;
        let newAddress = regeocode.formattedAddress.split(regeocode.addressComponent.district)[1];
        customer_map_form.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(customer_myMap, lnglat);
      }
      else {
        layer.msg("根据经纬度查询地址失败");
      }
    });
  }

  AMap.plugin(["AMap.AutoComplete", "AMap.PlaceSearch", "AMap.Geocoder"], function () {
    // 查询输入框
    var autoOptions = {
      input: "customer_addressAnalysis_keyword"//使用联想输入的input的id
    };
    var autocomplete = new AMap.AutoComplete(autoOptions);
    var placeSearch = new AMap.PlaceSearch({
      map: customer_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) {
      customer_regeoCode([e.data.location.lng, e.data.location.lat]);
    });

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

  function customer_addressAnalysis(returnDiv, data) {
    changePanel("#customer_addressAnalysis");
    customer_map_form.clear();

    if (returnDiv === "#customer_main") {
      customer_map_ids = data;
      $("#addressAnalysisCustomer_div2A").show();
      customer_map_form.hideItem("master_addressAnalysis");
      customer_map_grid.clearAll();
      customer_map_grid.getToolBarForm().clear();
      customer_map_grid.setParams(JSON.stringify({ ids: customer_map_ids }));
      customer_map_grid.reload();
    }
    else {
      $("#addressAnalysisCustomer_div2A").hide();
      customer_map_form.showItem("master_addressAnalysis");
      let { address, longitude, latitude } = data;
      customer_map_form.setFormData({ address, longitude, latitude });
      if (longitude && latitude) {
        customer_regeoCode([longitude, latitude]);
      }
      else if (address) {
        $("#addressAnalysisCustomer_tip input").val(address);
        setTimeout(() => {
          var placeSearch = new AMap.PlaceSearch({
            map: customer_myMap
          });
          placeSearch.search(address);
          AMap.Event.addListener(placeSearch, "markerClick", function (e) {
            customer_regeoCode([e.data.location.lng, e.data.location.lat]);
          });
        }, 100);
      }
    }
  }

  // 收货方table
  let consignee_gird_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: "statusName", 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: "memo", name: "备注", type: "ro", width: 120 },
    { id: "carrierTypeName", name: "默认承运方类型", type: "ro", width: 120 },
    { id: "carrierName", 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 },
  ]
  let consignee_grid_opts = {
    skin: "card",
    columns: consignee_gird_opts_columns.concat(consignee_gird_opts_list, [
      {
        id: "op", name: "操作", type: "button", align: "center", fixed: "right", width: 200, render: function (v, rd) {
          let result = "查看^consignee_view,修改^consignee_edit,";
          if (rd.status == "1") {
            result += "停用^consignee_enOrDis";
          }
          else {
            result += "启用^consignee_enOrDis";
          }
          result += ",删除^consignee_del";
          return result;
        }
      }
    ]),
    toolbar: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          {
            type: "block", className: "layui-col-md12 right",
            list: [
              { type: "button", className: "btn-normal", name: "consignee_add", value: "<i class='layui-icon layui-icon-add-1'></i>新 增" },
              { type: "newcolumn" },
              { type: "button", className: "btn-normal", name: "consignee_en", value: "启用" },
              { type: "newcolumn" },
              { type: "button", className: "btn-danger", name: "consignee_dis", value: "停用" },
              { type: "newcolumn" },
              { type: "button", className: "btn-danger", name: "consignee_del", value: "删除" },
              { type: "newcolumn" },
              { type: "button", className: "btn-normal", name: "consignee_addressAnalysis", value: "地址解析" },
              { type: "newcolumn" },
              { type: "button", className: "btn-normal", name: "consignee_import", value: "导入" }

            ]
          }
        ]
      }
    ],
    multiselect: true,
    fixedLast: true,

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/tmsBaseCustomer/queryCustomerReceiver",
    type: "post",
    contentType: "application/x-www-form-urlencoded",
    params: {},
    page: false,
    totalCount: "totalCount"
  };
  consignee_grid = new PlgGrid(consignee_grid_opts);
  consignee_grid.renderTo("customer_consignee");

  consignee_grid.attachToolBarEvent("onButtonClick", function (name) {
    if (name === "consignee_add") {
      if (!master_grid.getSelectedRowId()) {
        layer.msg("请选择客户");
        return false;
      }
      changePanel("#customer_edit");
      $("#customer_edit_title").html("新增");
      editType = "saveCustomerReceiver";
      editFormInit("consignee");
    }
    else if (name === "consignee_addressAnalysis") {
      let ids = consignee_grid.getCheckedIds();
      if (!ids) {
        layer.msg("请选择数据");
        return false;
      }
      let list = ids.split(",");
      returnDiv = "#customer_main";
      consignee_addressAnalysis(returnDiv, list);
    }
    else if (name === "consignee_en" || name === "consignee_dis") {
      let ids = consignee_grid.getCheckedIds();
      let Interface = name === "master_en" ? "activeCustomerReceiver" : "deleteCustomerReceiver";
      if (!ids) {
        layer.msg("请选择数据");
        return false;
      }
      let list = ids.split(",");
      deleteCustomerReceiver(list, Interface);
    }
    else if (name === "consignee_del") {
      let ids = consignee_grid.getCheckedIds();
      if (!ids) {
        layer.msg("请选择数据");
        return false;
      }
      let list = ids.split(",").map(item => {
        return { id: item };
      });
      deleteCustomerReceiver(list, "neverDeleteCustomerReceiver");
    }
    else if (name === "consignee_import") {
      importDialog({ id: "import", importUrl: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/tmsBaseCustomer/batchImportCustomerReceiver", downloadUrl: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/tmsBaseCustomer/consignee_download_template", downloadName: "客户收货方模板" });
    }
  });

  // 停用/启用
  window.consignee_enOrDis = function (rid, rdata) {
    let Interface = rdata.status == "1" ? "deleteCustomerReceiver" : "activeCustomerReceiver";
    deleteCustomerReceiver([rid], Interface);
  };
  // 删除
  window.consignee_del = function (rid) {
    deleteCustomer([{ id: rid }], "neverDeleteCustomerReceiver");
  };
  // 删除方法
  function deleteCustomerReceiver(idList, Interface) {
    let text = Interface === "activeCustomerReceiver" ? "启用" : Interface === "deleteCustomerReceiver" ? "停用" : "删除";
    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 + "/tmsBaseCustomer/" + 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);
              consignee_grid.reload();
              return true;
            }
            return false;

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

  // 修改
  window.consignee_edit = function (rid, rdata) {
    changePanel("#customer_edit");
    $("#customer_edit_title").html("修改");
    editType = "updateCustomerReceiver";
    editFormInit("consignee", rdata);
  };
  // 详情
  window.consignee_view = function (rid, rdata) {
    changePanel("#customer_view");
    $("#customer_view_form_1").html("");
    $("#customer_view_form_2").html("");
    $("#customer_view_form_3").html("");
    $("#customer_view_form_4").html("");
    new PlgPanel({
      renderer: "customer_view_form_1",
      skin: 2,
      header: {
        isShow: true,
        title: "基本信息"
      },
      defaultBody: {
        layoutCol: 3,
        valueBj: true,
        cols: [
          [
            { label: "收货方编码", value: rdata.code },
            { label: "收货方名称", value: rdata.name },
            { label: "收货方简称", value: rdata.shortName },
            { label: "状态", value: rdata.statusName }
          ],
          [
            { label: "联系人", value: rdata.contact },
            { label: "手机号", value: rdata.phoneNumber },
            { label: "座机号", value: rdata.landlineNumber },
            { label: "邮箱", value: rdata.email }
          ],
          [
            { label: "关联方手机号", value: rdata.relationPhoneNumber },
            { label: "省", value: rdata.provinceName },
            { label: "市", value: rdata.cityName },
            { label: "区", value: rdata.districtName }
          ],
          [
            { label: "备注", value: rdata.memo },
            { label: "详细地址", value: rdata.address },
            { label: "经度", value: rdata.longitude },
            { label: "纬度", value: rdata.latitude }
          ]
        ]
      }
    });
    new PlgPanel({
      renderer: "customer_view_form_2",
      skin: 2,
      header: {
        isShow: true,
        title: "扩展信息"
      },
      defaultBody: {
        layoutCol: 3,
        valueBj: true,
        cols: [
          consignee_gird_opts_list.map(item => {
            return { label: item.name, value: rdata[item.id] };
          })
        ]
      }
    });
  };

  // 收货方编辑form
  consignee_form_opts = {
    renderer: "customer_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: "combo", className: "layui-col-md3", name: "carrierType", label: "默认承运方类型:", options: dataSelect.LINE_CARRIER_TYPE, readonly: true }
              // { type: "combo", className: "layui-col-md3", name: "status", label: "状态:", options: dataSelect.MAINDATA_STATUS, readonly: true }
            ]
          },
          {
            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: "座机号:" },
              {
                className: "layui-col-md3",
                type: "selectTable",
                placeholder: "请选择承运商",
                readonly: false,
                table: carrierTable,
                tableWidth: 800,
                tableHeight: 600,
                fieldText: "name",
                fieldValue: "code",
                name: "carrierList",
                label: "默认承运方:",
                listener: {
                  "init": function (grid) {
                    setMethod(grid, carrierTable, function () { });
                  },
                  "afterSelect": function (isSelected, selectId, sgrid) {
                    let sdata = sgrid.getRowData(selectId);
                    edit_form.setFormData({
                      carrierId: isSelected ? sdata.id : "",
                      carrierCode: isSelected ? sdata.code : "",
                      carrierName: isSelected ? sdata.name : ""
                    });
                  }
                }
              },
              {
                className: "layui-col-md3",
                type: "selectTable",
                placeholder: "请选择司机",
                readonly: false,
                table: driverTable,
                tableWidth: 800,
                tableHeight: 600,
                fieldText: "name",
                fieldValue: "code",
                name: "driverList",
                label: "默认承运方:",
                listener: {
                  "init": function (grid) {
                    setMethod(grid, driverTable, function () { });
                  },
                  "afterSelect": function (isSelected, selectId, sgrid) {
                    let sdata = sgrid.getRowData(selectId);
                    edit_form.setFormData({
                      carrierId: isSelected ? sdata.id : "",
                      carrierCode: isSelected ? sdata.code : "",
                      carrierName: isSelected ? sdata.name : ""
                    });
                  }
                }
              },
              { type: "hidden", name: "carrierId" },
              { type: "hidden", name: "carrierCode" },
              { type: "hidden", name: "carrierName" },
            ]
          },
          {
            type: "row",
            list: [
              { type: "input", className: "layui-col-md3", name: "relationPhoneNumber", 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: "input", className: "layui-col-md3", name: "email", label: "邮箱:" },
              { type: "input", className: "layui-col-md3", name: "memo", 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: "formBtn_addressAnalysis", value: "地址解析" }
                ]
              }
            ]
          }
        ]
      },
      {
        type: "fieldset", name: "kuozhan", label: "扩展信息", list: [
          { type: "settings", labelAlign: "right", labelWidth: 90 },
          {
            type: "row",
            list: consignee_form_opts_list
          }
        ]
      },
    ]
  };

  let consignee_map_form, consignee_map_ids = [], customerId;

  var consignee_map_grid_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 + "/tmsBaseCustomer/queryCustomerReceiverForAddress", //数据接口
    type: "post", //数据提交方式，默认为get
    contentType: "application/json",
    params: "{}", //查询提交参数，分页参数默认为pageNum,pageSize
    page: true, //是否启用分页
    multiselect: false,
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };
  //分页参数 pageSize pageNum
  let consignee_map_grid = new PlgGrid(consignee_map_grid_opts);
  consignee_map_grid.renderTo("addressAnalysisConsignee_div2A");

  //按钮添加方法
  consignee_map_grid.attachToolBarEvent("onButtonClick", function (name) {
    //查询
    if (name === "querywork") {
      var request = consignee_map_grid.getToolBarForm().getFormData();
      consignee_map_grid.setParams(JSON.stringify({ name: request.name, ids: consignee_map_ids, customerId }));
      consignee_map_grid.reload();
    }
    //重置
    if (name === "work_Reset") {
      consignee_map_grid.getToolBarForm().clear();
    }
    //保存
    if (name === "work_Reset2") {
      let id = consignee_map_grid.getSelectedRowId();
      if (!id) {
        layer.msg("请选择一行数据");
        return;
      }
      let formData = consignee_map_form.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 + "/tmsBaseCustomer/updateCustomerReceiver", type: "post", contentType: "application/json", data: JSON.stringify(formData),
        success: function (res) {
          PlgDialog.close(pload);
          if (res.success) {
            PlgDialog.msg(res.message);
            consignee_map_grid.reload();
            consignee_map_form.clear();
            return true;
          }
          return false;
        }, error: function () { PlgDialog.close(pload); return false; }
      });
    }
  });

  let consignee_map_form_opts = {
    renderer: "addressAnalysisConsignee_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: "地址解析" }
        ]
      }
    ]
  };
  consignee_map_form = new PlgForm(consignee_map_form_opts);
  consignee_map_form.attachEvent("onButtonClick", function (name) {
    if (name === "master_addressAnalysis") {
      let { newLongitude, newLatitude } = consignee_map_form.getFormData();
      eve.emit("setAnalysis_customer", { longitude: newLongitude, latitude: newLatitude });
      addressAnalysis_customer_return();
    }
  });

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

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

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

  // 将经纬度转换为地址
  var consignee_geocoder;
  var consignee_marker;
  function consignee_regeoCode(lnglat) {
    consignee_marker && consignee_myMap.remove(consignee_marker);
    consignee_marker = new AMap.Marker({
      position: new AMap.LngLat(lnglat[0], lnglat[1])
    });
    consignee_myMap.add(consignee_marker);
    consignee_myMap.setCenter(lnglat);

    consignee_geocoder.getAddress(lnglat, function (status, result) {
      if (status === "complete" && result.regeocode) {
        var regeocode = result.regeocode;
        let newAddress = regeocode.formattedAddress.split(regeocode.addressComponent.district)[1];
        consignee_map_form.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(consignee_myMap, lnglat);
      }
      else {
        layer.msg("根据经纬度查询地址失败");
      }
    });
  }

  AMap.plugin(["AMap.AutoComplete", "AMap.PlaceSearch"], function () {
    // 查询输入框
    var autoOptions = {
      input: "consignee_addressAnalysis_keyword"//使用联想输入的input的id
    };
    var autocomplete = new AMap.AutoComplete(autoOptions);
    var placeSearch = new AMap.PlaceSearch({
      map: consignee_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) {
      consignee_regeoCode([e.data.location.lng, e.data.location.lat]);
    });

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

  function consignee_addressAnalysis(returnDiv, data) {
    changePanel("#consignee_addressAnalysis");
    consignee_map_form.clear();

    if (returnDiv === "#customer_main") {
      consignee_map_ids = data;
      customerId = selectCustomerId;
      $("#addressAnalysisConsignee_div2A").show();
      consignee_map_form.hideItem("master_addressAnalysis");
      consignee_map_grid.clearAll();
      consignee_map_grid.getToolBarForm().clear();
      consignee_map_grid.setParams(JSON.stringify({ ids: consignee_map_ids, customerId }));
      consignee_map_grid.reload();
    }
    else {
      $("#addressAnalysisConsignee_div2A").hide();
      consignee_map_form.showItem("master_addressAnalysis");
      let { address, longitude, latitude } = data;
      consignee_map_form.setFormData({ address, longitude, latitude });
      if (longitude && latitude) {
        consignee_regeoCode([longitude, latitude]);
      }
      else if (address) {
        $("#addressAnalysisConsignee_tip input").val(address);
        setTimeout(() => {
          var placeSearch = new AMap.PlaceSearch({
            map: consignee_myMap
          });
          placeSearch.search(address);
          AMap.Event.addListener(placeSearch, "markerClick", function (e) {
            consignee_regeoCode([e.data.location.lng, e.data.location.lat]);
          });
        }, 100);
      }
    }
  }
};
