/**
   * guoj
   * 2020.10.26
   * 运单拆分
   */
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 carousel = layui.carousel;
  var car = carousel.render({
    elem: "#splitWaybill",
    autoplay: false,
    index: 0,
    arrow: "none",
    indicator: "none",
    anim: "fade",
    width: "100%", //设置容器宽度
    height: "100%"
  });
  // 跳转方法
  var tt = "splitWaybill_main";
  function changePanel() {
    car.slide(tt);
    tt = tt == "splitWaybill_edit" ? "splitWaybill_main" : "splitWaybill_edit";
  }

  let GridObj = {}; // 用于储存运单拆分的grid
  let before_totalGrid_data = {}; // 用于储存拆分前数据汇总
  let saveType = 0;
  let edit_form, master_grid;
  // 获取默认时间
  var sdate = Prolog.formatDate(new Date(), "%YY-%MM") + "-01 00:00:00";
  var edate = Prolog.formatDate(new Date()) + " 23:59:59";

  let dataSelect;
  // 获取下拉框
  getSelectGJ([
    { "objectcode": "TMS_REF_BILLTYPE" },
    { "objectcode": "SIGNSTATUS" },
    { "objectcode": "TMS_SHIP_BILLTYPE" },
    { "objectcode": "ITEM_TYPE" }
  ], function (data) {
    data.data.TMS_REF_BILLTYPE.unshift({ "text": "", "value": "" });
    dataSelect = data.data;
  });

  // 配送中心table
  var userTable = {
    columns: [
      { id: "companyid", name: "id", type: "ro", width: "130", hidden: true },
      { id: "companycode", name: "配送中心编号", type: "ro" },
      { id: "companyname", name: "配送中心名称", type: "ro" }
    ],
    multiselect: false,
    contentType: "application/json",
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/pubCompany/queryCompanyBranch", //数据接口
    type: "post", //数据提交方式，默认为get
    pagebar: { type: "simple" },
    params: JSON.stringify({ "companytype": "S" }), //查询提交参数，分页参数默认为pageNum,pageSize
    page: true, //是否启用分页
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };
  // 客户table
  var companyTable = {
    columns: [
      { id: "companyid", name: "id", type: "ro", width: "130", hidden: true },
      { id: "companycode", name: "编号", type: "ro" },
      { id: "companyname", name: "名称", type: "ro" }
    ],
    multiselect: false,
    pagebar: { type: "simple" },
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/pubCompany/queryCompanyCustomer", //数据接口
    type: "post", //数据提交方式，默认为get
    contentType: "application/json",
    params: JSON.stringify({ companytypes: ["C"] }), //查询提交参数，分页参数默认为pageNum,pageSize
    page: true, //是否启用分页
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };
  // 货主table
  var connerTable = {
    columns: [
      { id: "companyid", name: "id", type: "ro", width: "130", hidden: true },
      { id: "companycode", name: "编号", type: "ro" },
      { id: "companyname", name: "名称", type: "ro" }
    ],
    multiselect: false,
    pagebar: { type: "simple" },
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/pubCompany/queryCompanyConsignor", //数据接口
    type: "post", //数据提交方式，默认为get
    contentType: "application/json",
    params: JSON.stringify({ companytypes: ["H"] }), //查询提交参数，分页参数默认为pageNum,pageSize
    page: true, //是否启用分页
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };

  // 分页参数
  var opts = {
    skin: "card",
    columns: [
      { id: "INDEX", name: "id", type: "ro", width: "80", hidden: true },
      { id: "branchname", name: "配送中心", type: "ro", width: "100" },
      { id: "shipbillno", name: "运单号", type: "ro", width: "100" },
      { id: "consignorname", name: "货主", type: "ro", width: "80" },
      {
        id: "billtype", name: "运单类型", type: "ro", width: "100", render: (v) => {
          return getSelectValue(dataSelect.TMS_SHIP_BILLTYPE, v);
        }
      },
      { id: "linenane", name: "线路名称", type: "ro", width: "80" },
      { id: "billdate", name: "单据日期", type: "ro", width: "120" },
      {
        id: "urgentIdentify", name: "是否急单", type: "ro", width: "120", render: (v) => {
          return v == "01" ? "是" : "否";
        }
      },
      { id: "refbillno", name: "业务单号", type: "ro", width: "120" },
      {
        id: "refbilltype", name: "业务类型", type: "ro", width: "130", render: (v) => {
          return getSelectValue(dataSelect.TMS_REF_BILLTYPE, v);
        }
      },
      { id: "arriverName", name: "客户名称", type: "ro", width: "80" },
      { id: "arriveAddress", name: "客户地址", type: "ro", width: "80" },
      { id: "rsumcases", name: "件数", type: "ro", width: "80" },
      { id: "rsumgoodsweight", name: "重量", type: "ro", width: "80" },
      { id: "rsumgoodsvol", name: "体积", type: "ro", width: "80" },
      { id: "memo", name: "备注", type: "ro", width: "80" }
    ],
    multiselect: false,
    toolbar: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          { type: "calendar", name: "sdate", className: "layui-col-md3", label: "开始时间:", value: sdate },
          { type: "calendar", name: "edate", className: "layui-col-md3", label: "结束时间:", value: edate },
          {
            className: "layui-col-md3",
            type: "selectTable",
            placeholder: "请选择配送中心",
            readonly: false,
            table: userTable,
            tableWidth: 500,
            tableHeight: 400,
            fieldText: "companyname",
            fieldValue: "companycode",
            name: "branchid",
            label: "配送中心:"
          },
          { type: "input", name: "shipbillno", className: "layui-col-md3", label: "运单号:" },
          {
            className: "layui-col-md3",
            type: "selectTable",
            placeholder: "请选择货主",
            readonly: false,
            table: connerTable,
            tableWidth: 500,
            tableHeight: 400,
            fieldText: "companyname",
            fieldValue: "companyid",
            name: "consignor",
            label: "货主:"
          },
          { type: "input", name: "refbillno", className: "layui-col-md3", label: "业务单号:" },
          {
            className: "layui-col-md3",
            type: "selectTable",
            placeholder: "请选择客户",
            readonly: false,
            table: companyTable,
            tableWidth: 500,
            tableHeight: 400,
            fieldText: "companyname",
            fieldValue: "companyid",
            name: "shiptoCustomerId",
            label: "客户:",
            listener: function () {
            }
          },
          {
            type: "block", className: "layui-col-md6 form_btn_left",
            list: [
              { type: "button", className: "btn-normal", name: "querycarr", value: "查 询" },
              { type: "newcolumn" },
              { type: "button", name: "car_Reset", className: "normal", value: "重 置" }
            ]
          },
          {
            type: "block", className: "layui-col-md6 right",
            list: [
              { type: "button", className: "btn-addBtn btn-normal", name: "splitWaybill", value: "运单拆分" },
              { type: "newcolumn" },
              { type: "button", className: "btn-addBtn btn-normal", name: "inSplitWaybill", value: "合并运单拆分" },
              { type: "newcolumn" },
              { type: "button", className: "btn-addBtn btn-normal", name: "master_splitUndo", value: "拆分撤销" }
            ]
          }
        ]
      }],
    beforeLoadData: function (res) {
      if (res.data == null) {
        res.data = [];
        return res;
      }
      res.data.list.forEach((item, index) => {
        item.INDEX = index + "";
      });
      return res;
    },
    url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/tmsOrderDivide/query",
    type: "post",
    contentType: "application/json",
    params: JSON.stringify({ sdate: sdate, edate: edate }),
    page: true,
    totalCount: "totalCount"
  };
  master_grid = new PlgGrid(opts);
  master_grid.renderTo("splitWaybill_master");
  master_grid.loadData();
  master_grid.attachToolBarEvent("onButtonClick", function (name) {
    // 查询
    if (name == "querycarr") {
      var jsonData = master_grid.getToolBarForm().getFormData();
      jsonData.sdate = jsonData.sdate ? Prolog.formatDate(jsonData.sdate) + " 00:00:00" : "";
      jsonData.edate = jsonData.edate ? Prolog.formatDate(jsonData.edate) + " 23:59:59" : "";
      if (jsonData.sdate > jsonData.edate) {
        layer.msg("开始时间不能大于结束时间");
        return false;
      }
      jsonData.branchid = jsonData.branchid ? JSON.parse(jsonData.branchid)[0] : "";
      jsonData.shiptoCustomerId = jsonData.shiptoCustomerId ? JSON.parse(jsonData.shiptoCustomerId)[0] : "";
      jsonData.consignor = jsonData.consignor ? JSON.parse(jsonData.consignor)[0] : "";
      master_grid.setParams(JSON.stringify(jsonData));
      master_grid.reload();
    }
    // 重置
    if (name == "car_Reset") {
      master_grid.getToolBarForm().getDForm().setText("branchid", "");
      master_grid.getToolBarForm().getDForm().setText("shiptoCustomerId", "");
      master_grid.getToolBarForm().getDForm().setText("consignor", "");
      master_grid.getToolBarForm().clear();
      master_grid.getToolBarForm().setFormData({ sdate: sdate, edate: edate });
    }
    // 合并运单拆分
    if (name == "inSplitWaybill") {
      let datarowid = master_grid.getSelectedRowId();
      if (datarowid == null || datarowid == "") {
        layer.msg("请选择一行数据");
        return;
      }
      let dataId = master_grid.getRowData(datarowid);
      $("#splitWaybill_edit_grid").html("");
      $("#splitWaybill_edit_form").html("");
      edit_form = new PlgForm({
        renderer: "splitWaybill_edit_form",
        items: [
          { type: "settings", labelWidth: 90, labelAlign: "right" },
          {
            type: "row",
            list: [
              { type: "settings", position: "label-left", width: 300, labelWidth: 90 },
              { type: "hidden", name: "shipbillid", label: "id:", className: "layui-col-md3" },
              { type: "input", name: "shiptoCustomerName", label: "目的单位 :", className: "layui-col-md3", disabled: true },
              { type: "input", name: "rsumcases", label: "合并前件数 :", className: "layui-col-md3", disabled: true },
              { type: "input", name: "rsumgoodsvol", label: "合并前体积 :", className: "layui-col-md3", disabled: true },
              { type: "input", name: "rsumgoodsweight", label: "合并前重量 :", className: "layui-col-md3", disabled: true },
              { type: "input", name: "extend01", label: "合并订单数 :", className: "layui-col-md3", disabled: true },
              { type: "input", name: "sumcases", label: "合并后件数 :", className: "layui-col-md3", disabled: true },
              { type: "input", name: "sumgoodsvol", label: "合并后体积 :", className: "layui-col-md3", disabled: true },
              { type: "input", name: "sumgoodsweight", label: "合并后重量 :", className: "layui-col-md3", disabled: true },
              { type: "input", name: "memo", label: "合并备注 :", className: "layui-col-md3", disabled: true }
            ]
          }
        ]
      });
      utilAjaxGJ(UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/tmsOrderDivide/tmsOrderDivideHbQuery", "post", JSON.stringify({ shipbillid: dataId.shipbillid }), (data) => {
        edit_form.setFormData({
          shiptoCustomerName: dataId.shiptoCustomerName,
          shipbillid: dataId.shipbillid,
          memo: dataId.memo,
          rsumcases: data.data.rsumcases,
          rsumgoodsvol: data.data.rsumgoodsvol,
          rsumgoodsweight: data.data.rsumgoodsweight,
          sumcases: data.data.sumcases,
          sumgoodsvol: data.data.sumgoodsvol,
          sumgoodsweight: data.data.sumgoodsweight,
          extend01: data.data.extend01
        });
        saveType = 1;
        changePanel();
      }, "application/json");
    }
    // 运单拆分
    if (name == "splitWaybill") {
      splitWaybill_init();
    }
    // 拆分撤销
    if (name === "master_splitUndo") {
      Revoke();
    }
  });

  // 返回
  document.querySelector("#splitWaybill_back1").onclick = function () {
    changePanel();
  };
  // 保存
  document.querySelector("#splitWaybill_save").onclick = function () {
    setTimeout(() => {
      //信息比对
      let url = UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/tmsOrderDivide/divide";
      let datai = edit_form.getFormData();
      // 合并运单拆分
      if (saveType == 1) {
        url = UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/tmsOrderDivide/tmsOrderDivideHb";
        datai = { shipbillid: datai.shipbillid };
        //调用ajax方法
        utilAjaxGJ(url, "post", JSON.stringify(datai), function (data) {
          if (data.success) {
                changePanel();
            master_grid.reload();
          }
        }, "application/json");
      }
      // 运单拆分
      else {
        splitWaybill_save();
      }
    }, 200);
  };

  // 拆分撤销
  function Revoke() {
    let id = master_grid.getSelectedRowId();
    if (!id) {
      layer.msg("请选择一行数据");
      return;
    }
    let { shipbillid } = master_grid.getRowData(id);
    let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/tmsOrderDivide/revoke", type: "post", contentType: "application/json", data: JSON.stringify({ shipbillid }),
      success: function (data) {
        PlgDialog.close(pload);
        if (data.success) {
          PlgDialog.msg(data.message);
          master_grid.reload();
          return true;
        }
        setTimeout(() => { PlgDialog.alert(data.message || "接口调用失败"); }, 300);
        return false;

      }, error: function () { PlgDialog.close(pload); return false; }
    });
  }
  // 运单拆分
  function splitWaybill_init() {
    let datarowid = master_grid.getSelectedRowId();
    if (!datarowid) {
      layer.msg("请选择一行数据");
      return;
    }
    changePanel();
    saveType = 0;
    $("#splitWaybill_edit_grid").html("");
    $("#splitWaybill_edit_form").html("");
    GridObj = {};
    before_totalGrid_data = {};
    let selectData = master_grid.getRowData(datarowid);
    selectData.splitqty = 0;

    edit_form = new PlgForm({
      renderer: "splitWaybill_edit_form",
      items: [
        { type: "settings", labelWidth: 90, labelAlign: "right" },
        {
          type: "row",
          list: [
            { type: "input", name: "shipbillno", label: "运单号:", className: "layui-col-md6", disabled: true },
            { type: "input", name: "shipperName", label: "发货单位:", className: "layui-col-md6", disabled: true },
            { type: "input", name: "arriverName", label: "收货单位:", className: "layui-col-md6", disabled: true },
            { type: "input", name: "arriveAddress", label: "收货地址:", className: "layui-col-md6", disabled: true },
            { type: "input", name: "splitqty", label: "拆单数量:", className: "layui-col-md6", disabled: true },
            {
              type: "block", className: "layui-col-md6",
              list: [
                { type: "button", className: "btn-addBtn btn-normal", name: "editForm_add", value: "新增拆分行" }
              ]
            }
          ]
        }
      ]
    });
    edit_form.setFormData(selectData);
    edit_form.attachEvent("onButtonClick", function (name) {
      if (name === "editForm_add") {
        splitWaybill_editGrid_init();
        let { splitqty } = edit_form.getFormData();
        splitqty = Number(splitqty) + 1;
        edit_form.setFormData({ splitqty });
      }
    });

    splitWaybill_totalGrid_init(selectData);
  }
  // 运单拆分-汇总表格
  function splitWaybill_totalGrid_init(selectData) {
    var totalGrid_opts = {
      columns: [
        { id: "lineid", name: "id", type: "ro", width: "130", hidden: true },
        {
          id: "itemtype", name: "货品类型", type: "ro", render: (v) => {
            return getSelectValue(dataSelect.ITEM_TYPE, v);
          }
        },
        { id: "itemid", name: "货物ID", type: "ro" },
        { id: "itemname", name: "货物名称", type: "ro" },
        { id: "pcs", name: "件数", type: "ro" },
        { id: "weight", name: "重量", type: "ro" },
        { id: "vol", name: "体积", type: "ro" }
      ],
      fixedLast: false,
      multiselect: false,
        url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/tmsOrderDivide/detailed",
      type: "post",
      contentType: "application/json",
      params: JSON.stringify({ shipbillid: selectData.shipbillid, branchid: selectData.branchid }),
      page: false,
      totalCount: "totalCount"
    };
    let total_grid = new PlgGrid(totalGrid_opts);
    total_grid.renderTo("splitWaybill_edit_totalGrid");

    let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/tmsOrderDivide/detailed", type: "post", contentType: "application/json", data: JSON.stringify({ shipbillid: selectData.shipbillid, branchid: selectData.branchid }),
      success: function (res) {
        PlgDialog.close(pload);
        if (res.success) {
          res.data.forEach(item => {
            if (!before_totalGrid_data[item.itemid]) {
              before_totalGrid_data[item.itemid] = {
                pcs: item.pcs,
                vol: item.vol,
                weight: item.weight
              };
            }
            else {
              before_totalGrid_data[item.itemid].pcs = Prolog.floatOper(before_totalGrid_data[item.itemid].pcs, item.pcs, "+");
              before_totalGrid_data[item.itemid].vol = Prolog.floatOper(before_totalGrid_data[item.itemid].vol, item.vol, "+");
              before_totalGrid_data[item.itemid].weight = Prolog.floatOper(before_totalGrid_data[item.itemid].weight, item.weight, "+");
            }
          });
          total_grid.loadData({ data: { list: res.data } });
          return true;
        }
                return false;

      }, error: function () { PlgDialog.close(pload); return false; }
    });
  }
  // 运单拆分-明细表格拆分
  function splitWaybill_editGrid_init() {
    let strId = "splitWaybill_edit_grid_" + new Date().getTime();
    let dialog_id = "splitWaybill_dialog_" + strId;
    let str = "<div id='" + strId + "' clas='grid_nopadding'></div>";
    $("#splitWaybill_edit_grid").append(str);
    // 拆分table
    var splitOptions = {
      columns: [
        { id: "lineid", 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: "settings", labelWidth: 90, labelAlign: "right" },
        {
          type: "row",
          list: [
            {
              type: "block", className: "layui-col-md12 right",
              list: [
                { type: "button", className: "btn-normal", name: "editGrid_add", value: "新增明细行" },
                { type: "newcolumn" },
                { type: "button", className: "btn-danger", name: "editGrid_del", value: "删除拆分行" }
              ]
            }
          ]
        }
      ],
      pagebar: {
        buttons: [
          { text: "<i class='layui-icon layui-icon-delete'></i>删除", className: "plg-btn-normal", name: "page_del" }
        ]
      },
      fixedLast: false,
      multiselect: true,
        url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/pubCompany/queryCompanyConsignor",
      type: "post",
      contentType: "application/json",
      params: "{}",
      page: false,
      totalCount: "totalCount"
    };
    let edit_grid = new PlgGrid(splitOptions);
    edit_grid.renderTo(strId);
    edit_grid.getGrid().enableEditEvents(true, false, true);
    let lineid = new Date().getTime();
    edit_grid.addRow(lineid, { lineid });
    // 下拉赋值
    let combo_3 = edit_grid.getGrid().getCombo(3);
    dataSelect.ITEM_TYPE.forEach(v => {
      combo_3.put(v.value, v.text);
    });

    GridObj[strId] = edit_grid;

    edit_grid.attachToolBarEvent("onButtonClick", function (name) {
      // 新增
      if (name == "editGrid_add") {
        let id = Math.random();
        edit_grid.addRow(id, {});
      }
      // 删除
      if (name == "editGrid_del") {
        let { splitqty } = edit_form.getFormData();
        splitqty = Number(splitqty) - 1;
        edit_form.setFormData({ splitqty });

        delete GridObj[strId];
        $("#" + strId).remove();
      }
    });

    // 表格单击事件
    edit_grid.on("onRowSelect", function (id, index) {
      let { itemtype } = edit_grid.getRowData(id);
      let { branchid, shipbillid } = edit_form.getFormData();
      if (index === 4) {
        // 01-商品 02-货品
        if (!itemtype) {
          layer.msg("请选择货品类型");
          return false;
        }
        PlgDialog.open({
          title: "选择" + (itemtype === "01" ? "商品" : "货品"),
          shadeClose: true,
          type: 1,
          area: ["850px", "500px"],
          content: "<div id ='" + dialog_id + "'></div>"
        });
        $(".layui-layer-btn0").hide();
        // 注册商品、货品
        let item_grid = new PlgGrid({
          skin: "card",
          columns: [
            { id: "itemid", name: "id", type: "ro", width: "130", hidden: true },
            { id: "itemno", 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: "itemno", 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_BUSINESS_SERVICE+"/tmsOrderDivide/detailedPopup",
          pagebar: { type: "simple" },
          type: "post",
          params: JSON.stringify({ branchid, shipbillid, itemtype }),
          contentType: "application/json",
          page: true,
          totalCount: "totalCount"
        });
        item_grid.renderTo(dialog_id);
        item_grid.attachToolBarEvent("onButtonClick", function (name) {
          switch (name) {
            case "querycarr":
              var request = item_grid.getToolBarForm().getFormData();
              item_grid.setParams(JSON.stringify(Object.assign({}, request, { branchid, shipbillid, itemtype })));
              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();
          delete data.pcs;
          delete data.vol;
          delete data.weight;
          edit_grid.setCellValue(id, 4, data.itemid);
          edit_grid.setCellValue(id, 5, data.itemname);
          edit_grid.setCellValue(id, 6, "");
          edit_grid.setCellValue(id, 7, "");
          edit_grid.setCellValue(id, 8, "");
          edit_grid.setCellValue(id, 9, data.itemno);
          edit_grid.setUserData(id, "data", data);
          layer.closeAll();
        });
      }
    });

    // 离开事件
    edit_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) {
          edit_grid.setCellValue(rId, cInd, nValue);
          edit_grid.setCellValue(rId, 4, "");
          edit_grid.setCellValue(rId, 5, "");
          edit_grid.setCellValue(rId, 6, "");
          edit_grid.setCellValue(rId, 7, "");
          edit_grid.setCellValue(rId, 8, "");
          edit_grid.setCellValue(rId, 9, "");
        }
        else if (cInd === 6) { // 件数
          if (!positiveInteger.test(Number(nValue))) {
            layer.msg("请输入正整数");
            return;
          }
          edit_grid.setCellValue(rId, 6, Number(nValue));
        }
        else if (cInd === 7 || cInd === 8) {
          if (!positveOrZero.test(nValue)) {
            layer.msg("请输入正数");
            return;
          }
          edit_grid.setCellValue(rId, cInd, Number(nValue));
        }
        else {
          edit_grid.setCellValue(rId, cInd, nValue);
        }
      }
      return true;
    });
    // 删除
    edit_grid.attachPageBarEvent(function (name, ids) {
      layer.open({
        title: "删除",
        content: "还未保存，是否删除？",
        btn: ["确认", "取消"],
        yes: function () {
          ids.split(",").forEach(id => {
            edit_grid.deleteRow(id);
          });
          layer.closeAll();
        }
      });
    });
  }
  // 运单拆分保存
  function splitWaybill_save() {
    let list = [];

    let after_totalGrid_data = {};
    for (const key in GridObj) {

      // 拆分的汇总数据
      let formData = edit_form.getFormData();
      formData.rsumcases = 0;
      formData.rsumgoodsvol = 0;
      formData.rsumgoodsweight = 0;
      formData.sumcases = 0;
      formData.sumgoodsvol = 0;
      formData.sumgoodsweight = 0;
      formData.detaileds = [];
      list.push(formData);

      let split_grid = GridObj[key];
      let indexNum = split_grid.getGrid().getRowsNum();
      for (let i = 0; i < indexNum; i++) {
        const element = split_grid.getRowData(split_grid.getRowId(i));

        // 所有拆分汇总、比对
        if (!after_totalGrid_data[element.itemid]) {
          after_totalGrid_data[element.itemid] = {
            pcs: element.pcs,
            vol: element.vol,
            weight: element.weight
          };
        }
        else {
          after_totalGrid_data[element.itemid].pcs = Prolog.floatOper(after_totalGrid_data[element.itemid].pcs, element.pcs, "+");
          after_totalGrid_data[element.itemid].vol = Prolog.floatOper(after_totalGrid_data[element.itemid].vol, element.vol, "+");
          after_totalGrid_data[element.itemid].weight = Prolog.floatOper(after_totalGrid_data[element.itemid].weight, element.weight, "+");
        }

        // 保存的汇总
        formData.detaileds.push(element);
        formData.rsumcases = Prolog.floatOper(formData.rsumcases, element.pcs, "+");
        formData.rsumgoodsvol = Prolog.floatOper(formData.rsumgoodsvol, element.vol, "+");
        formData.rsumgoodsweight = Prolog.floatOper(formData.rsumgoodsweight, element.weight, "+");
        formData.sumcases = formData.rsumcases;
        formData.sumgoodsvol = formData.rsumgoodsvol;
        formData.sumgoodsweight = formData.rsumgoodsweight;
      }
    }

    console.log(before_totalGrid_data, after_totalGrid_data);

    if (Object.keys(before_totalGrid_data).length !== Object.keys(after_totalGrid_data).length) {
      layer.msg("拆分前后货物数量不匹配");
      return false;
    }
    for (const key in before_totalGrid_data) {
      if (before_totalGrid_data[key].pcs != after_totalGrid_data[key].pcs || before_totalGrid_data[key].vol != after_totalGrid_data[key].vol || before_totalGrid_data[key].weight != after_totalGrid_data[key].weight) {
        layer.msg("拆分前后货物数量不匹配");
        return false;
      }
    }


    let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/tmsOrderDivide/divide", type: "post", contentType: "application/json", data: JSON.stringify(list),
      success: function (res) {
        PlgDialog.close(pload);
        if (res.success) {
          PlgDialog.msg(res.message);
          changePanel();
          master_grid.reload();
          return true;
        }
                return false;

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