/**
 * zzx
 * 2020.11.17
 * 单位资料管理
    */
    import { UPCLOUD_RDC_TMS_MAINDATA_SERVICE,UPCLOUD_RDC_TMS_BUSINESS_SERVICE,UPCLOUD_RDC_TMS_INTERFACE_SERVICE} from '@/config/serviceSettings.js';
    import { getSelectGJ, querySysPicture } from '@/utils/prolog.ajax.js';
export default () => {
  var master_grid, edit_form_opts, edit_form, edit_grid, dialog_form;

  // 跳转页面
  var carousel = layui.carousel;
  carousel.render({
    elem: "#unitDataManage",
    autoplay: false,
    index: 0,
    arrow: "none",
    indicator: "none",
    anim: "fade",
    width: "100%", // 设置容器宽度
    height: "100%"
  });
  // 切换页面
  function changePanel(name) {
    var slideList = ["#unitDataManage_main", "#unitDataManage_edit"];
    for (var i = 0; i < slideList.length; i++) {
      if (slideList[i] == name) {
        $(name).css("display", "block");
      }
      else {
        $(slideList[i]).css("display", "none");
      }
    }
  }
  // 返回
  $("#unitDataManage_edit_return").on("click", function () {
    changePanel("#unitDataManage_main");
    master_grid.reload();
  });

  // 获取下拉框
  var dataSelect;
  getSelectGJ([
    { "objectcode": "COMPANY_TYPE", "groupcode1": "2" },
    { "objectcode": "COMPANY_STATUS" }
  ], function (data) {
    dataSelect = data.data;
  });

  // 查询省
  var 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 consignorTable = {
    // terrace显示全部，card分页显示
    skin: "card",
    // renderer:"grid",
    columns: [
      { id: "companyid", name: "id", type: "ro", width: "130", hidden: true },
      { id: "companycode", name: "货主编号", type: "ro" },
      { id: "companyname", name: "货主名称", type: "ro" }
    ],
    multiselect: false,
    toolbar: [
      { type: "settings", position: "label-left", width: 200, labelWidth: 100 },
      {
        type: "block", id: "bk", blockOffset: 0, list: [
          { type: "input", name: "companycode", label: "货主编号:", width: 120 },
          { type: "newcolumn" },
          { type: "button", name: "querycarr", value: "查询" },
          { type: "newcolumn" },
          { type: "button", name: "car_Reset", value: "重置" }
        ]
      }
    ],

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/pubCompany/queryCompanyConsignor",
    pagebar: { type: "simple" },
    type: "post", // 数据提交方式，默认为get
    params: JSON.stringify({ companytype: "H" }), // 查询提交参数，分页参数默认为pageNum,pageSize
    contentType: "application/json",
    page: true, // 是否启用分页
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };

  // 主页grid
  var master_grid_opts = {
    skin: "card",
    columns: [
      { id: "companyid", name: "id", type: "ro", width: "130", hidden: true },
      { id: "companycode", name: "单位编号", type: "ro", width: 120 },
      { id: "companyname", name: "单位名称", type: "ro", width: 120 },
      { id: "shortname", name: "简称", type: "ro", width: 120 },
      { id: "companytypeName", name: "单位类型", type: "ro", width: 120 },
      { id: "zjm", name: "助记码", type: "ro", width: 120 },
      { id: "legalman", name: "法人", type: "ro", width: 120 },
      { id: "address", name: "详细地址", type: "ro", width: 120 },
      { id: "contactman", name: "联系人", type: "ro", width: 120 },
      { id: "tel", name: "联系方式", type: "ro", width: 120 },
      { id: "statusName", name: "状态", type: "ro", width: 120 },
      { id: "remark", name: "备注", type: "ro", width: 120 },
      // {
      //   id: "containerType", name: "容器类型", type: "ro", render: function (v) {
      //     return getSelectValue(dataSelect.CONTAINER_TYPE, v);
      //   }
      // },
      {
        id: "op", name: "操作", type: "button", align: "left", width: 150, fixed: "right", render: function (v, rd) {
          if (rd.source === "WMS") {
            return "详情^unitDataManage_view";
          }
          return "修改^unitDataManage_edit,删除^unitDataManage_del,详情^unitDataManage_view";
        }
      }
    ],
    toolbar: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md3", name: "companycode", label: "单位编号:" },
          { type: "input", className: "layui-col-md3", name: "companyname", label: "单位名称:" },
          { type: "combo", className: "layui-col-md3", readonly: true, name: "companytype", label: "单位类型:", options: [{ "value": "", "text": "" }].concat(dataSelect.COMPANY_TYPE) },
          { type: "input", className: "layui-col-md3", name: "zjm", 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: "block", className: "layui-col-md6 right",
            list: [
              { type: "button", className: "btn-normal", name: "master_add", value: "<i class='layui-icon layui-icon-add-1'></i>新 增" }
            ]
          }
        ]
      }

    ],
    pagebar: {
      buttons: [
        { text: "<i class='layui-icon layui-icon-delete'></i>删除", className: "plg-btn-normal", name: "page_del" }
      ]
    },
    fixedLast: true, // 开启固定列，固定最后一行，倒数第二列不能隐藏
    multiselect: true, // 是否支持多选

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/pubCompany/searchPubCompany", // 数据接口
    type: "post", // 数据提交方式，默认为get
    params: JSON.stringify({ companytypes: ["C", "H", "V"] }), // 查询提交参数，分页参数默认为pageNum,pageSize
    page: true, // 是否启用分页
    contentType: "application/json",
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  master_grid = new PlgGrid(master_grid_opts);
  master_grid.renderTo("unitDataManage_master");
  master_grid.loadData();
  master_grid.attachToolBarEvent("onButtonClick", function (name) {
    switch (name) {
      case "master_search":
        var request = master_grid.getToolBarForm().getFormData();
        request.companytypes = ["C", "H", "V"];
        master_grid.setParams(JSON.stringify(request));
        master_grid.reload();
        break;
      case "master_reset":
        master_grid.getToolBarForm().clear();
        break;
      case "master_add":
        changePanel("#unitDataManage_edit");
        $("#unitDataManage_edit_form").html("");
        editFormCreated();
        editGridCreated();
        $("#unitDataManage_edit_title").html("新增");
        //$("#unitDataManage_edit_grid").hide();
        break;
    }
  });
  // 单个删除
  window.unitDataManage_del = function (rid) {
    deletePubCompany([{ companyid: rid }]);
  };
  // 批量删除
  master_grid.attachPageBarEvent(function (name, ids) {
    let list = ids.split(",").map(item => {
      return { companyid: item };
    });
    deletePubCompany(list);
  });
  // 删除方法
  function deletePubCompany(idList) {
    layer.open({
      title: "删除",
      content: "是否删除？",
      btn: ["确认", "取消"],
      yes: function () {
        let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
        Prolog.ajax({
          url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/pubCompany/deletePubCompany", 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.unitDataManage_edit = function (rid, rdata) {
    changePanel("#unitDataManage_edit");
    $("#unitDataManage_edit_form").html("");
    $("#unitDataManage_edit_save").show();
    rdata.crossDays = rdata.crossDays || "0";
    rdata.serviceTime = rdata.serviceTime || "0";
    editFormCreated(rdata);
    editGridCreated(rdata);
    $("#unitDataManage_edit_title").html("修改");
    //$("#unitDataManage_edit_grid").show();
  };
  // 查看
  window.unitDataManage_view = function (rid, rdata) {
    changePanel("#unitDataManage_edit");
    $("#unitDataManage_edit_form").html("");
    $("#unitDataManage_edit_save").hide();
    editFormCreated(rdata, true);
    editGridCreated(rdata, true);
    $("#unitDataManage_edit_title").html("详情");
    //$("#unitDataManage_edit_grid").show();
  };

  // 详情form
  edit_form_opts = {
    renderer: "unitDataManage_edit_form",
    items: [
      { type: "settings", labelAlign: "left", labelWidth: 90 },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md3", name: "companycode", label: "单位编号:", required: true },
          { type: "input", className: "layui-col-md3", name: "companyname", label: "单位名称:", required: true },
          { type: "input", className: "layui-col-md3", name: "zjm", label: "助记码:", required: true },
          { type: "input", className: "layui-col-md3", name: "shortname", label: "单位简称:" }
        ]
      },
      {
        type: "row",
        list: [
          { type: "combo", className: "layui-col-md3", name: "companytype", label: "单位类型:", options: dataSelect.COMPANY_TYPE, readonly: true, required: true },
          {
            type: "selectTable",
            className: "layui-col-md3",
            placeholder: "请选择货主",
            readonly: false,
            table: consignorTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "companyname",
            fieldValue: "companyid",
            name: "consignorList",
            label: "货主:<span class='dhxform_item_required'>*<span>",
            listener: {
              "init": function (Grid) {
                // 注册按钮事件
                Grid.attachToolBarEvent("onButtonClick", function (name) {
                  switch (name) {
                    case "querycarr":
                      var request = Grid.getToolBarForm().getFormData();
                      Grid.setParams(JSON.stringify(request));
                      Grid.reload();
                      break;
                    case "car_Reset":
                      Grid.getToolBarForm().clear();
                      break;
                  }
                });
              },
              "afterSelect": function (isSelected, selectId, sgrid) {
                let sdata = sgrid.getRowData(selectId);
                edit_form.setFormData({
                  consignor: isSelected ? sdata.companyid : "",
                  consignorname: isSelected ? sdata.companyname : ""
                });
              }
            }
          },
          { type: "hidden", name: "consignor", label: "" },
          { type: "hidden", name: "consignorname", label: "" },
          { type: "input", className: "layui-col-md3", name: "legalman", label: "法人:" },
          { type: "input", className: "layui-col-md3", name: "address", label: "详细地址:", required: true }
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md3", name: "contactman", label: "联系人:" },
          { type: "input", className: "layui-col-md3", name: "tel", label: "联系方式:" },
          { type: "combo", className: "layui-col-md3", name: "status", label: "状态:", options: dataSelect.COMPANY_STATUS, readonly: true, required: true }
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md12", name: "remark", label: "备注:", rows: 1 }
        ]
      },
      {
        type: "block",
        blockOffset: 0,
        name: "timeInfo",
        //hidden: true,
        list: [
          { type: "hidden", name: "coordinateSystem", value: "GCJ" },
          { type: "input", name: "serviceTime", label: "交接货物时间:", width: 220, validate: "ValidInteger", value: "0", placeholder: "单位秒", required: true },
          { type: "newcolumn" },
          { type: "label", name: "serviceStartTime", label: "<div class='label'>开始收货时间:</div><input class='dhxform_textarea plg-input' readonly style='width: 220px;' id='unit_stime' />", width: 310, labelWidth: 310 },
          { type: "newcolumn" },
          { type: "label", name: "serviceEndTime", label: "<div class='label'>停止收货时间:</div><input class='dhxform_textarea plg-input' readonly style='width: 220px;' id='unit_etime' />", width: 310, labelWidth: 305 }
        ]
      },
      {
        type: "block",
        blockOffset: 0,
        name: "timeInfo1",
        //hidden: true,
        list: [
          { type: "input", name: "crossDays", label: "跨天数:", width: 220, validate: "ValidInteger", maxLength: 4, value: "0", placeholder: "单位天", required: true },
          { type: "newcolumn" },
          { type: "checkbox", name: "isAllowCrossDay", label: "允许跨天", width: 300, labelWidth: 295, position: "label-right", checked: true },
          { type: "newcolumn" }
        ]
      },
      {
        type: "block",
        blockOffset: 0,
        name: "timeInfo2",
        //hidden: true,
        list: [
          { type: "label", name: "serviceStartTime2", label: "<div class='label'>开始收货时间2:</div><input class='dhxform_textarea plg-input' readonly style='width: 220px;' id='unit_stime2' />", width: 310, labelWidth: 310 },
          { type: "newcolumn" },
          { type: "label", name: "serviceEndTime2", label: "<div class='label'>停止收货时间2:</div><input class='dhxform_textarea plg-input' readonly style='width: 220px;' id='unit_etime2' />", width: 310, labelWidth: 305 },
          { type: "newcolumn" },
          { type: "label", name: "serviceStartTime3", label: "<div class='label'>开始收货时间3:</div><input class='dhxform_textarea plg-input' readonly style='width: 220px;' id='unit_stime3' />", width: 310, labelWidth: 310 },
          { type: "newcolumn" },
          { type: "label", name: "serviceEndTime3", label: "<div class='label'>停止收货时间3:</div><input class='dhxform_textarea plg-input' readonly style='width: 220px;' id='unit_etime3' />", width: 310, labelWidth: 305 }
        ]
      }
    ]
  };
  // 注册详情form type:true-详情
  function editFormCreated(rdata, type) {
    edit_form = new PlgForm(edit_form_opts);
    edit_form.attachComboEvent("companytype", "onChange", function (id) {
      edit_form.setFormData({ consignor: "", consignorname: "" });
      edit_form.setText("consignorList", "");
      if (id == "C") {
        edit_form.showItem("timeInfo");
        edit_form.showItem("timeInfo1");
        edit_form.showItem("timeInfo2");
        edit_form.setItemValue("serviceTime", "");
        edit_form.setItemValue("crossDays", "");
      }
      else {
        edit_form.setItemValue("serviceTime", "0");
        edit_form.setItemValue("crossDays", "0");
        edit_form.hideItem("timeInfo");
        edit_form.hideItem("timeInfo1");
        edit_form.hideItem("timeInfo2");
      }
      if (id === "H") {
        edit_form.hideItem("consignorList");
      }
      else {
        edit_form.showItem("consignorList");
      }
    });

    edit_form.attachEvent("onChange", function (name, value, state) {
      if (name == "isAllowCrossDay") {
        if (state) {
          //edit_form.setItemLabel("crossDays","跨天数:<span class='dhxform_item_required'>*</span>")
          edit_form.setRequired("crossDays", true);
        }
        else {
          edit_form.setRequired("crossDays", false);
        }
      }
    });

    if (rdata) {
      rdata.consignorList = rdata.consignor ? JSON.stringify([rdata.consignor]) : "[]";
      edit_form.setFormData(rdata);
      edit_form.setText("consignorList", rdata.consignorname || "");
      edit_form.disableItem("companycode");
    }
    else {
      edit_form.enableItem("companycode");
      rdata = {};
    }
    if (type) {
      edit_form.disableAllItem();
    }

    //时间选择器
    plgDate.render({
      elem: "#unit_stime",
       type: "time",
       btns: ["now", "confirm"],
       value: rdata.serviceStartTime || "00:00:00"
    });
    plgDate.render({
      elem: "#unit_etime",
       type: "time",
       btns: ["now", "confirm"],
       value: rdata.serviceEndTime || "23:59:59"
    });
    plgDate.render({
      elem: "#unit_stime2",
       type: "time",
       value: rdata.serviceStartTime2 || "",
       done: function (value, date, endDate) {
        if (value == "") {
          $("#unit_stime2").val("00:00:00");
        }
      }
    });
    plgDate.render({
      elem: "#unit_etime2",
       type: "time",
       value: rdata.serviceEndTime2 || "",
       done: function (value, date, endDate) {
        if (value == "") {
          $("#unit_etime2").val("00:00:00");
        }
      }
    });
    plgDate.render({
      elem: "#unit_stime3",
       type: "time",
       value: rdata.serviceStartTime3 || "",
       done: function (value, date, endDate) {
        if (value == "") {
          $("#unit_stime3").val("00:00:00");
        }
      }
    });
    plgDate.render({
      elem: "#unit_etime3",
       type: "time",
       value: rdata.serviceEndTime3 || "",
       done: function (value, date, endDate) {
        if (value == "") {
          $("#unit_etime3").val("00:00:00");
        }
      }
    });
  }

  // 注册地址资料grid type:true-详情
  function editGridCreated(rdata, type) {
    $("#unitDataManage_edit_grid").html("");
    var edit_grid_opts = {
      skin: "card",
      columns: [
        { id: "addressid", name: "id", type: "ro", width: "130", hidden: true },
        { id: "companycode", name: "单位编号", type: "ro", width: 120 },
        { id: "companyname", name: "单位名称", type: "ro", width: 120 },
        { id: "addresscode", name: "地址编号", type: "ro", width: 120 },
        { id: "contactman", name: "收货人", type: "ro", width: 120 },
        { id: "contacttel", name: "联系方式", type: "ro", width: 120 },
        { id: "address", name: "详细地址", type: "ro", width: 120 },
        { id: "province", name: "省", type: "ro", width: 120 },
        { id: "city", name: "市", type: "ro", width: 120 },
        { id: "district", name: "区", type: "ro", width: 120 },
        { id: "town", name: "街道", type: "ro", width: 120 },
        { id: "longitude", name: "经度", type: "ro", width: 120 },
        { id: "latitude", name: "纬度", type: "ro", width: 120 },
        { id: "remark", name: "备注", type: "ro", width: 120 }
      ],
      fixedLast: !type, // 开启固定列，固定最后一行，倒数第二列不能隐藏
      multiselect: !type, // 是否支持多选

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

    if (!type) {
      edit_grid_opts.columns.push({
        id: "op", name: "操作", type: "button", align: "left", width: 150, fixed: "right", render: function () {
          return "修改^unitDataManage_editGrid_edit";
        }
      });
      edit_grid_opts.toolbar = [
        { type: "settings", labelWidth: 90, labelAlign: "right" },
        {
          type: "block", width: "*",
          list: [
            { type: "button", className: "btn-normal", name: "editGrid_add", value: "<i class='layui-icon layui-icon-add-1'></i>新 增" }
          ]
        }
      ];
      edit_grid_opts.pagebar = {
        buttons: [
          { text: "<i class='layui-icon layui-icon-delete'></i>删除", className: "plg-btn-normal", name: "editGrid_delete" }
        ]
      };
    }

    edit_grid = new PlgGrid(edit_grid_opts);
    edit_grid.renderTo("unitDataManage_edit_grid");
    if (rdata) {
      edit_grid.setParams(JSON.stringify({ companyid: rdata.companyid }));
      edit_grid.reload();
    }
    // 地址资料新增
    edit_grid.attachToolBarEvent("onButtonClick", function (name) {
      if (name === "editGrid_add") {
        let { companyid, companycode, companyname } = edit_form.getFormData();
        if (!companyid) {
          layer.msg("请先维护单位资料");
          return false;
        }
        addressDialogCreated({ companyid, companycode, companyname }, "add");
      }
    });
    // 地址资料删除
    edit_grid.attachPageBarEvent(function (name, ids) {
      if (name === "editGrid_delete") {
        let idList = ids.split(",").map(item => {
          return { id: item };
        });
        layer.open({
          title: "删除",
          content: "是否删除？",
          btn: ["确认", "取消"],
          yes: function () {
            let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
            Prolog.ajax({
              url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/pubAddress/deletePubAddress", type: "post", contentType: "application/json", data: JSON.stringify(idList),
              success: function (data) {
                PlgDialog.close(pload);
                if (data.success) {
                  layer.closeAll();
                  PlgDialog.msg(data.message);
                  edit_grid.reload();
                  return true;
                }
                    return false;

              }, error: function () { PlgDialog.close(pload); return false; }
            });
          }
        });
      }
    });
  }
  // 地址资料修改
  window.unitDataManage_editGrid_edit = function (rid) {
    let rdata = edit_grid.getRowData(rid);
    addressDialogCreated(rdata, "edit");
  };
  // 注册地址资料弹窗
  function addressDialogCreated(formData, type) {
    PlgDialog.open({
      title: (type === "edit" ? "修改" : "新增") + "地址",
      //offset: ["150px", "200px"],
      type: 1,
      shadeClose: false, //点击遮罩关闭
      content: "<div id=\"unitDataManage_addressDialog\" class=\"grid-container-full\" ></div>",
      area: ["1000px", "550px"],
      btn: ["保存", "取消"],
      yes: function () {
        let feik = dialog_form.validate();
        if (!feik) return;
        let request = dialog_form.getFormData();
        let url = type === "edit" ? UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/pubAddress/updatePubAddress" : UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/pubAddress/newPubAddress";
        savePubAddress(request, url);
      }
    });
    var dialog_form_opts = {
      renderer: "unitDataManage_addressDialog",
      items: [
        { type: "settings", PoSingle: "label-left", labelWidth: 70 },
        {
          type: "row",
          list: [
            { type: "input", className: "layui-col-md4 no-border", name: "companycode", label: "单位编号:", readonly: true },
            { type: "input", className: "layui-col-md4 no-border", name: "companyname", label: "单位名称:", readonly: true },
            { type: "input", className: "layui-col-md4", name: "addresscode", label: "地址编号:", required: true, disabled: type === "edit" ? true : false },
            { type: "combo", className: "layui-col-md4", name: "addresszone2", label: "省:", options: provinceEnums, readonly: true, required: true },
            { type: "hidden", name: "province", label: "省:" },
            { type: "combo", className: "layui-col-md4", name: "addresszone3", label: "市:", options: [], readonly: true, required: true },
            { type: "hidden", name: "city", label: "市:" },
            { type: "combo", className: "layui-col-md4", name: "addresszone4", label: "区/县:", options: [], readonly: true, required: true },
            { type: "hidden", name: "district", label: "区/县:" },
            { type: "combo", className: "layui-col-md4", name: "addresszone5", label: "街道/乡镇:", options: [], readonly: true, required: true },
            { type: "hidden", name: "town", label: "街道/乡镇:" },
            { type: "input", className: "layui-col-md8", name: "address", label: "详细地址:", required: true },
            { type: "input", className: "layui-col-md4", name: "contactman", label: "联系人:", required: true },
            { type: "input", className: "layui-col-md4", name: "contacttel", label: "联系方式:", required: true },
            { type: "input", className: "layui-col-md4", name: "longitude", label: "经度:" },
            { type: "input", className: "layui-col-md4", name: "latitude", label: "纬度:" }
          ]
        },
        {
          type: "row",
          list: [
            { type: "input", className: "layui-col-md12", name: "remark", label: "备注:", rows: 3 }
          ]
        }
      ]
    };
    dialog_form = new PlgForm(dialog_form_opts);
    if (type === "edit") {
      // 首先更新省市区下拉框数据
      getByPid(formData.addresszone2, "addresszone3", formData.addresszone3);
      getByPid(formData.addresszone3, "addresszone4", formData.addresszone4);
      getByPid(formData.addresszone4, "addresszone5", formData.addresszone5);
    }
    dialog_form.setFormData(formData);

    // 省市区联动
    dialog_form.attachComboEvent("addresszone2", "onChange", function (id) {
      dialog_form.setFormData({ province: dialog_form.getCombo("addresszone2").getComboText() });
      dialog_form.getCombo("addresszone3").setComboText("");
      if (id) {
        dialog_form.loadComboData("addresszone3", { url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/zone/get-by-pid", type: "post", contentType: "application/json", data: JSON.stringify({ "fatherid": id }), valueField: "zoneid", textField: "keyvalue" });
      }
      else {
        dialog_form.getCombo("addresszone3").clearAll();
      }
    });
    dialog_form.attachComboEvent("addresszone3", "onChange", function (id) {
      dialog_form.setFormData({ city: dialog_form.getCombo("addresszone3").getComboText() });
      dialog_form.getCombo("addresszone4").setComboText("");
      if (id) {
        dialog_form.loadComboData("addresszone4", { url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/zone/get-by-pid", type: "post", contentType: "application/json", data: JSON.stringify({ "fatherid": id }), valueField: "zoneid", textField: "keyvalue" });
      }
      else {
        dialog_form.getCombo("addresszone4").clearAll();
      }
    });
    dialog_form.attachComboEvent("addresszone4", "onChange", function (id) {
      dialog_form.setFormData({ district: dialog_form.getCombo("addresszone4").getComboText() });
      dialog_form.getCombo("addresszone5").setComboText("");
      if (id) {
        dialog_form.loadComboData("addresszone5", { url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/zone/get-by-pid", type: "post", contentType: "application/json", data: JSON.stringify({ "fatherid": id }), valueField: "zoneid", textField: "keyvalue" });
      }
      else {
        dialog_form.getCombo("addresszone5").clearAll();
      }
    });
    dialog_form.attachComboEvent("addresszone5", "onChange", function () {
      dialog_form.setFormData({ town: dialog_form.getCombo("addresszone5").getComboText() });
    });
  }
  // 省市区联动
  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赋下拉框数据
          dialog_form.getCombo(comboName).addOption(list);
          // 给combo赋值
          const nextData = {};
          nextData[comboName] = value;
          dialog_form.setFormData(nextData);
          return true;
        }
                return false;
      },
      error: function () { PlgDialog.close(pload); return false; }
    });
  }
  // 地址保存
  function savePubAddress(request, url) {
    let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url, type: "post", contentType: "application/json", data: JSON.stringify(request),
      success: function (res) {
        PlgDialog.close(pload);
        if (res.success) {
          layer.closeAll();
          PlgDialog.msg(res.message);
          edit_grid.setParams(JSON.stringify({ companyid: edit_form.getFormData().companyid }));
          edit_grid.reload();
          return true;
        }
                return false;
      }, error: function () { PlgDialog.close(pload); return false; }
    });
  }

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

    //获取时间
    formData.serviceStartTime = $("#unit_stime").val();
    formData.serviceEndTime = $("#unit_etime").val();
    formData.serviceStartTime2 = $("#unit_stime2").val();
    formData.serviceEndTime2 = $("#unit_etime2").val();
    formData.serviceStartTime3 = $("#unit_stime3").val();
    formData.serviceEndTime3 = $("#unit_etime3").val();

    //都是0点清空值
    if (formData.serviceStartTime2 == "00:00:00" && formData.serviceEndTime2 == "00:00:00") {
      formData.serviceStartTime2 = "";
      formData.serviceEndTime2 = "";
    }
    if (formData.serviceStartTime3 == "00:00:00" && formData.serviceEndTime3 == "00:00:00") {
      formData.serviceStartTime3 = "";
      formData.serviceEndTime3 = "";
    }

    console.log(formData);


    if (formData.companytype !== "H" && !formData.consignor) {
      layer.msg("单位类型为客户、供应商时货主不能为空");
      return false;
    }
    delete formData.consignorList;

    if (formData.crossDays && parseInt(formData.crossDays) < 0) {
      PlgDialog.msg("跨天数不能为负数");
      return;
    }

    if (formData.serviceTime && parseInt(formData.serviceTime) < 0) {
      PlgDialog.msg("交接货物时间不能为负数");
      return;
    }

    dealNullQueryCondition(formData);
    let url = $("#unitDataManage_edit_title").html() === "新增" ? UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/pubCompany/addPubCompany" : UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/pubCompany/updatePubCompany";
    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);
          if (res.data) edit_form.setFormData({ companyid: res.data.companyid });

          //master_grid.reload();
          //changePanel("#unitDataManage_main");
          return true;
        }
                return false;
      }, error: function () { PlgDialog.close(pload); return false; }
    });
  });
};