/*
* zzx
* 2020.05.25
* 订单录入
*    */
    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 orderEntry_form, orderEntry_grid;

  // 配送中心/站点table
  var branchTable = {
    // 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: 110 },
      {
        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/queryCompanyBranch",
    pagebar: { type: "simple" },
    type: "post", // 数据提交方式，默认为get
    params: JSON.stringify({ companytype: "S" }), // 查询提交参数，分页参数默认为pageNum,pageSize
    contentType: "application/json",
    page: true, // 是否启用分页
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  // 货主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
  };
  // 客户table
  var clientTable01 = {
    // 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/querySenderReceiver",
    pagebar: { type: "simple" },
    type: "post", // 数据提交方式，默认为get
    params: "{}", // 查询提交参数，分页参数默认为pageNum,pageSize
    contentType: "application/json",
    page: true, // 是否启用分页
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  var client_dialog_grid01 = new PlgGrid(clientTable01);
  // 个人table
  var clientTable02 = {
    // terrace显示全部，card分页显示
    skin: "card",
    // renderer:"grid",
    columns: [
      { id: "customerId", name: "id", type: "ro", width: "130", hidden: true },
      { id: "customerCode", name: "客户编号", type: "ro" },
      { id: "customerName", name: "客户名称", type: "ro" }
    ],
    multiselect: false,
    toolbar: [
      { type: "settings", position: "label-left", width: 200, labelWidth: 70 },
      {
        type: "block", id: "bk", blockOffset: 0, list: [
          { type: "input", name: "customerCode", label: "客户编码:", width: 120 },
          { type: "newcolumn", offset: 10 },
          { type: "input", name: "customerName", label: "客户名称:", width: 120 },
          { type: "newcolumn" },
          { type: "button", name: "querycarr", value: "查询" },
          { type: "newcolumn" },
          { type: "button", name: "car_Reset", value: "重置" }
        ]
      }
    ],

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/tBaseIndividualCustomer/queryPopup",
    pagebar: { type: "simple" },
    type: "post", // 数据提交方式，默认为get
    params: "{}", // 查询提交参数，分页参数默认为pageNum,pageSize
    contentType: "application/json",
    page: true, // 是否启用分页
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  var client_dialog_grid02 = new PlgGrid(clientTable02);
  // 商品table
  var itemTable = {
    // terrace显示全部，card分页显示
    skin: "card",
    // renderer:"grid",
    columns: [
      { id: "itemid", name: "id", type: "ro", width: "130", hidden: true },
      { id: "itemcode", name: "商品编码", type: "ro" },
      { id: "itemname", name: "商品名称", type: "ro" }
    ],
    toolbar: [
      { type: "settings", position: "label-left", width: 200, labelWidth: 100 },
      {
        type: "block", id: "bk", blockOffset: 0, list: [
          { type: "input", name: "itemcode", label: "商品编码:", width: 120 },
          { type: "newcolumn" },
          { type: "input", name: "itemname", label: "商品名称:", width: 120 },
          { type: "newcolumn" },
          { type: "button", name: "querycarr", value: "查询" },
          { type: "newcolumn" },
          { type: "button", name: "car_Reset", value: "重置" }
        ]
      }
    ],
    multiselect: false,

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/iteminfo/pop/v1.0",
    pagebar: { type: "simple" },
    type: "post", // 数据提交方式，默认为get
    params: "{}", // 查询提交参数，分页参数默认为pageNum,pageSize
    contentType: "application/json",
    page: true, // 是否启用分页
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  // 货品table
  var categoryTable = {
    // terrace显示全部，card分页显示
    skin: "card",
    // renderer:"grid",
    columns: [
      { id: "categoryId", name: "id", type: "ro", width: "130", hidden: true },
      { id: "categoryCode", name: "运输品类编号", type: "ro" },
      { id: "categoryName", name: "运输品类名称", type: "ro" }
    ],
    toolbar: [
      { type: "settings", position: "label-left", width: 200, labelWidth: 100 },
      {
        type: "block", id: "bk", blockOffset: 0, list: [
          { type: "input", name: "categoryCode", label: "运输品类编号:", width: 120 },
          { type: "newcolumn" },
          { type: "input", name: "categoryName", label: "运输品类名称:", width: 120 },
          { type: "newcolumn" },
          { type: "button", name: "querycarr", value: "查询" },
          { type: "newcolumn" },
          { type: "button", name: "car_Reset", value: "重置" }
        ]
      }
    ],
    multiselect: false,

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

  // 客户/个人弹窗事件
  function clientDialog(grid, type, valueName) {
    PlgDialog.open({
      title: "选择客户",
      shadeClose: true,
      type: 1, // 设置为1，手动控制dialog的开关
      area: ["650px", "500px"],
      content: "<div id =\"client_dialog\"></div>" //iframe的url
    });
    grid.renderTo("client_dialog");
    grid.reload();
    // 注册表格查询时间
    grid.attachToolBarEvent("onButtonClick", function (name) {
      switch (name) {
        case "querycarr":
          grid.setParams(JSON.stringify(grid.getToolBarForm().getFormData()));
          grid.reload();
          break;
        case "car_Reset":
          grid.getToolBarForm().clear();
          break;
      }
    });
    // 注册表格单击选择事件
    grid.on("onRowSelect", function () {
      let data = grid.getSelectedRowData();
      // 01-公司 02-个人
      // valueName shipper-发货人 arriver-收货人
      if (type === "01") {
        if (valueName === "shipper") {
          orderEntry_form.setFormData({
            shipperName: data.companyname,
            shipperId: data.companyid,
            shipperCode: data.companycode,
            shipoperator: data.contactman,
            shipoperatortel: data.tel,
            shipmentProvinceNo: data.province,
            shipmentProvinceName: data.provincename,
            shipmentCityNo: data.city,
            shipmentCityName: data.cityname,
            shipmentDistrictNo: data.area,
            shipmentDistrictName: data.areaname,
            shipmentTownNo: data.town,
            shipmentTownName: data.townname,
            shipmentAddress: data.address
          });

          // 更新省市区下拉框数据
          getByPid(data.province, "shipmentCityNo", data.city);
          getByPid(data.city, "shipmentDistrictNo", data.area);
          getByPid(data.area, "shipmentTownNo", data.town);
          getByPid(data.town, "shipmentCommunityNo", data.community);
        }
        else if (valueName === "arriver") {
          orderEntry_form.setFormData({
            arriverName: data.companyname,
            arriverId: data.companyid,
            arriverCode: data.companycode,
            consignee: data.contactman,
            consigneetel: data.tel,
            arriveProvinceNo: data.province,
            arriveProvinceName: data.provincename,
            arriveCityNo: data.city,
            arriveCityName: data.cityname,
            arriveDistrictNo: data.area,
            arriveDistrictName: data.areaname,
            arriveTownNo: data.town,
            arriveTownName: data.townname,
            arriveAddress: data.address
          });

          // 更新省市区下拉框数据
          getByPid(data.province, "arriveCityNo", data.city);
          getByPid(data.city, "arriveDistrictNo", data.area);
          getByPid(data.area, "arriveTownNo", data.town);
          getByPid(data.town, "arriveCommunityNo", data.community);
        }
      }
      else if (type === "02") {
        if (valueName === "shipper") {
          orderEntry_form.setFormData({
            shipperName: data.customerName,
            shipperId: data.customerId,
            shipperCode: data.customerCode,
            shipoperator: data.contactman,
            shipoperatortel: data.contacttel1,
            shipmentProvinceNo: data.province,
            shipmentProvinceName: data.provinceName,
            shipmentCityNo: data.city,
            shipmentCityName: data.cityName,
            shipmentDistrictNo: data.district,
            shipmentDistrictName: data.districtName,
            shipmentTownNo: data.street,
            shipmentTownName: data.streetName,
            shipmentAddress: data.address
          });

          // 更新省市区下拉框数据
          getByPid(data.province, "shipmentCityNo", data.city);
          getByPid(data.city, "shipmentDistrictNo", data.district);
          getByPid(data.district, "shipmentTownNo", data.street);
          getByPid(data.street, "shipmentCommunityNo", data.community);
        }
        else if (valueName === "arriver") {
          orderEntry_form.setFormData({
            arriverName: data.customerName,
            arriverId: data.customerId,
            arriverCode: data.customerCode,
            consignee: data.contactman,
            consigneetel: data.contacttel1,
            arriveProvinceNo: data.province,
            arriveProvinceName: data.provinceName,
            arriveCityNo: data.city,
            arriveCityName: data.cityName,
            arriveDistrictNo: data.district,
            arriveDistrictName: data.districtName,
            arriveTownNo: data.street,
            arriveTownName: data.streetName,
            arriveAddress: data.address
          });

          // 更新省市区下拉框数据
          getByPid(data.province, "arriveCityNo", data.city);
          getByPid(data.city, "arriveDistrictNo", data.district);
          getByPid(data.district, "arriveTownNo", data.street);
          getByPid(data.street, "arriveCommunityNo", data.community);
        }
      }
      layer.closeAll();
    });
  }

  // 获取枚举
  var dataSelect;
  getSelectGJ([
    { "objectcode": "TMS_SHIP_BILLTYPE" },
    { "objectcode": "TEMP_REQ" },
    { "objectcode": "GOODS_TYPE" },
    { "objectcode": "URG_FLG" },
    { "objectcode": "SEND_CUS_TYPE" },
    { "objectcode": "GET_CUS_TYPE" },
    { "objectcode": "ITEM_TYPE" }], function (data) {
      dataSelect = data.data;
      dataSelect.TMS_SHIP_BILLTYPE.unshift({ "value": "", "text": "" });
      dataSelect.TEMP_REQ.unshift({ "value": "", "text": "" });
      dataSelect.GOODS_TYPE.unshift({ "value": "", "text": "" });
      dataSelect.URG_FLG.unshift({ "value": "", "text": "" });
      dataSelect.SEND_CUS_TYPE.unshift({ "value": "", "text": "" });
      dataSelect.GET_CUS_TYPE.unshift({ "value": "", "text": "" });
    }
  );
  // 查询省
  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");

  // 表单
  var orderEntry_form_opts = {
    renderer: "orderEntry_form",
    items: [
      {
        type: "block", list: [
          { type: "settings", position: "label-left", labelWidth: 90, inputWidth: 190 },
          {
            type: "block", width: "*",
            list: [
              {
                width: 190,
                type: "selectTable",
                placeholder: "请选择配送中心/站点",
                readonly: false,
                table: branchTable,
                tableWidth: 600,
                tableHeight: 500,
                fieldText: "companyname",
                fieldValue: "companyid",
                name: "branchList",
                label: "配送中心/站点:<span class='dhxform_item_required'>*<span>",
                listener: {
                  "init": function (Grid) {
                    // 注册按钮事件
                    Grid.attachToolBarEvent("onButtonClick", function (name) {
                      switch (name) {
                        case "querycarr":
                          var { companycode } = Grid.getToolBarForm().getFormData();
                          Grid.setParams(JSON.stringify({ companycode, companytype: "S" }));
                          Grid.reload();
                          break;
                        case "car_Reset":
                          Grid.getToolBarForm().clear();
                          break;
                      }
                    });
                  },
                  "afterSelect": function (isSelected, selectId, sgrid) {
                    let sdata = sgrid.getRowData(selectId);
                    orderEntry_form.setFormData({
                      branchid: isSelected ? sdata.companyid : "",
                      branchcode: isSelected ? sdata.companycode : "",
                      branchname: isSelected ? sdata.companyname : ""
                    });
                  }
                }
              },
              { type: "hidden", name: "branchid", label: "当前仓ID:" },
              { type: "hidden", name: "branchcode", label: "当前仓编号:" },
              { type: "hidden", name: "branchname", label: "当前仓名称:" },
              { type: "newcolumn", offset: 40 },
              {
                width: 190,
                type: "selectTable",
                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 { companycode } = Grid.getToolBarForm().getFormData();
                          Grid.setParams(JSON.stringify({ companycode, companytype: "H" }));
                          Grid.reload();
                          break;
                        case "car_Reset":
                          Grid.getToolBarForm().clear();
                          break;
                      }
                    });
                  },
                  "afterSelect": function (isSelected, selectId, sgrid) {
                    let sdata = sgrid.getRowData(selectId);
                    orderEntry_form.setFormData({
                      consignor: isSelected ? sdata.companyid : "",
                      consignorcode: isSelected ? sdata.companycode : "",
                      consignorname: isSelected ? sdata.companyname : ""
                    });
                    // 切换货主，清空详情表
                    orderEntry_grid.clearAll();
                  }
                }
              },
              { type: "hidden", name: "consignor", label: "货主ID:" },
              { type: "hidden", name: "consignorcode", label: "货主编号:" },
              { type: "hidden", name: "consignorname", label: "货主名称:" },
              { type: "newcolumn", offset: 40 },
              { type: "combo", name: "billtype", label: "单据类型:", width: 190, options: dataSelect.TMS_SHIP_BILLTYPE, readonly: true, required: true }
            ]
          },
          {
            type: "block", width: "*",
            list: [
              { type: "combo", name: "temperatureRequire", label: "温度要求:", width: 190, options: dataSelect.TEMP_REQ, readonly: true, required: true },
              { type: "newcolumn", offset: 40 },
              { type: "combo", name: "shipgoodsgroup", label: "货物类型:", width: 190, options: dataSelect.GOODS_TYPE, readonly: true },
              { type: "newcolumn", offset: 40 },
              { type: "combo", name: "urgentIdentify", label: "紧急标识:", width: 190, options: dataSelect.URG_FLG, readonly: true, required: true }
            ]
          },
          {
            type: "block", width: "*",
            list: [
              { type: "calendar", name: "reqshipmentdate", label: "预计发货时间:", width: 190, required: true },
              { type: "newcolumn", offset: 40 },
              { type: "calendar", name: "reqarrivvaldate", label: "要求到货时间:", width: 190, required: true }
              // { type: "newcolumn", offset: 40 },
              // { type: "calendar", name: "billdate", label: "单据日期:", width: 190, readonly: true, required: true }
            ]
          },
          {
            type: "block", width: "*",
            list: [
              { type: "input", name: "memo", label: "备注:", inputWidth: 518, rows: 3 }
            ]
          }
        ]
      },
      {
        type: "fieldset", name: "shipperInfo", label: "发货人信息", list: [
          { type: "settings", position: "label-left", labelWidth: 90, inputWidth: 190 },
          {
            type: "block", width: "*",
            list: [
              { type: "combo", name: "shipperType", label: "客户类型:", width: 190, options: dataSelect.SEND_CUS_TYPE, readonly: true, required: true },
              { type: "newcolumn", offset: 40 },
              { type: "input", name: "shipperName", label: "发运客户:", placeholder: "请双击选择", readonly: true, required: true },
              { type: "hidden", name: "shipperId", label: "发运客户/个人id:" }
            ]
          },
          {
            type: "block", width: "*",
            list: [
              { type: "input", name: "shipoperator", label: "发运联系人:", required: true },
              { type: "newcolumn", offset: 40 },
              { type: "input", name: "shipoperatortel", label: "发运人电话:" },
              { type: "newcolumn", offset: 40 },
              { type: "input", name: "shipoperatormobile", label: "发运人手机:" }
            ]
          },
          {
            type: "block", width: "*",
            list: [
              { type: "combo", readonly: true, name: "shipmentProvinceNo", label: "省:", width: 190, options: provinceEnums },
              { type: "hidden", name: "shipmentProvinceName", label: "省:" },
              { type: "newcolumn", offset: 40 },
              { type: "combo", readonly: true, name: "shipmentCityNo", label: "市:", width: 190 },
              { type: "hidden", name: "shipmentCityName", label: "市:" },
              { type: "newcolumn", offset: 40 },
              { type: "combo", readonly: true, name: "shipmentDistrictNo", label: "区/县:", width: 190 },
              { type: "hidden", name: "shipmentDistrictName", label: "区/县:" }
            ]
          },
          {
            type: "block", width: "*",
            list: [
              { type: "combo", readonly: true, name: "shipmentTownNo", label: "街道/乡镇:", width: 190 },
              { type: "hidden", name: "shipmentTownName", label: "街道/乡镇:" },
              { type: "newcolumn", offset: 40 },
              { type: "combo", readonly: true, name: "shipmentCommunityNo", label: "村/社区:", width: 190 },
              { type: "hidden", name: "shipmentCommunityName", label: "村/社区:" }
            ]
          },
          {
            type: "block", width: "*",
            list: [
              { type: "input", name: "shipmentAddress", label: "详细地址:", inputWidth: 518 }
            ]
          }
        ]
      },
      {
        type: "fieldset", name: "arriverInfo", label: "收货人信息", list: [
          { type: "settings", position: "label-left", labelWidth: 90, inputWidth: 190 },
          {
            type: "block", width: "*",
            list: [
              { type: "combo", name: "arriverType", label: "客户类型:", width: 190, options: dataSelect.GET_CUS_TYPE, readonly: true },
              { type: "newcolumn", offset: 40 },
              { type: "input", name: "arriverName", label: "收货客户:", placeholder: "请双击选择", readonly: true },
              { type: "hidden", name: "arriverId", label: "收货客户/个人id:" }
            ]
          },
          {
            type: "block", width: "*",
            list: [
              { type: "input", name: "consignee", label: "收货联系人:" },
              { type: "newcolumn", offset: 40 },
              { type: "input", name: "consigneetel", label: "收货人电话:" },
              { type: "newcolumn", offset: 40 },
              { type: "input", name: "consigneemobile", label: "收货人手机:" }
            ]
          },
          {
            type: "block", width: "*",
            list: [
              { type: "combo", readonly: true, name: "arriveProvinceNo", label: "省:", width: 190, options: provinceEnums },
              { type: "hidden", name: "arriveProvinceName", label: "省:" },
              { type: "newcolumn", offset: 40 },
              { type: "combo", readonly: true, name: "arriveCityNo", label: "市:", width: 190 },
              { type: "hidden", name: "arriveCityName", label: "市:" },
              { type: "newcolumn", offset: 40 },
              { type: "combo", readonly: true, name: "arriveDistrictNo", label: "区/县:", width: 190 },
              { type: "hidden", name: "arriveDistrictName", label: "区/县:" }
            ]
          },
          {
            type: "block", width: "*",
            list: [
              { type: "combo", readonly: true, name: "arriveTownNo", label: "街道/乡镇:", width: 190 },
              { type: "hidden", name: "arriveTownName", label: "街道/乡镇:" },
              { type: "newcolumn", offset: 40 },
              { type: "combo", readonly: true, name: "arriveCommunityNo", label: "村/社区:", width: 190 },
              { type: "hidden", name: "arriveCommunityName", label: "村/社区:" }
            ]
          },
          {
            type: "block", width: "*",
            list: [
              { type: "input", name: "arriveAddress", label: "详细地址:", inputWidth: 518 }
            ]
          }
        ]
      }
    ]
  };

  formInit();

  // 注册form
  function formInit() {
    $("#orderEntry_form").html("");
    orderEntry_form = new PlgForm(orderEntry_form_opts);
    // 发运客户、收货客户点击事件
    $("#orderEntry_form input").on("dblclick", function (data) {
      let shipperType = orderEntry_form.getItemValue("shipperType");
      let arriverType = orderEntry_form.getItemValue("arriverType");
      // 01-公司 02-个人
      if (data.delegateTarget.name == "shipperName") {
        if (shipperType === "01") {
          clientDialog(client_dialog_grid01, shipperType, "shipper");
        }
        else if (shipperType === "02") {
          clientDialog(client_dialog_grid02, shipperType, "shipper");
        }
        else {
          layer.msg("请选择发货人客户类型");
        }
      }
      if (data.delegateTarget.name == "arriverName") {
        if (arriverType === "01") {
          clientDialog(client_dialog_grid01, arriverType, "arriver");
        }
        else if (arriverType === "02") {
          clientDialog(client_dialog_grid02, arriverType, "arriver");
        }
        else {
          layer.msg("请选择收货人客户类型");
        }
      }
    });

    // 客户类型修改时清空数据
    orderEntry_form.attachComboEvent("shipperType", "onChange", function (id) {
      orderEntry_form.setFormData({
        shipperName: "",
        shipperId: "",
        shipperCode: "",
        shipoperator: "",
        shipoperatortel: "",
        shipoperatormobile: "",
        shipmentProvinceNo: "",
        shipmentProvinceName: "",
        shipmentCityNo: "",
        shipmentCityName: "",
        shipmentDistrictNo: "",
        shipmentDistrictName: "",
        shipmentTownNo: "",
        shipmentTownName: "",
        shipmentCommunityNo: "",
        shipmentCommunityName: "",
        shipmentAddress: ""
      });
      orderEntry_form.getCombo("shipmentProvinceNo").setComboText("");
      orderEntry_form.getCombo("shipmentCityNo").setComboText("");
      orderEntry_form.getCombo("shipmentDistrictNo").setComboText("");
      orderEntry_form.getCombo("shipmentTownNo").setComboText("");
      orderEntry_form.getCombo("shipmentCommunityNo").setComboText("");
      orderEntry_form.setReadonly("shipperName", id === "01");
    });
    orderEntry_form.attachComboEvent("arriverType", "onChange", function (id) {
      orderEntry_form.setFormData({
        arriverName: "",
        arriverId: "",
        arriverCode: "",
        consignee: "",
        consigneetel: "",
        consigneemobile: "",
        arriveProvinceNo: "",
        arriveProvinceName: "",
        arriveCityNo: "",
        arriveCityName: "",
        arriveDistrictNo: "",
        arriveDistrictName: "",
        arriveTownNo: "",
        arriveTownName: "",
        arriveCommunityNo: "",
        arriveCommunityName: "",
        arriveAddress: ""
      });
      orderEntry_form.getCombo("arriveProvinceNo").setComboText("");
      orderEntry_form.getCombo("arriveCityNo").setComboText("");
      orderEntry_form.getCombo("arriveDistrictNo").setComboText("");
      orderEntry_form.getCombo("arriveTownNo").setComboText("");
      orderEntry_form.getCombo("arriveCommunityNo").setComboText("");
      orderEntry_form.setReadonly("arriverName", id === "01");
    });

    // 省市区联动
    orderEntry_form.attachComboEvent("shipmentProvinceNo", "onChange", function (id) {
      orderEntry_form.setFormData({ shipmentProvinceName: orderEntry_form.getCombo("shipmentProvinceNo").getComboText() });
      orderEntry_form.getCombo("shipmentCityNo").setComboText("");
      if (id) {
        orderEntry_form.loadComboData("shipmentCityNo", { 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 {
        orderEntry_form.getCombo("shipmentCityNo").clearAll();
      }
    });
    orderEntry_form.attachComboEvent("shipmentCityNo", "onChange", function (id) {
      orderEntry_form.setFormData({ shipmentCityName: orderEntry_form.getCombo("shipmentCityNo").getComboText() });
      orderEntry_form.getCombo("shipmentDistrictNo").setComboText("");
      if (id) {
        orderEntry_form.loadComboData("shipmentDistrictNo", { 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 {
        orderEntry_form.getCombo("shipmentDistrictNo").clearAll();
      }
    });
    orderEntry_form.attachComboEvent("shipmentDistrictNo", "onChange", function (id) {
      orderEntry_form.setFormData({ shipmentDistrictName: orderEntry_form.getCombo("shipmentDistrictNo").getComboText() });
      orderEntry_form.getCombo("shipmentTownNo").setComboText("");
      if (id) {
        orderEntry_form.loadComboData("shipmentTownNo", { 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 {
        orderEntry_form.getCombo("shipmentTownNo").clearAll();
      }
    });
    orderEntry_form.attachComboEvent("shipmentTownNo", "onChange", function (id) {
      orderEntry_form.setFormData({ shipmentTownName: orderEntry_form.getCombo("shipmentTownNo").getComboText() });
      orderEntry_form.getCombo("shipmentCommunityNo").setComboText("");
      if (id) {
        orderEntry_form.loadComboData("shipmentCommunityNo", { 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 {
        orderEntry_form.getCombo("shipmentCommunityNo").clearAll();
      }
    });
    orderEntry_form.attachComboEvent("shipmentCommunityNo", "onChange", function () {
      orderEntry_form.setFormData({ shipmentCommunityName: orderEntry_form.getCombo("shipmentCommunityNo").getComboText() });
    });

    orderEntry_form.attachComboEvent("arriveProvinceNo", "onChange", function (id) {
      orderEntry_form.setFormData({ arriveProvinceName: orderEntry_form.getCombo("arriveProvinceNo").getComboText() });
      orderEntry_form.getCombo("arriveCityNo").setComboText("");
      if (id) {
        orderEntry_form.loadComboData("arriveCityNo", { 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 {
        orderEntry_form.getCombo("arriveCityNo").clearAll();
      }
    });
    orderEntry_form.attachComboEvent("arriveCityNo", "onChange", function (id) {
      orderEntry_form.setFormData({ arriveCityName: orderEntry_form.getCombo("arriveCityNo").getComboText() });
      orderEntry_form.getCombo("arriveDistrictNo").setComboText("");
      if (id) {
        orderEntry_form.loadComboData("arriveDistrictNo", { 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 {
        orderEntry_form.getCombo("arriveDistrictNo").clearAll();
      }
    });
    orderEntry_form.attachComboEvent("arriveDistrictNo", "onChange", function (id) {
      orderEntry_form.setFormData({ arriveDistrictName: orderEntry_form.getCombo("arriveDistrictNo").getComboText() });
      orderEntry_form.getCombo("arriveTownNo").setComboText("");
      if (id) {
        orderEntry_form.loadComboData("arriveTownNo", { 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 {
        orderEntry_form.getCombo("arriveTownNo").clearAll();
      }
    });
    orderEntry_form.attachComboEvent("arriveTownNo", "onChange", function (id) {
      orderEntry_form.setFormData({ arriveTownName: orderEntry_form.getCombo("arriveTownNo").getComboText() });
      orderEntry_form.getCombo("arriveCommunityNo").setComboText("");
      if (id) {
        orderEntry_form.loadComboData("arriveCommunityNo", { 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 {
        orderEntry_form.getCombo("arriveCommunityNo").clearAll();
      }
    });
    orderEntry_form.attachComboEvent("arriveCommunityNo", "onChange", function () {
      orderEntry_form.setFormData({ arriveCommunityName: orderEntry_form.getCombo("arriveCommunityNo").getComboText() });
    });
  }

  // 表格
  var orderEntry_grid_opts = {
    skin: "card",
    columns: [
      { id: "id", name: "id", type: "ro", width: "130", hidden: true },
      { id: "itemtype", name: "<span style='color:#096dd9;'>货品类型</span>", type: "coro" }, // 3
      { id: "itemid", name: "<span style='color:#096dd9;'>货物ID</span>", type: "ro" }, // 4
      { id: "itemname", name: "货物名称", type: "ro" }, // 5
      { id: "pcs", name: "<span style='color:#096dd9;'>件数</span>", type: "ed" }, // 6
      { id: "weight", name: "<span style='color:#096dd9;'>重量</span>", type: "ed" }, // 7
      { id: "vol", name: "<span style='color:#096dd9;'>体积</span>", type: "ed" }, // 8
      { id: "itemno", name: "货品code", type: "ed", hidden: true } // 9
    ],
    toolbar: [
      { type: "button", name: "grid_add", className: "plg-toolbar-right ", 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: false, // 开启固定列，固定最后一行，倒数第二列不能隐藏
    multiselect: true, // 是否支持多选

    url: "/omsbusiness/instockOrder/searchDetailList/v1.0", // 数据接口
    type: "post", // 数据提交方式，默认为get
    params: "{}", // 查询提交参数，分页参数默认为pageNum,pageSize
    page: false, // 是否启用分页
    contentType: "application/json",
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };

  gridInit();

  // 注册grid
  function gridInit() {
    $("#orderEntry_grid").html("");
    orderEntry_grid = new PlgGrid(orderEntry_grid_opts);
    orderEntry_grid.renderTo("orderEntry_grid");
    // 表格编辑资源
    orderEntry_grid.getGrid().enableEditEvents(true, false, true);
    // 下拉赋值
    let combo_1 = orderEntry_grid.getGrid().getCombo(3);
    dataSelect.ITEM_TYPE.forEach(v => {
      combo_1.put(v.value, v.text);
    });
    // 表格新增事件
    orderEntry_grid.attachToolBarEvent("onButtonClick", function () {
      let { branchid, branchname, consignor, consignorname } = orderEntry_form.getFormData();
      if (!consignor) {
        layer.msg("请先选择货主");
        return;
      }
      let id = Math.random();
      let rowData = {
        branchid,
        branchname,
        consignor,
        consignorname
      };
      orderEntry_grid.addRow(id, rowData);
    });
    // 表格单击事件
    orderEntry_grid.on("onRowSelect", function (id, index) {
      let { itemtype } = orderEntry_grid.getRowData(id);
      if (index === 4) {
        // 01-商品 02-货品
        if (!itemtype) {
          layer.msg("请选择货品类型");
          return false;
        }
        PlgDialog.open({
          title: "选择" + (itemtype === "01" ? "商品" : "货品"),
          shadeClose: true,
          type: 1, // 设置为1，手动控制dialog的开关
          area: ["850px", "500px"],
          content: "<div id =\"item_dialog\"></div>" //iframe的url
        });
        $(".layui-layer-btn0").hide();
        // 注册商品、货品
        let item_grid = new PlgGrid(itemtype === "01" ? itemTable : categoryTable);
        item_grid.renderTo("item_dialog");
        let consignor = orderEntry_form.getFormData().consignor;
        item_grid.setParams(JSON.stringify({ consignor }));
        item_grid.attachToolBarEvent("onButtonClick", function (name) {
          switch (name) {
            case "querycarr":
              var request = item_grid.getToolBarForm().getFormData();
              item_grid.setParams(JSON.stringify(Object.assign({}, request, { consignor })));
              item_grid.reload();
              break;
            case "car_Reset":
              item_grid.getToolBarForm().clear();
              break;
          }
        });
        item_grid.reload();
        // 单击选择事件
        item_grid.on("onRowSelect", function () {
          let data = item_grid.getSelectedRowData();
          orderEntry_grid.setCellValue(id, 4, itemtype === "01" ? data.itemid : data.categoryId);
          orderEntry_grid.setCellValue(id, 5, itemtype === "01" ? data.itemname : data.categoryName);
          orderEntry_grid.setCellValue(id, 9, itemtype === "01" ? data.itemcode : data.categoryCode);
          layer.closeAll();
        });
      }
    });
    // 编辑离开校验
    orderEntry_grid.attachEvent("onEditCell", function (stage, rId, cInd, nValue, oValue) {
      let positiveInteger = /^[1-9]\d*$/; // 正整数
      let positveOrZero = /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/; // 非负数
      if (stage === 2) {
        if (cInd === 3 && nValue !== oValue) {
          orderEntry_grid.setCellValue(rId, cInd, nValue);
          orderEntry_grid.setCellValue(rId, 4, "");
          orderEntry_grid.setCellValue(rId, 5, "");
          orderEntry_grid.setCellValue(rId, 6, "");
          orderEntry_grid.setCellValue(rId, 7, "");
          orderEntry_grid.setCellValue(rId, 8, "");
          orderEntry_grid.setCellValue(rId, 9, "");
        }
        else if (cInd === 6) { // 件数
          if (!positiveInteger.test(Number(nValue))) {
            layer.msg("请输入正整数");
            return;
          }
          orderEntry_grid.setCellValue(rId, 6, Number(nValue));
        }
        else if (cInd === 7 || cInd === 8) {
          if (!positveOrZero.test(nValue)) {
            layer.msg("请输入正数");
            return;
          }
          orderEntry_grid.setCellValue(rId, cInd, Number(nValue));
        }
        else {
          orderEntry_grid.setCellValue(rId, cInd, nValue);
        }
      }
      return true;
    });
    // 删除
    orderEntry_grid.attachPageBarEvent(function (name, ids) {
      layer.open({
        title: "删除",
        content: "还未保存，是否删除？",
        btn: ["确认", "取消"],
        yes: function () {
          ids.split(",").forEach(id => {
            orderEntry_grid.deleteRow(id);
          });
          layer.closeAll();
        }
      });
    });
  }

  // 保存
  $("#orderEntry_save").on("click", function () {
    let vdate = orderEntry_form.validate();
    if (!vdate) return false;

    let telValidate = /^[0][1-9]{2,3}-[0-9]{5,10}$/; // 座机正则
    let phoneValidate = /^1\d{10}$/; // 手机号校验

    let tmsOrderBillHVo = orderEntry_form.getFormData();
    if (!tmsOrderBillHVo.shipperName) {
      layer.msg("发货人信息不能为空");
      return false;
    }
    if (tmsOrderBillHVo.billtype !== "02" && (!tmsOrderBillHVo.arriverName || !tmsOrderBillHVo.arriveProvinceNo || !tmsOrderBillHVo.arriveCityNo || !tmsOrderBillHVo.arriveDistrictNo || !tmsOrderBillHVo.arriveAddress)) {
      layer.msg("单据类型不为提货入库时，请选择收货人、地址相关信息不能为空");
      return false;
    }
    if (tmsOrderBillHVo.billtype === "02" && (!tmsOrderBillHVo.shipmentProvinceNo || !tmsOrderBillHVo.shipmentCityNo || !tmsOrderBillHVo.shipmentDistrictNo || !tmsOrderBillHVo.shipmentAddress)) {
      layer.msg("单据类型不为配送类型时，发货人地址相关信息不能为空");
      return false;
    }
    if (!tmsOrderBillHVo.shipoperatortel && !tmsOrderBillHVo.shipoperatormobile || !tmsOrderBillHVo.consigneetel && !tmsOrderBillHVo.consigneemobile) {
      layer.msg("联系人电话，联系人手机不能同时为空");
      return false;
    }
    if (tmsOrderBillHVo.shipoperatortel && !telValidate.test(tmsOrderBillHVo.shipoperatortel) && !phoneValidate.test(tmsOrderBillHVo.shipoperatortel)) {
      layer.msg("请输入正确的发运人电话");
      return false;
    }
    if (tmsOrderBillHVo.shipoperatormobile && !telValidate.test(tmsOrderBillHVo.shipoperatormobile) && !phoneValidate.test(tmsOrderBillHVo.shipoperatormobile)) {
      layer.msg("请输入正确的发运人手机");
      return false;
    }
    if (tmsOrderBillHVo.consigneetel && !telValidate.test(tmsOrderBillHVo.consigneetel) && !phoneValidate.test(tmsOrderBillHVo.consigneetel)) {
      layer.msg("请输入正确的收货人电话");
      return false;
    }
    if (tmsOrderBillHVo.consigneemobile && !telValidate.test(tmsOrderBillHVo.consigneemobile) && !phoneValidate.test(tmsOrderBillHVo.consigneemobile)) {
      layer.msg("请输入正确的收货人手机");
      return false;
    }

    tmsOrderBillHVo.reqshipmentdate = tmsOrderBillHVo.reqshipmentdate ? Prolog.formatDate(tmsOrderBillHVo.reqshipmentdate) : "";
    tmsOrderBillHVo.reqarrivvaldate = tmsOrderBillHVo.reqarrivvaldate ? Prolog.formatDate(tmsOrderBillHVo.reqarrivvaldate) : "";
    // tmsOrderBillHVo.billdate = tmsOrderBillHVo.billdate ? Prolog.formatDate(tmsOrderBillHVo.billdate) : "";
    dealNullQueryCondition(tmsOrderBillHVo);
    delete tmsOrderBillHVo.branchList;
    delete tmsOrderBillHVo.consignorList;

    let list = [];
    let indexNum = orderEntry_grid.getGrid().getRowsNum();
    for (let i = 0; i < indexNum; i++) {
      const element = orderEntry_grid.getRowData(orderEntry_grid.getRowId(i));
      if (!element.itemtype || !element.itemid || !element.pcs || !element.weight || !element.vol) {
        layer.msg("请填写完整的货品信息");
        return false;
      }
      list.push(element);
    }

    let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/tmsOrderManage/tmsOrderSave", type: "post", contentType: "application/json", data: JSON.stringify({ tmsOrderBillHVo, list }),
      success: function (res) {
        PlgDialog.close(pload);
        if (res.success) {
          PlgDialog.msg(res.message);
          orderEntry_form.clear();
          orderEntry_form.setText("branchList", "");
          orderEntry_form.setText("consignorList", "");
          orderEntry_grid.clearAll();
          return true;
        }
                return false;

      }, error: function () { PlgDialog.close(pload); return false; }
    });
  });
  // 重置
  $("#orderEntry_reset").on("click", function () {
    formInit();
    gridInit();
  });

  // 省市区联动
  function getByPid(fatherid, comboName, value) {
    if (fatherid) {
      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赋下拉框数据
            orderEntry_form.getCombo(comboName).addOption(list);
            // 给combo赋值
            const nextData = {};
            nextData[comboName] = value;
            orderEntry_form.setFormData(nextData);
            return true;
          }
                    return false;
        },
        error: function () { PlgDialog.close(pload); return false; }
      });
    }
  }
};