/**
 * zzx
 * 2020.10.13
 * 派车确认
 */
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, details_grid, add_grid1_opts, add_grid1, add_grid2_opts, add_grid2, edit_form_opts, edit_form;
  var selectedMasterGridData;
var userinfo = {
  p_id: '',
  p_username: '',
  p_workernumber: '',
  p_nickname: '',
  p_phone: null,
  p_email: null,
  p_companyid: '',
  p_enterpriseid: '',
  p_organizationid: '',
  p_companyname: '',
  p_orgname: '',
  p_enterprisename: '',
  p_usertype: '',
  p_lastlogindate: '',
  p_lastmodipassdate: null,
  p_validdate: '',
  p_import_batchno: null,
  p_data_source: null,
  forceModifyPasswdFlag: false,
  vehicle: null,
}

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

  // 获取默认时间
  var startTime = Prolog.formatDate(new Date(), "%YY-%MM") + "-01 00:00:00";
  var endTime = Prolog.formatDate(new Date()) + " 23:59:59";
  // 获取下拉框
  var dataSelect = {
    TMS_SHIP_BILLTYPE: [],
    GET_CUS_TYPE: [],
    URG_FLG: []
  };
  getSelectGJ([
    { "objectcode": "TMS_SHIP_BILLTYPE" },
    { "objectcode": "GET_CUS_TYPE" },
    { "objectcode": "URG_FLG" }
  ], function (data) {
    dataSelect = data.data;
    dataSelect.TMS_SHIP_BILLTYPE.unshift({ "value": "", "text": "" });
  });

  // 承运商table
  var carrierTable = {
    // 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: 70 },
      {
        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/queryCompanyCarrier",
    pagebar: { type: "simple" },
    type: "post", // 数据提交方式，默认为get
    params: JSON.stringify({ companytype: "Y" }), // 查询提交参数，分页参数默认为pageNum,pageSize
    contentType: "application/json",
    page: true, // 是否启用分页
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  // 客户table
  var customerTable = {
    // 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: 70 },
      {
        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/queryCompanyCustomer",
    pagebar: { type: "simple" },
    type: "post", // 数据提交方式，默认为get
    params: JSON.stringify({ companytype: "C" }), // 查询提交参数，分页参数默认为pageNum,pageSize
    contentType: "application/json",
    page: true, // 是否启用分页
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  // 线路table
  var lineTable = {
    // terrace显示全部，card分页显示
    skin: "card",
    // renderer:"grid",
    columns: [
      { id: "lineId", name: "id", type: "ro", width: "130", hidden: true },
      { id: "branchName", name: "配送中心/站点", type: "ro" },
      { id: "lineCode", name: "线路编号", type: "ro" },
      { id: "lineName", name: "线路名称", type: "ro" },
      { id: "lineTypename", 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: "lineCode", label: "线路编号:", width: 120 },
          { type: "newcolumn" },
          { type: "input", name: "lineName", label: "线路名称:", width: 120 },
          { type: "newcolumn" },
          { type: "button", name: "querycarr", value: "查询" },
          { type: "newcolumn" },
          { type: "button", name: "car_Reset", value: "重置" }
        ]
      }
    ],
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/tBaseTransline/queryTBaseTransline",
    pagebar: { type: "simple" },
    type: "post", // 数据提交方式，默认为get
    params: "{}", // 查询提交参数，分页参数默认为pageNum,pageSize
    contentType: "application/json",
    page: true, // 是否启用分页
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  // 车牌号table
  var vehicleTable = {
    skin: "card",
    columns: [
      { id: "id", name: "id", type: "ro", width: "130", hidden: true },
      { id: "vehicleNo", name: "车牌号", type: "ro" },
      { id: "vehicleName", name: "车辆名称", type: "ro" }
    ],
    multiselect: false,
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/tBaseBranchVehicle/branchVehiclePopupQuery",
    type: "post",
    pagebar: { type: "simple" },
    contentType: "application/json",
    params: "{}",
    page: true,
    totalCount: "totalCount"
  };
  // 司机table
  var driverTable = {
    skin: "card",
    columns: [
      { id: "driverId", name: "司机编号", type: "ro" },
      { id: "driverName", name: "司机名称", type: "ro" },
      { id: "tel", name: "手机号", type: "ro" },
      { id: "card", name: "身份证号", type: "ro" }
    ],
    toolbar: [
      { type: "settings", position: "label-left", width: 200, labelWidth: 70 },
      {
        type: "block", id: "bk", blockOffset: 0, list: [
          { type: "input", name: "driverName", 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+"/tBaseBranchDriver/queryDispatchDriver",
    type: "post",
    pagebar: { type: "simple" },
    contentType: "application/json",
    params: "{}",
    page: true,
    totalCount: "totalCount"
  };

  // 司机(副)table
  var driverTable2 = {
    skin: "card",
    columns: [
      { id: "driverId", name: "司机编号", type: "ro" },
      { id: "driverName", name: "司机名称", type: "ro" },
      { id: "tel", name: "手机号", type: "ro" },
      { id: "card", name: "身份证号", type: "ro" }
    ],
    toolbar: [
      { type: "settings", position: "label-left", width: 200, labelWidth: 70 },
      {
        type: "block", id: "bk", blockOffset: 0, list: [
          { type: "input", name: "driverName", 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+"/tBaseBranchDriver/queryDispatchDriver",
    type: "post",
    pagebar: { type: "simple" },
    contentType: "application/json",
    params: "{}",
    page: true,
    totalCount: "totalCount"
  };

  // 打印弹窗
  function print() {
    PlgDialog.open({
      title: "打印",
      shadeClose: true,
      type: 1, // 设置为1，手动控制dialog的开关
      area: ["900px", "650px"],
      content: "<div id =\"dispatchConfirm_dialog\"></div>" //iframe的url
    });
    let dialog_grid_opts = {
      skin: "card",
      columns: [
        { id: "loadbillid", name: "装车单id", type: "ro", width: 120, hidden: true },
        { id: "branchid", name: "机构号", type: "ro", width: 120, hidden: true },
        { id: "branchname", name: "机构名称", type: "ro", width: 120, hidden: true },
        { id: "loadbillno", name: "装车单号", type: "ro", width: 150 },
        { id: "billdate", name: "单据日期", type: "ro", width: 120 },
        { id: "carrierid", name: "承运商", type: "ro", width: 120, hidden: true },
        { id: "carrierno", name: "承运商编号", type: "ro", width: 120, hidden: true },
        { id: "carriername", name: "承运商名称", type: "ro", width: 120, hidden: true },
        { id: "voucherno", name: "车牌号", type: "ro", width: 120 },
        { id: "vouchernane", name: "运输工具名称", type: "ro", width: 120, hidden: true },
        { id: "driver1st", name: "司机id", type: "ro", width: 120, hidden: true },
        { id: "driver1stname", name: "司机名称", type: "ro", width: 120 },
        { id: "dirver2nd", name: "副驾驶id", type: "ro", width: 120, hidden: true },
        { id: "dirver2ndname", name: "副驾驶名称", type: "ro", width: 120 },
        { id: "distperson1", name: "配送员id", type: "ro", width: 120, hidden: true },
        { id: "distperson1name", name: "配送员名称", type: "ro", width: 120 },
        { id: "distperson2", name: "副配送员id", type: "ro", width: 120, hidden: true },
        { id: "distperson2name", name: "副配送员名称", type: "ro", width: 120 },
        { id: "dispatcher", name: "调度员id", type: "ro", width: 120, hidden: true },
        { id: "stoppointnum", name: "停靠站点数", type: "ro", width: 120 },
        { id: "shipmentNumber", name: "配送装载件数", type: "ro", width: 120 },
        { id: "shipmentVol", name: "配送装载体积", type: "ro", width: 120 },
        { id: "shipmentWeight", name: "配送装载重量", type: "ro", width: 120 },
        { id: "loadingRateVol", name: "配送体积装载率", type: "ro", width: 120 },
        { id: "loadingRateWeight", name: "配送重量装载率", type: "ro", width: 120 },
        { id: "remark", name: "备注", type: "ro", width: 120 }
      ],
      toolbar: [
        { type: "settings", labelWidth: 60, labelAlign: "right" },
        {
          type: "row",
          list: [
            { type: "calendar", className: "layui-col-md4", name: "startdate", label: "开始时间:", value: startTime },
            { type: "calendar", className: "layui-col-md4", name: "enddate", label: "结束时间:", value: endTime },
            { type: "input", className: "layui-col-md4", name: "loadbillno", label: "装车单号:" },
            {
              type: "selectTable",
              className: "layui-col-md4",
              placeholder: "请选择承运商",
              readonly: false,
              table: carrierTable,
              tableWidth: 600,
              tableHeight: 500,
              fieldText: "companyname",
              fieldValue: "companyid",
              name: "carrieridList",
              label: "承运商:",
              listener: function (Grid) {
                setMethod(Grid, carrierTable, function () { });
              }
            },
            {
              type: "block", className: "layui-col-md4 form_btn_left",
              list: [
                { type: "button", className: "btn-normal", name: "search", value: "查 询" },
                { type: "newcolumn" },
                { type: "button", name: "reset", value: "重 置" }
              ]
            },
            {
              type: "block", className: "layui-col-md4 right",
              list: [
                { type: "button", className: "btn-normal", name: "print", value: "打 印" }
              ]
            }
          ]
        }
      ],
      multiselect: false,
        url: "business/dispatchConfirmation/summaryQueryByPage/v1.0",
      pagebar: { type: "simple" },
      type: "post",
      params: JSON.stringify({ startdate: startTime, enddate: endTime }),
      contentType: "application/json",
      page: true,
      totalCount: "totalCount"
    };
    let dialog_grid = new PlgGrid(dialog_grid_opts);
    dialog_grid.renderTo("dispatchConfirm_dialog");
    dialog_grid.reload();
    dialog_grid.attachToolBarEvent("onButtonClick", function (name) {
      switch (name) {
        case "search":
          var request = dialog_grid.getToolBarForm().getFormData();
          request.startdate = request.startdate ? Prolog.formatDate(request.startdate) + " 00:00:00" : "";
          request.enddate = request.enddate ? Prolog.formatDate(request.enddate) + " 23:59:59" : "";
          if (request.startdate > request.enddate) {
            layer.msg("开始时间不能大于结束时间");
            return false;
          }
          request.carrierid = request.carrieridList ? JSON.parse(request.carrieridList)[0] : "";
          dealNullQueryCondition(request);
          delete request.carrieridList;
          dialog_grid.setParams(JSON.stringify(request));
          dialog_grid.reload();
          break;
        case "reset":
          dialog_grid.getToolBarForm().clear();
          dialog_grid.getToolBarForm().setFormData({ startdate: startTime, enddate: endTime });
          dialog_grid.getToolBarForm().setText("carrieridList", "");
          break;
        case "print":
          var data = dialog_grid.getSelectedRowData();
          if (!data) {
            layer.msg("请选择一行数据");
            return false;
          }
          dispatchConfirmationPrint({ loadbillno: data.loadbillno, loadbillid: data.loadbillid });
          break;
      }
    });
  }
  function dispatchConfirmationPrint(params) {
    var pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url: "business/dispatchConfirmation/print", type: "post", contentType: "application/json", data: JSON.stringify(params),
      success: function (res) {
        PlgDialog.close(pload);
        if (res.success) {
          if (!res.data || !Object.keys(res.data).length) {
            setTimeout(() => { PlgDialog.msg("该报表没有数据"); }, 300);
            return false;
          }
          res.data.printSolution = "";
          // res.data.printName = "127.0.0.1";
          PrintService("", res.data, function (rsp) {
            if (!rsp) {
              setTimeout(() => { PlgDialog.msg("打印失败"); }, 300);
              return;
            }
            setTimeout(() => { PlgDialog.alert(rsp.message || "打印失败"); }, 300);
          });
          return true;
        }
                return false;

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

  // 主表grid
  var master_grid_opts = {
    skin: "card",
    columns: [
      { id: "loadbillid", name: "装车单id", type: "ro", width: 120, hidden: true },
      { id: "branchid", name: "机构号", type: "ro", width: 120, hidden: true },
      { id: "branchname", name: "机构名称", type: "ro", width: 120, hidden: true },
      { id: "loadbillno", name: "装车单号", type: "ro", width: 150 },
      { id: "billdate", name: "单据日期", type: "ro", width: 120 },
      { id: "carrierid", name: "承运商", type: "ro", width: 120, hidden: true },
      { id: "carrierno", name: "承运商编号", type: "ro", width: 120, hidden: true },
      { id: "carriername", name: "承运商名称", type: "ro", width: 120, hidden: true },
      { id: "voucherno", name: "车牌号", type: "ro", width: 120 },
      { id: "vouchernane", name: "运输工具名称", type: "ro", width: 120, hidden: true },
      { id: "driver1st", name: "司机id", type: "ro", width: 120, hidden: true },
      { id: "driver1stname", name: "司机名称", type: "ro", width: 120 },
      { id: "dirver2nd", name: "副驾驶id", type: "ro", width: 120, hidden: true },
      { id: "dirver2ndname", name: "副驾驶名称", type: "ro", width: 120 },
      { id: "distperson1", name: "配送员id", type: "ro", width: 120, hidden: true },
      { id: "distperson1name", name: "配送员名称", type: "ro", width: 120 },
      { id: "distperson2", name: "副配送员id", type: "ro", width: 120, hidden: true },
      { id: "distperson2name", name: "副配送员名称", type: "ro", width: 120 },
      { id: "dispatcher", name: "调度员id", type: "ro", width: 120, hidden: true },
      { id: "stoppointnum", name: "停靠站点数", type: "ro", width: 120 },
      { id: "shipmentNumber", name: "配送装载件数", type: "ro", width: 120 },
      { id: "shipmentVol", name: "配送装载体积", type: "ro", width: 120 },
      { id: "shipmentWeight", name: "配送装载重量", type: "ro", width: 120 },
      { id: "loadingRateVol", name: "配送体积装载率", type: "ro", width: 120 },
      { id: "loadingRateWeight", name: "配送重量装载率", type: "ro", width: 120 },
      { id: "remark", name: "备注", type: "ro", width: 120 },
      // {
      //   id: "status", name: "状态", type: "ro", width: 120, render: function (v) {
      //     return getSelectValue(dataSelect.AUDIT_STATUS, v);
      //   }
      // },
      {
        id: "op", name: "操作", type: "button", align: "left", fixed: "right", width: "100", render: function () {
          return "新增^dispatchConfirm_add,修改^dispatchConfirm_edit";
        }
      }
    ],
    toolbar: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          { type: "calendar", className: "layui-col-md3", name: "startdate", label: "开始时间:", value: startTime },
          { type: "calendar", className: "layui-col-md3", name: "enddate", label: "结束时间:", value: endTime },
          { type: "input", className: "layui-col-md3", name: "loadbillno", label: "装车单号:" },
          {
            type: "selectTable",
            className: "layui-col-md3",
            placeholder: "请选择承运商",
            readonly: false,
            table: carrierTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "companyname",
            fieldValue: "companyid",
            name: "carrieridList",
            label: "承运商:",
            listener: function (Grid) {
              setMethod(Grid, carrierTable, function () { });
            }
          },
          {
            type: "block", className: "layui-col-md3 form_btn_left",
            list: [
              { type: "button", className: "btn-normal", name: "master_search", value: "查 询" },
              { type: "newcolumn" },
              { type: "button", name: "master_reset", value: "重 置" }
            ]
          },
          {
            type: "block", className: "layui-col-md9 right",
            list: [
              { type: "button", className: "btn-normal", name: "master_confirm", value: "派车确认" },
              { type: "newcolumn" },
              { type: "button", className: "btn-normal", name: "master_print", value: "派车单打印" }
            ]
          }
        ]
      }
    ],
    fixedLast: true, // 开启固定列，固定最后一行，倒数第二列不能隐藏
    multiselect: true, // 是否支持多选
    url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/dispatchConfirmation/summaryQuery/v1.0", // 数据接口
    type: "post", // 数据提交方式，默认为get
    params: JSON.stringify({ startdate: startTime, enddate: endTime, status: 10 }), // 查询提交参数，分页参数默认为pageNum,pageSize
    page: false, // 是否启用分页
    contentType: "application/json",
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  master_grid = new PlgGrid(master_grid_opts);
  master_grid.renderTo("dispatchConfirm_master");
  master_grid.loadData();
  master_grid.attachToolBarEvent("onButtonClick", function (name) {
    var ids = master_grid.getCheckedIds();
    switch (name) {
      case "master_search":
        var request = master_grid.getToolBarForm().getFormData();
        request.startdate = request.startdate ? Prolog.formatDate(request.startdate) + " 00:00:00" : "";
        request.enddate = request.enddate ? Prolog.formatDate(request.enddate) + " 23:59:59" : "";
        if (request.startdate > request.enddate) {
          layer.msg("开始时间不能大于结束时间");
          return false;
        }
        request.carrierid = request.carrieridList ? JSON.parse(request.carrieridList)[0] : "";
        request.status = 10;
        dealNullQueryCondition(request);
        delete request.carrieridList;
        master_grid.setParams(JSON.stringify(request));
        master_grid.reload();
        break;
      case "master_reset":
        master_grid.getToolBarForm().clear();
        master_grid.getToolBarForm().setText("carrieridList", "");
        master_grid.getToolBarForm().setFormData({ startdate: startTime, enddate: endTime });
        break;
      case "master_confirm":
        if (!ids) {
          layer.msg("请选择数据");
          return false;
        }
        master_checkClick(ids, "confirm");
        break;
      case "master_print":
        print();
        break;
    }
  });
  // 查询明细
  master_grid.on("onRowSelect", function (id) {
    details_grid.setParams(JSON.stringify({ loadbillid: id }));
    details_grid.reload();
  });
  // 新增
  window.dispatchConfirm_add = function (rid, rdata) {
    selectedMasterGridData = rdata;
    addGridCreated();
  };
  // 修改
  window.dispatchConfirm_edit = function (rid, rdata) {
    editFormCreated(rdata);
  };
  // 撤销、确认
  function master_checkClick(ids, event) {
    let dataList = ids.split(",").map(item => {
      const element = master_grid.getRowData(item);
      return {
        loadbillid: element.loadbillid,
        shipbillid: element.shipbillid
      };
    });
    let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/dispatchConfirmation/" + event + "/v1.0", type: "post", contentType: "application/json", data: JSON.stringify(dataList),
      success: function (res) {
        PlgDialog.close(pload);
        if (res.success) {
          PlgDialog.msg(res.data);
          setTimeout(() => {
            master_grid.reload();
            details_grid.clearAll();
            details_grid.loadData({ data: { list: [] } });
          }, 500);
          return true;
        }
                return false;

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

  // 详情表grid
  var details_grid_opts = {
    skin: "card",
    columns: [
      { id: "shipbillid", name: "运单id", type: "ro", width: 120, hidden: true },
      { id: "shipbillno", name: "运单编号", type: "ro", width: 120 },
      { id: "rrfshipbillid", name: "原运单id", type: "ro", width: 120, hidden: true },
      { id: "rrfshipbillno", name: "原运单编号", type: "ro", width: 120, hidden: true },
      { id: "fathershipbillno", name: "父运单编号", type: "ro", width: 120, hidden: true },
      { id: "branchid", name: "当前仓编号", type: "ro", width: 120 },
      { id: "branchname", name: "当前仓名称", type: "ro", width: 120 },
      { id: "consignor", name: "货主编号", type: "ro", width: 120 },
      { id: "consignorname", name: "货主名称", type: "ro", width: 120 },
      {
        id: "billtype", name: "单据类型", type: "ro", width: 120, render: function (v) {
          return getSelectValue(dataSelect.TMS_SHIP_BILLTYPE, v);
        }
      },
      { id: "billsource", name: "单据来源", type: "ro", width: 120, hidden: true },
      { id: "billsourceName", name: "单据来源", type: "ro", width: 120 },
      { id: "billdate", name: "单据时间", type: "ro", width: 120 },
      { id: "lineno", name: "线路编号", type: "ro", width: 120 },
      { id: "linenane", name: "线路名称", type: "ro", width: 120 },
      { id: "shiptoCustomerType", name: "目的客户类型", type: "ro", width: 120, hidden: true },
      { id: "shiptoCustomerTypeName", name: "目的客户类型", type: "ro", width: 120 },
      { id: "shiptoCustomerId", name: "目的客户/个人id", type: "ro", width: 120 },
      { id: "shiptoCustomerName", name: "目的客户/个人名称", type: "ro", width: 120 },
      { id: "shiptoAddress", name: "目的详细地址", type: "ro", width: 120 },
      { id: "reqshipmentdate", name: "预计发货日期", type: "ro", width: 120 },
      { id: "reqarrivvaldate", name: "要求到货日期", type: "ro", width: 120 },
      {
        id: "urgentIdentify", name: "紧急标识", type: "ro", width: 120, render: function (v) {
          return getSelectValue(dataSelect.URG_FLG, v);
        }
      },
      { id: "refbillid", name: "业务单据id", type: "ro", width: 120, hidden: true },
      { id: "refbillno", name: "业务单据号", type: "ro", width: 120 },
      { id: "refbilltype", name: "业务单据类型", type: "ro", width: 120, hidden: true },
      { id: "refbilltypeName", name: "业务单据类型", type: "ro", width: 120 },
      { id: "rsumcases", name: "实际总件数", type: "ro", width: 120 },
      { id: "rsumpcs", name: "实际整件数", type: "ro", width: 120 },
      { id: "rsumboxnum", name: "实际拼箱数", type: "ro", width: 120 },
      { id: "rsumgoodsqty", name: "实际货物总数量", type: "ro", width: 120, hidden: true },
      { id: "rsumgoodsweight", name: "实际货物总重量", type: "ro", width: 120 },
      { id: "rsumgoodsvol", name: "实际货物总体积", type: "ro", width: 120 },
      { id: "status", name: "状态", type: "ro", width: 120, hidden: true },
      { id: "memo", name: "备注", type: "ro", width: 120 },
      // {
      //   id: "status", name: "状态", type: "ro", width: 120, render: function (v) {
      //     return getSelectValue(dataSelect.AUDIT_STATUS, v);
      //   }
      // },
      {
        id: "op", name: "操作", type: "button", align: "left", fixed: "right", width: "100", render: function () {
          return "任务撤销^dispatchConfirm_withdraw";
        }
      }
    ],
    pagebar: {
      buttons: [
        { text: "<i class='layui-icon layui-icon-delete'></i>任务撤销", className: "plg-btn-normal", name: "details_withdraw" }
      ]
    },
    fixedLast: true, // 开启固定列，固定最后一行，倒数第二列不能隐藏
    multiselect: true, // 是否支持多选
    url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/dispatchConfirmation/detailsQuery/v1.0", // 数据接口
    type: "post", // 数据提交方式，默认为get
    params: "{}", // 查询提交参数，分页参数默认为pageNum,pageSize
    page: false, // 是否启用分页
    contentType: "application/json",
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  details_grid = new PlgGrid(details_grid_opts);
  details_grid.renderTo("dispatchConfirm_details");
  // 批量撤销
  details_grid.attachPageBarEvent(function (name, ids) {
    let dataList = ids.split(",").map(item => {
      const element = details_grid.getRowData(item);
      return {
        seqno: element.seqno,
        loadbillid: element.loadbillid,
        shipbillid: element.shipbillid
      };
    });
    undo(dataList);
  });
  // 撤销
  window.dispatchConfirm_withdraw = function (rid, rdata) {
    undo([{ seqno: rdata.seqno, loadbillid: rdata.loadbillid, shipbillid: rdata.shipbillid }]);
  };
  // 撤销接口
  function undo(params) {
    let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/dispatchConfirmation/undo/v1.0", type: "post", contentType: "application/json", data: JSON.stringify(params),
      success: function (res) {
        PlgDialog.close(pload);
        if (res.success) {
          PlgDialog.msg(res.data);
          details_grid.reload();
          return true;
        }
                return false;

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

  // 新增表grid1
  add_grid1_opts = {
    skin: "card",
    columns: [
      { id: "shipbillid", name: "运单id", type: "ro", width: 120, hidden: true },
      { id: "shipbillno", name: "运单编号", type: "ro", width: 120 },
      { id: "rrfshipbillid", name: "原运单id", type: "ro", width: 120, hidden: true },
      { id: "rrfshipbillno", name: "原运单编号", type: "ro", width: 120, hidden: true },
      { id: "fathershipbillno", name: "父运单编号", type: "ro", width: 120, hidden: true },
      { id: "branchid", name: "当前仓编号", type: "ro", width: 120 },
      { id: "branchname", name: "当前仓名称", type: "ro", width: 120 },
      { id: "consignor", name: "货主编号", type: "ro", width: 120 },
      { id: "consignorname", name: "货主名称", type: "ro", width: 120 },
      { id: "billtypeName", name: "运单类型", type: "ro", width: 120 },
      { id: "billsource", name: "单据来源", type: "ro", width: 120, hidden: true },
      { id: "billsourceName", name: "单据来源", type: "ro", width: 120 },
      { id: "billdate", name: "单据时间", type: "ro", width: 120 },
      { id: "lineno", name: "线路编号", type: "ro", width: 120 },
      { id: "linenane", name: "线路名称", type: "ro", width: 120 },
      { id: "shiptoCustomerTypeName", name: "目的客户类型", type: "ro", width: 120 },
      { id: "shiptoCustomerId", name: "目的客户/个人id", type: "ro", width: 120 },
      { id: "shiptoCustomerName", name: "目的客户/个人名称", type: "ro", width: 120 },
      { id: "shiptoAddress", name: "目的详细地址", type: "ro", width: 120 },
      { id: "reqshipmentdate", name: "预计发货日期", type: "ro", width: 120 },
      { id: "reqarrivvaldate", name: "要求到货日期", type: "ro", width: 120 },
      { id: "urgentIdentify", name: "紧急标识", type: "ro", width: 120, hidden: true },
      { id: "urgentIdentifyName", name: "紧急标识", type: "ro", width: 120 },
      { id: "refbillid", name: "业务单据id", type: "ro", width: 120 },
      { id: "refbillno", name: "业务单据号", type: "ro", width: 120 },
      { id: "refbilltypeName", name: "业务单据类型", type: "ro", width: 120 },
      { id: "rsumcases", name: "实际总件数", type: "ro", width: 120 },
      { id: "rsumpcs", name: "实际整件数", type: "ro", width: 120 },
      { id: "rsumboxnum", name: "实际拼箱数", type: "ro", width: 120 },
      { id: "rsumgoodsqty", name: "实际货物总数量", type: "ro", width: 120, hidden: true },
      { id: "rsumgoodsweight", name: "实际货物总重量", type: "ro", width: 120 },
      { id: "rsumgoodsvol", name: "实际货物总体积", type: "ro", width: 120 },
      { id: "status", name: "状态", type: "ro", width: 120, hidden: true },
      { id: "memo", name: "备注", type: "ro", width: 120 }
    ],
    toolbar: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          { type: "calendar", className: "layui-col-md3", name: "startdate", label: "开始时间:", value: startTime },
          { type: "calendar", className: "layui-col-md3", name: "enddate", label: "结束时间:", value: endTime },
          {
            type: "selectTable",
            className: "layui-col-md3",
            placeholder: "请选择线路",
            readonly: false,
            table: lineTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "lineName",
            fieldValue: "lineCode",
            name: "linenoList",
            label: "线路:",
            listener: function (Grid) {
              setMethod(Grid, lineTable, function () { });
            }
          },
          { type: "combo", className: "layui-col-md3", readonly: true, name: "billtype", label: "运单类型:", options: dataSelect.TMS_SHIP_BILLTYPE },
          { type: "input", className: "layui-col-md3", name: "shipbillno", label: "运单号:" },
          {
            type: "selectTable",
            className: "layui-col-md3",
            placeholder: "请选择客户",
            readonly: false,
            table: customerTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "companyname",
            fieldValue: "companyid",
            name: "shiptoCustomerIdList",
            label: "客户:",
            listener: function (Grid) {
              setMethod(Grid, customerTable, function () { });
            }
          },
          {
            type: "block", className: "layui-col-md3 form_btn_left",
            list: [
              { type: "button", className: "btn-normal", name: "add_grid1_search", value: "查 询" },
              { type: "newcolumn" },
              { type: "button", name: "add_grid1_reset", value: "重 置" }
            ]
          },
          {
            type: "block", className: "layui-col-md3 right",
            list: [
              { type: "button", className: "btn-normal", name: "add_grid1_confirm", value: "多条确认" }
            ]
          }
        ]
      }
    ],
    fixedLast: false, // 开启固定列，固定最后一行，倒数第二列不能隐藏
    multiselect: true, // 是否支持多选
    url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/dispatchConfirmation/addQuery/v1.0", // 数据接口
    type: "post", // 数据提交方式，默认为get
    params: "{}", // 查询提交参数，分页参数默认为pageNum,pageSize
    page: false, // 是否启用分页
    contentType: "application/json",
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  // 新增表grid2
  add_grid2_opts = {
    skin: "card",
    columns: [
      { id: "shipbillid", name: "运单id", type: "ro", width: 120, hidden: true },
      { id: "shipbillno", name: "运单编号", type: "ro", width: 120 },
      { id: "rrfshipbillid", name: "原运单id", type: "ro", width: 120, hidden: true },
      { id: "rrfshipbillno", name: "原运单编号", type: "ro", width: 120, hidden: true },
      { id: "fathershipbillno", name: "父运单编号", type: "ro", width: 120, hidden: true },
      { id: "branchid", name: "当前仓编号", type: "ro", width: 120 },
      { id: "branchname", name: "当前仓名称", type: "ro", width: 120 },
      { id: "consignor", name: "货主编号", type: "ro", width: 120 },
      { id: "consignorname", name: "货主名称", type: "ro", width: 120 },
      { id: "billtypeName", name: "运单类型", type: "ro", width: 120 },
      { id: "billsource", name: "单据来源", type: "ro", width: 120, hidden: true },
      { id: "billsourceName", name: "单据来源", type: "ro", width: 120 },
      { id: "billdate", name: "单据时间", type: "ro", width: 120 },
      { id: "lineno", name: "线路编号", type: "ro", width: 120 },
      { id: "linenane", name: "线路名称", type: "ro", width: 120 },
      { id: "shiptoCustomerTypeName", name: "目的客户类型", type: "ro", width: 120 },
      { id: "shiptoCustomerId", name: "目的客户/个人id", type: "ro", width: 120 },
      { id: "shiptoCustomerName", name: "目的客户/个人名称", type: "ro", width: 120 },
      { id: "shiptoAddress", name: "目的详细地址", type: "ro", width: 120 },
      { id: "reqshipmentdate", name: "预计发货日期", type: "ro", width: 120 },
      { id: "reqarrivvaldate", name: "要求到货日期", type: "ro", width: 120 },
      { id: "urgentIdentify", name: "紧急标识", type: "ro", width: 120, hidden: true },
      { id: "urgentIdentifyName", name: "紧急标识", type: "ro", width: 120 },
      { id: "refbillid", name: "业务单据id", type: "ro", width: 120 },
      { id: "refbillno", name: "业务单据号", type: "ro", width: 120 },
      { id: "refbilltypeName", name: "业务单据类型", type: "ro", width: 120 },
      { id: "rsumcases", name: "实际总件数", type: "ro", width: 120 },
      { id: "rsumpcs", name: "实际整件数", type: "ro", width: 120 },
      { id: "rsumboxnum", name: "实际拼箱数", type: "ro", width: 120 },
      { id: "rsumgoodsqty", name: "实际货物总数量", type: "ro", width: 120, hidden: true },
      { id: "rsumgoodsweight", name: "实际货物总重量", type: "ro", width: 120 },
      { id: "rsumgoodsvol", name: "实际货物总体积", type: "ro", width: 120 },
      { id: "status", name: "状态", type: "ro", width: 120 },
      { id: "memo", name: "备注", type: "ro", width: 120 }
    ],
    fixedLast: false, // 开启固定列，固定最后一行，倒数第二列不能隐藏
    multiselect: false, // 是否支持多选
    url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/dispatchConfirmation/addQuery/v1.0", // 数据接口
    type: "post", // 数据提交方式，默认为get
    params: "{}", // 查询提交参数，分页参数默认为pageNum,pageSize
    page: false, // 是否启用分页
    contentType: "application/json",
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  // 注册新增表
  function addGridCreated() {
    changePanel("#dispatchConfirm_add");
    add_grid1 = new PlgGrid(add_grid1_opts);
    add_grid1.renderTo("dispatchConfirm_add_grid1");
    add_grid2 = new PlgGrid(add_grid2_opts);
    add_grid2.renderTo("dispatchConfirm_add_grid2");
    let { startdate, enddate } = master_grid.getToolBarForm().getFormData();
    add_grid1.setParams(JSON.stringify({ startdate: Prolog.formatDate(startdate) + " 00:00:00", enddate: Prolog.formatDate(enddate) + " 23:59:59", branchid: selectedMasterGridData.branchid }));
    add_grid1.reload();
    // 双击新增
    add_grid1.on("onRowDblClicked", function (id) {
      add_grid1.deleteRow(id);
      const rowData = add_grid1.getRowData(id);
      add_grid2.addRow(id, rowData);
    });
    // 双击删除
    add_grid2.on("onRowDblClicked", function (id) {
      add_grid2.deleteRow(id);
      const rowData = add_grid2.getRowData(id);
      add_grid1.addRow(id, rowData);
    });
    // 表1点击事件
    add_grid1.attachToolBarEvent("onButtonClick", function (name) {
      switch (name) {
        case "add_grid1_search":
          var request = add_grid1.getToolBarForm().getFormData();
          request.lineno = request.linenoList ? JSON.parse(request.linenoList)[0] : "";
          request.shiptoCustomerId = request.shiptoCustomerIdList ? JSON.parse(request.shiptoCustomerIdList)[0] : "";
          request.startdate = request.startdate ? Prolog.formatDate(request.startdate) + " 00:00:00" : "";
          request.enddate = request.enddate ? Prolog.formatDate(request.enddate) + " 23:59:59" : "";
          request.branchid = selectedMasterGridData.branchid;
          if (request.startdate > request.enddate) {
            layer.msg("开始时间不能大于结束时间");
            return false;
          }
          dealNullQueryCondition(request);
          delete request.linenoList;
          delete request.shiptoCustomerIdList;
          add_grid1.setParams(JSON.stringify(request));
          add_grid1.reload();
          add_grid2.clearAll();
          break;
        case "add_grid1_reset":
          add_grid1.getToolBarForm().clear();
          add_grid1.getToolBarForm().setFormData({ startdate: startTime, enddate: endTime });
          add_grid1.getToolBarForm().setText("linenoList", "");
          add_grid1.getToolBarForm().setText("shiptoCustomerIdList", "");
          break;
        case "add_grid1_confirm":
          var ids = add_grid1.getCheckedIds();
          if (!ids) {
            layer.msg("请选择数据");
            return false;
          }
          ids.split(",").forEach((id, index) => {
            const rowData = add_grid1.getRowData(id);
            add_grid1.deleteRow(id);
            add_grid2.addRow(id, rowData, index);
          });
          break;
      }
    });
  }
  // 新增提交
  $("#dispatchConfirm_add_save").on("click", function () {
    let dataList = [];
    let indexNum = add_grid2.getGrid().getRowsNum();
    if (!indexNum) {
      layer.msg("请选择数据");
      return false;
    }
    let request = JSON.parse(JSON.stringify(selectedMasterGridData));
    let customerCodeSet = new Set(request.customerCode.split(","));
    for (let i = 0; i < indexNum; i++) {
      const element = add_grid2.getRowData(add_grid2.getRowId(i));
      dataList.push(element);
      request.orderNumber++;
      request.orders += "," + element.shipbillid;
      if (element.temperatureRequire !== "00") {
        request.coldBillNumber++;
      }
      customerCodeSet.add(element.shiptoCustomerId);
      request.shipmentNumber = Prolog.floatOper(request.shipmentNumber, element.rsumcases, "+");
      request.shipmentWeight = Prolog.floatOper(request.shipmentWeight, element.rsumgoodsweight, "+");
      request.shipmentVol = Prolog.floatOper(request.shipmentVol, element.rsumgoodsvol, "+");
    }

    request.itemlist = dataList;
    request.customerNumber = customerCodeSet.size;
    request.customerCode = [...customerCodeSet].join(",");
    request.loadingRateWeight = Math.round(request.shipmentWeight / request.maxWeight * 10000) / 10000 + "%";
    request.loadingRateVol = Math.round(request.shipmentVol / request.maxVol * 10000) / 10000 + "%";
    let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/dispatchConfirmation/addDetail/v1.0", type: "post", contentType: "application/json", data: JSON.stringify(request),
      success: function (res) {
        PlgDialog.close(pload);
        if (res.success) {
          PlgDialog.msg(res.data);
          changePanel("#dispatchConfirm_main");
          master_grid.reload();
          details_grid.clearAll();
          return true;
        }
                return false;

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

  // 修改表form
  edit_form_opts = {
    renderer: "dispatchConfirm_edit_form",
    items: [
      { type: "settings", labelAlign: "left", labelWidth: 90 },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md3 no-border", name: "orderNumber", label: "运单数:", readonly: true },
          { type: "input", className: "layui-col-md3 no-border", name: "shipmentNumber", label: "总件数:", readonly: true },
          { type: "input", className: "layui-col-md3 no-border", name: "shipmentWeight", label: "总重量:", readonly: true },
          { type: "input", className: "layui-col-md3 no-border", name: "shipmentVol", label: "总体积:", readonly: true },
          { type: "input", className: "layui-col-md3 no-border", name: "customerNumber", label: "客户数:", readonly: true },
          {
            type: "selectTable",
            className: "layui-col-md3",
            placeholder: "请选择承运商",
            readonly: false,
            table: carrierTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "companyname",
            fieldValue: "companyid",
            name: "carrierList",
            label: "承运商:",
            listener: {
              "init": function (Grid) {
                // 注册按钮事件
                Grid.attachToolBarEvent("onButtonClick", function (name) {
                  switch (name) {
                    case "querycarr":
                      var { companycode } = Grid.getToolBarForm().getFormData();
                      Grid.setParams(JSON.stringify({ companycode }));
                      Grid.reload();
                      break;
                    case "car_Reset":
                      Grid.getToolBarForm().clear();
                      break;
                  }
                });
              },
              "afterSelect": function (isSelected, selectId, sgrid) {
                // 切换承运商，清空车辆数据
                const sdata = sgrid.getRowData(selectId);
                const formData = {
                  carrierid: isSelected ? sdata.companyid : "",
                  carrierno: isSelected ? sdata.companycode : "",
                  carriername: isSelected ? sdata.companyname : "",
                  voucherno: "",
                  vouchernane: "",
                  maxWeight: "",
                  maxVol: "",
                  maxPkg: "",
                  loadingRateWeight: "",
                  loadingRateVol: "",
                  driver1st: "",
                  driver1stname: "",
                  dirver2nd: "",
                  dirver2ndname: "",
                  drivertel: "",
                  drivercard: "",
                  appointVehicleModel: "",
                  appointVehicleModelName: ""
                };
                edit_form.setFormData(formData);

                isSelected ? edit_form.enableItem("voucherList") : edit_form.disableItem("voucherList");
                edit_form.setText("voucherList", "");
                vehicleTable.params = JSON.stringify({ companyId: isSelected ? sdata.companyid : "", branchId: userinfo.p_companyid });
                edit_form.getDForm().setTableConfig("voucherList", vehicleTable);

                isSelected ? edit_form.enableItem("driver1stList") : edit_form.disableItem("driver1stList");
                edit_form.setText("driver1stList", "");
                driverTable.params = JSON.stringify({ companyId: isSelected ? sdata.companyid : "", branchId: userinfo.p_companyid });
                edit_form.getDForm().setTableConfig("driver1stList", driverTable);

                isSelected ? edit_form.enableItem("dirver2ndList") : edit_form.disableItem("dirver2ndList");
                edit_form.setText("dirver2ndList", "");
                driverTable2.params = JSON.stringify({ companyId: isSelected ? sdata.companyid : "", branchId: userinfo.p_companyid });
                edit_form.getDForm().setTableConfig("dirver2ndList", driverTable2);
              }
            }
          },
          { type: "hidden", name: "carrierid", label: "承运商id:" },
          { type: "hidden", name: "carrierno", label: "承运商编号:" },
          { type: "hidden", name: "carriername", label: "承运商名称:" },
          {
            type: "selectTable",
            className: "layui-col-md3",
            placeholder: "请选择车辆",
            readonly: false,
            table: vehicleTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "vehicleNo",
            fieldValue: "vehicleNo",
            name: "voucherList",
            label: "车辆:",
            listener: {
              "afterSelect": function (isSelected, selectId, sgrid) {
                // 切换承运商，清空车辆数据
                const sdata = sgrid.getRowData(selectId);
                const { shipmentWeight, shipmentVol } = edit_form.getFormData();
                const formData = {
                  voucherno: isSelected ? sdata.vehicleNo : "",
                  vouchernane: isSelected ? sdata.vehicleName : "",
                  vehicleType: isSelected ? sdata.vehicleType : "",
                  maxWeight: isSelected ? sdata.maxWeight : "",
                  maxVol: isSelected ? sdata.maxVol : "",
                  maxPkg: isSelected ? sdata.maxPkg : "",
                  loadingRateWeight: isSelected ? Math.round(shipmentWeight / sdata.maxWeight * 10000) / 10000 + "%" : "",
                  loadingRateVol: isSelected ? Math.round(shipmentVol / sdata.maxVol * 10000) / 10000 + "%" : "",
                  driver1st: isSelected ? sdata.mainDriverId : "",
                  driver1stname: isSelected ? sdata.mainDriverName : "",
                  dirver2nd: isSelected ? sdata.secondDriverId : "",
                  dirver2ndname: isSelected ? sdata.secondDriverName : "",
                  drivertel: isSelected ? sdata.tel : "",
                  drivercard: isSelected ? sdata.card : "",
                  appointVehicleModel: isSelected ? sdata.vehicleSpecsNo : "",
                  appointVehicleModelName: isSelected ? sdata.vehicleSpecsName : "",
                  driver1stList: isSelected ? JSON.stringify([sdata.mainDriverId]) : "[]",
                  driver2stList: isSelected && sdata.secondDriverId ? JSON.stringify([sdata.secondDriverId]) : "[]"

                };
                edit_form.setFormData(formData);
                edit_form.setText("driver1stList", isSelected ? sdata.mainDriverName : "");
                edit_form.setText("driver2stList", isSelected ? sdata.secondDriverName : "");
              }
            }
          },
          { type: "hidden", name: "voucherno", label: "车牌号:" },
          { type: "hidden", name: "vouchernane", label: "车辆名称:" },
          { type: "hidden", name: "appointVehicleModel", label: "车辆类型:" },
          { type: "input", className: "layui-col-md3 no-border", name: "appointVehicleModelName", label: "车辆规格:", readonly: true },
          { type: "input", className: "layui-col-md3 no-border", name: "maxWeight", label: "车辆载重:", readonly: true },
          { type: "input", className: "layui-col-md3 no-border", name: "maxVol", label: "车辆体积:", readonly: true },
          {
            type: "selectTable",
            className: "layui-col-md3",
            placeholder: "请选择主驾驶",
            readonly: false,
            table: driverTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "driverName",
            fieldValue: "driverId",
            name: "driver1stList",
            label: "主驾驶名称:",
            listener: {
              "init": function (Grid) {
                // 注册按钮事件
                Grid.attachToolBarEvent("onButtonClick", function (name) {
                  switch (name) {
                    case "querycarr":
                      var { driverName } = Grid.getToolBarForm().getFormData();
                      var { carrierid } = edit_form.getFormData();
                      Grid.setParams(JSON.stringify({ driverName, branchId: userinfo.p_companyid, companyId: carrierid }));
                      Grid.reload();
                      break;
                    case "car_Reset":
                      Grid.getToolBarForm().clear();
                      break;
                  }
                });
              },
              "afterSelect": function (isSelected, selectId, sgrid) {
                // 切换承运商，清空车辆数据
                const sdata = sgrid.getRowData(selectId);
                let fd = edit_form.getFormData();
                if (fd.dirver2nd == sdata.driverId && fd.dirver2nd) {
                  PlgDialog.msg("主驾驶与副驾驶不能相同");
                  edit_form.setItemValue("driver1stList", "");
                  edit_form.setText("driver1stList", "");
                  return;
                }
                const formData = {
                  driver1st: isSelected ? sdata.driverId : "",
                  driver1stname: isSelected ? sdata.driverName : ""
                };
                edit_form.setFormData(formData);
              }
            }
          },
          { type: "hidden", name: "driver1st", label: "主驾驶id:" },
          { type: "hidden", name: "driver1stname", label: "主驾驶名称:" },
          {
            type: "selectTable",
            className: "layui-col-md3",
            placeholder: "请选择副驾驶",
            readonly: false,
            table: driverTable2,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "driverName",
            fieldValue: "driverId",
            name: "dirver2ndList",
            label: "副驾驶名称:",
            listener: {
              "init": function (Grid) {
                // 注册按钮事件
                Grid.attachToolBarEvent("onButtonClick", function (name) {
                  switch (name) {
                    case "querycarr":
                      var { driverName } = Grid.getToolBarForm().getFormData();
                      var { carrierid } = edit_form.getFormData();
                      Grid.setParams(JSON.stringify({ driverName, branchId: userinfo.p_companyid, companyId: carrierid }));
                      Grid.reload();
                      break;
                    case "car_Reset":
                      Grid.getToolBarForm().clear();
                      break;
                  }
                });
              },
              "afterSelect": function (isSelected, selectId, sgrid) {
                // 切换承运商，清空车辆数据
                const sdata = sgrid.getRowData(selectId);
                let fd = edit_form.getFormData();
                if (fd.driver1st == sdata.driverId && fd.driver1st) {
                  PlgDialog.msg("主驾驶与副驾驶不能相同");
                  edit_form.setItemValue("dirver2ndList", "");
                  edit_form.setText("dirver2ndList", "");
                  return;
                }
                const formData = {
                  dirver2nd: isSelected ? sdata.driverId : "",
                  dirver2ndname: isSelected ? sdata.driverName : ""
                };
                edit_form.setFormData(formData);
              }
            }
          },
          { type: "hidden", name: "driver2nd", label: "副驾驶id:" },
          { type: "hidden", name: "dirver2ndname", label: "副驾驶名称:" },
          { type: "input", className: "layui-col-md3 no-border", name: "loadingRateWeight", label: "载重装载量:", readonly: true },
          { type: "input", className: "layui-col-md3 no-border", name: "loadingRateVol", label: "体积装载量:", readonly: true }

        ]
      },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md9", name: "remark", label: "备注:", rows: 3 }
        ]
      }
    ]
  };
  // 注册表单
  function editFormCreated(formData) {
    changePanel("#dispatchConfirm_edit");
    vehicleTable.params = JSON.stringify({ companyId: formData.carrierid, branchId: userinfo.p_companyid });
    driverTable.params = JSON.stringify({ companyId: formData.carrierid, branchId: userinfo.p_companyid });
    driverTable2.params = JSON.stringify({ companyId: formData.carrierid, branchId: userinfo.p_companyid });
    edit_form = new PlgForm(edit_form_opts);
    formData.carrierList = formData.carrierid ? JSON.stringify([formData.carrierid]) : "[]";
    formData.voucherList = formData.voucherno ? JSON.stringify([formData.voucherno]) : "[]";
    formData.driver1stList = formData.driver1st ? JSON.stringify([formData.driver1st]) : "[]";
    formData.dirver2ndList = formData.dirver2nd ? JSON.stringify([formData.dirver2nd]) : "[]";
    edit_form.setFormData(formData);
    edit_form.setText("carrierList", formData.carriername || "");
    edit_form.setText("voucherList", formData.voucherno || "");
    edit_form.setText("driver1stList", formData.driver1stname || "");
    edit_form.setText("dirver2ndList", formData.dirver2ndname || "");
  }
  // 修改保存
  $("#dispatchConfirm_edit_save").on("click", function () {
    let formData = edit_form.getFormData();
    if (!formData.carrierid) {
      layer.msg("请选择承运商");
      return false;
    }
    if (!formData.voucherno) {
      layer.msg("请选择车辆");
      return false;
    }

    let textList = [];
    if (formData.shipmentNumber > formData.maxPkg) {
      textList.push("总件数");
    }
    if (formData.shipmentVol > formData.maxVol) {
      textList.push("总体积");
    }
    if (formData.shipmentWeight > formData.maxWeight) {
      textList.push("总重量");
    }
    if (textList.length) {
      layer.open({
        title: "提示",
        content: "车辆" + textList.join(",") + "已超载，确认强制执行吗？",
        btn: ["确认", "取消"],
        yes: function () {
          Modify(formData);
        }
      });
    }
    else {
      Modify(formData);
    }
  });
  // 保存
  function Modify(formData) {
    delete formData.carrierList;
    delete formData.voucherList;
    delete formData.driver1stList;
    delete formData.dirver2ndList;

    let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/dispatchConfirmation/modify/v1.0", type: "post", contentType: "application/json", data: JSON.stringify(formData),
      success: function (res) {
        PlgDialog.close(pload);
        if (res.success) {
          layer.closeAll();
          PlgDialog.msg(res.data);
          changePanel("#dispatchConfirm_main");
          master_grid.reload();
          details_grid.clearAll();
          return true;
        }
                return false;

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