/**
 * 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 scan_form, total_grid, main_grid;
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: "#scanningDispatch",
    autoplay: false,
    index: 0,
    arrow: "none",
    indicator: "none",
    anim: "fade",
    width: "100%", // 设置容器宽度
    height: "100%"
  });
  // 切换页面
  function changePanel(name) {
    var slideList = ["#scanningDispatch_main", "#scanningDispatch_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", "#scanningDispatch_edit_return", function () {
    changePanel("#scanningDispatch_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" },
    { "objectcode": "BILLSOURCE" },
    { "objectcode": "GET_CUS_TYPE" }
  ], function (data) {
    dataSelect = data.data;
  });

  // 承运商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 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"
  };

  // 扫描表单
  var scan_form_opts = {
    renderer: "scanningDispatch_scan_form",
    items: [
      { type: "settings", labelAlign: "left", labelWidth: 90 },
      {
        type: "row",
        list: [
          {
            type: "block", className: "layui-col-md12",
            list: [
              { type: "button", className: "btn-normal", name: "form_truck", value: "配送派车" },
              { type: "newcolumn" },
              { type: "button", className: "btn-normal", name: "form_print", value: "打 印" }
            ]
          },
          { type: "input", className: "layui-col-md12 scan", name: "shipbillno", label: "扫描单号:" },
          { type: "input", className: "layui-col-md12", name: "reason", label: "扫描结果:", rows: 3, readonly: true }
        ]
      }
    ]
  };
  scan_form = new PlgForm(scan_form_opts);
  scan_form.attachEvent("onButtonClick", function (name) {
    switch (name) {
      case "form_truck":
        editFormCreated();
        break;
      case "form_print":
        Print();
        break;
    }
  });

  let textareas = document.getElementById("scanningDispatch_scan_form").getElementsByTagName("input");
  setTimeout(() => {
    textareas[0].focus();
  }, 500);
  textareas[0].onkeydown = function (key) {
    if (key.key == "Enter") {
      const { shipbillno } = scan_form.getFormData();
      if (!shipbillno) {
        layer.msg("请扫描单号");
        textareas[0].focus();
        return false;
      }
      let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
      Prolog.ajax({
        url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/scanPlatoon/waybillScan/v1.0", type: "post", contentType: "application/json", data: JSON.stringify({ shipbillno }),
        success: function (res) {
          PlgDialog.close(pload);
          if (res.success) {
            // PlgDialog.msg(res.message);
            scan_form.setFormData({
              shipbillno: "",
              reason: "运单" + shipbillno + "扫描成功"
            });
            textareas[0].focus();
            statisticsQuery();
          }
          else {
            scan_form.setFormData({
              shipbillno: "",
              reason: "运单" + shipbillno + "扫描失败。" + res.message
            });
          }
        }, error: function () { PlgDialog.close(pload); return false; }
      });
    }
  };

  // 修改扫描结果样式
  $("textarea[name='reason']").addClass("scanningDispatch_reason");

  // 合计表格
  var total_grid_opts = {
    skin: "card",
    columns: [
      { id: "id", name: "id", type: "ro", width: 120, hidden: true },
      { id: "customer", name: "客户名称", type: "ro" },
      { id: "sumBillNumber", name: "订单数", type: "ro" },
      { id: "sumPakageNumbers", name: "件数", type: "ro" },
      { id: "sumWeightNumber", name: "重量", type: "ro" },
      { id: "sumVolNumber", name: "体积", type: "ro" },
      { id: "orders", name: "运单集", type: "ro", hidden: true },
      { id: "coldBillNumber", name: "冷链运单数", type: "ro", hidden: true },
      { id: "customerCode", name: "客户集", type: "ro", hidden: true }
    ],
    fixedLast: false, // 开启固定列，固定最后一行，倒数第二列不能隐藏
    multiselect: false, // 是否支持多选
    url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/scanPlatoon/statisticsQuery/v1.0", // 数据接口
    type: "post", // 数据提交方式，默认为get
    params: "{}", // 查询提交参数，分页参数默认为pageNum,pageSize
    page: false, // 是否启用分页
    contentType: "application/json",
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  total_grid = new PlgGrid(total_grid_opts);
  total_grid.renderTo("scanningDispatch_total_grid");

  // 查询表格
  var main_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, render: function (v) {
          return getSelectValue(dataSelect.BILLSOURCE, v);
        }
      },
      { 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, render: function (v) {
          return getSelectValue(dataSelect.GET_CUS_TYPE, v);
        }
      },
      { 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, render: function (v) {
          return getSelectValue(dataSelect.TMS_SHIP_BILLTYPE, v);
        }
      },
      { 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 },
      { 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: "op", name: "操作", type: "button", align: "left", fixed: "right", width: "100", render: function () {
          return "删除^scanningDispatch_delete";
        }
      }
    ],
    pagebar: {
      buttons: [
        { text: "<i class='layui-icon layui-icon-delete'></i>删除", className: "plg-btn-normal", name: "main_detele" }
      ]
    },
    fixedLast: true, // 开启固定列，固定最后一行，倒数第二列不能隐藏
    multiselect: true, // 是否支持多选
    url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/scanPlatoon/waybillScan/v1.0", // 数据接口
    type: "post", // 数据提交方式，默认为get
    params: "{}", // 查询提交参数，分页参数默认为pageNum,pageSize
    page: false, // 是否启用分页
    contentType: "application/json",
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  main_grid = new PlgGrid(main_grid_opts);
  main_grid.renderTo("scanningDispatch_main_grid");
  // 批量删除
  main_grid.attachPageBarEvent(function (name, ids) {
    let dataList = ids.split(",").map(item => main_grid.getRowData(item));
    waybillDelete(dataList);
  });
  // 删除
  window.scanningDispatch_delete = function (rid, rdata) {
    waybillDelete([rdata]);
  };
  // 删除接口
  function waybillDelete(params) {
    let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/scanPlatoon/waybillDelete/v1.0", type: "post", contentType: "application/json", data: JSON.stringify(params),
      success: function (res) {
        PlgDialog.close(pload);
        if (res.success) {
          PlgDialog.msg(res.message);
          statisticsQuery();
          return true;
        }
                return false;

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

  // 刷新2个表格
  function statisticsQuery() {
    total_grid.clearAll();
    main_grid.clearAll();
    let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/scanPlatoon/statisticsQuery/v1.0", type: "post", contentType: "application/json", data: "{}",
      success: function (res) {
        PlgDialog.close(pload);
        if (res.success) {
          // 计算合计值
          let coldBillNumber = 0; // 冷链数
          let ordersSet = new Set(); // 运单集
          let customerCodeSet = new Set(); // 客户集
          for (let index = 0; index < res.data.list2.length; index++) {
            const element = res.data.list2[index];
            if (element.temperatureRequire !== "00") {
              coldBillNumber++;
            }
            ordersSet.add(element.shipbillid);
            customerCodeSet.add(element.shiptoCustomerId);
          }
          let totalList = res.data.list1.map((item, index) => {
            if (item.customer === "合计") {
              item.id = "total";
              item.coldBillNumber = coldBillNumber;
              item.orders = [...ordersSet].join(",");
              item.customerCode = [...customerCodeSet].join(",");
            }
            else {
              item.id = index + "";
            }
            return item;
          });
          total_grid.loadData({ data: { list: totalList } });
          main_grid.loadData({ data: { list: res.data.list2 } });
          return true;
        }
                return false;

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

  // 编辑表单
  var edit_form_opts = {
    renderer: "scanningDispatch_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 * 100) + "%" : "",
                  loadingRateVol: isSelected ? Math.round(shipmentVol / sdata.maxVol * 100) + "%" : "",
                  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: "dirver2nd", 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: "hidden", name: "orders", label: "运单集:" },
          { type: "hidden", name: "coldBillNumber", label: "冷链运单数:" },
          { type: "hidden", name: "customerCode", label: "客户集:" }
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md9", name: "remark", label: "备注:", rows: 3 }
        ]
      }
    ]
  };
  // 注册表单
  function editFormCreated() {
    let totalLength = total_grid.getGrid().getRowsNum() - 1;
    if (!totalLength) {
      layer.msg("暂无数据");
      return false;
    }

    changePanel("#scanningDispatch_edit");
    // 获取合计值
    const totalData = total_grid.getRowData("total");
    const formData = {
      orderNumber: totalData.sumBillNumber,
      shipmentNumber: totalData.sumPakageNumbers,
      shipmentWeight: totalData.sumWeightNumber,
      shipmentVol: totalData.sumVolNumber,
      customerNumber: totalLength,
      orders: totalData.orders,
      coldBillNumber: totalData.coldBillNumber,
      customerCode: totalData.customerCode
    };
    edit_form = new PlgForm(edit_form_opts);
    edit_form.disableItem("voucherList");
    edit_form.disableItem("driver1stList");
    edit_form.disableItem("dirver2ndList");
    edit_form.setFormData(formData);
  }

  // 保存
  $("#scanningDispatch_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 () {
          scanVehicle(formData);
        }
      });
    }
    else {
      scanVehicle(formData);
    }
  });
  // 保存
  function scanVehicle(formData) {
    formData.itemlist = [];
    const indexNum = main_grid.getGrid().getRowsNum();
    for (let i = 0; i < indexNum; i++) {
      const element = main_grid.getRowData(main_grid.getRowId(i));
      formData.itemlist.push(element);
    }
    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+"/scanPlatoon/scanVehicle/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.message);
          changePanel("#scanningDispatch_main");
          statisticsQuery();
          return true;
        }
                return false;

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

  // 排车单打印
  function Print() {
    PlgDialog.open({
      title: "打印",
      shadeClose: true,
      type: 1, // 设置为1，手动控制dialog的开关
      area: ["900px", "650px"],
      content: "<div id =\"scanningDispatch_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("scanningDispatch_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; }
    });
  }
};