/**
   * guoj
   * 2020.06.23
   * 发运确认
      */
    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 startTime = Prolog.formatDate(new Date(), "%YY-%MM") + "-01 00:00:00";
  var endTime = Prolog.formatDate(new Date()) + " 23:59:59";
  let shipConfirmFromData, shipConfirmEditFromData;
  let PoSingle_from1, PoSingle_from2;
  var grid;
  let grid2;
  var dataSelete = {};
  var hhmmValidate = /^([0-1][0-9]|2[0-3]):[0-5][0-9]$/; // hh:mm正则表达式

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

  //发货仓库table
  var consignor_Table = {
    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/queryCompanyBranch", //数据接口
    type: "post", //数据提交方式，默认为get
    contentType: "application/json",
    params: JSON.stringify({ companytype: "S" }), //查询提交参数，分页参数默认为pageNum,pageSize
    page: true, //是否启用分页
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };
  //组织table
  var branchTable = {
    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 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 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
  };

  //分页参数
  var opts = {
    //terrace显示全部，card分页显示
    skin: "card",
    //renderer:"grid",
    columns: [
      { id: "shipbillid", name: "运单id", type: "ro", width: "130", hidden: true },
      { id: "shipbillno", name: "运单号", type: "ro", width: 120 },
      { 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: "lineno", name: "线路编号", type: "ro", width: 120 },
      { id: "linenane", name: "线路名称", type: "ro", width: 140 },
      { id: "billdate", name: "单据时间", type: "ro", width: 80 },
      { id: "urgentIdentifyName", name: "紧急标识", type: "ro", width: 80 },
      { id: "refbillno", name: "业务单据号", type: "ro", width: 80 },
      { id: "refbilltypeName", name: "业务单据类型", type: "ro", width: 100 },
      { id: "carrierName", name: "承运商名称", type: "ro", width: 100 },
      { id: "shiptoCustomerName", name: "客户名称", type: "ro", width: 100 },
      { id: "shiptoAddress", name: "客户地址", type: "ro", width: 120 },
      { id: "reqshipmentdate", name: "预计发货日期", type: "ro", width: 120 },
      { id: "reqarrivvaldate", name: "要求到货日期", type: "ro", width: 120 },
      { id: "rsumcases", name: "件数", type: "ro", width: 120 },
      { id: "rsumgoodsweight", name: "总重量", type: "ro", width: 120 },
      { id: "rsumgoodsvol", name: "总体积", type: "ro", width: 120 },
      { id: "memo", name: "备注", type: "ro", width: 240 },
      {
        id: "op", name: "操作", type: "button", align: "left", fixed: "right", width: 80, render: function () {
          return "运单修改^shipConfirm_edit";
        }
      }
    ],
    multiselect: true,
    toolbar: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          { type: "calendar", readonly: true, name: "startTime", className: "layui-col-md3", label: "开始时间:", value: startTime },
          { type: "calendar", readonly: true, name: "endTime", className: "layui-col-md3", label: "结束时间:", value: endTime },
          {
            className: "layui-col-md3",
            type: "selectTable",
            placeholder: "请选择配送中心",
            readonly: false,
            table: branchTable,
            tableWidth: 500,
            tableHeight: 400,
            fieldText: "companyname",
            fieldValue: "companycode",
            name: "branchidList",
            label: "配送中心:",
            listener: function (Grid) {
              setMethod(Grid, branchTable, function () { });
            }
          },
          { type: "hidden", name: "branchid", label: "配送中心:" },
          { type: "input", name: "shipbillno", label: "运单号:", className: "layui-col-md3" },
          { type: "input", name: "refbillno", label: "业务单号:", className: "layui-col-md3" },
          { type: "combo", name: "urgentIdentify", className: "layui-col-md3", label: "是否急单:", options: dataSelete.URG_FLG },
          {
            type: "block", className: "layui-col-md3 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-md3 right",
            list: [
              { type: "button", className: "btn-addBtn btn-normal expdataShip", value: "批量导入" },
              { type: "newcolumn" },
              { type: "button", className: "btn-addBtn btn-normal", name: "clear", value: "取 消" },
              { type: "newcolumn" },
              { type: "button", className: "btn-addBtn btn-normal", name: "export", value: "导 出" }
            ]
          }
        ]
      }],

    url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/shipConfirm/query",//数据接口
    type: "post",//数据提交方式，默认为get
    contentType: "application/json",
    params: JSON.stringify({ startTime, endTime }),//查询提交参数，分页参数默认为pageNum,pageSize
    fixedLast: true, // 开启固定列，固定最后一行，倒数第二列不能隐藏
    page: true, //是否启用分页
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };
  //分页参数 pageSize pageNum
  grid = new PlgGrid(opts);
  grid.renderTo("shipConfirm_zhu");
  grid.loadData();
  grid.attachEvent("onDataReady", function () {
    let indexNum = grid.getGrid().getRowsNum();
    for (let i = 0; i < indexNum; i++) {
      const id = grid.getRowId(i);
      const element = grid.getRowData(id);
      if (element.urgentIdentify == "01") grid.getGrid().setRowColor(id, "#F56C6C");
    }
  });
  //导入
  uploadImportGJ(UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/shipConfirm/import", ".expdataShip", (data) => {
    layer.msg(data.message);
    grid2.getGrid().clearAll();
  });
  //按钮添加方法
  grid.attachToolBarEvent("onButtonClick", function (name) {
    //查询
    if (name == "querycarr") {
      let request = grid.getToolBarForm().getFormData();
      request.startTime = request.startTime ? Prolog.formatDate(request.startTime) + " 00:00:00" : "";
      request.endTime = request.endTime ? Prolog.formatDate(request.endTime) + " 23:59:59" : "";
      if (request.startTime > request.endTime) {
        layer.msg("开始时间不能大于结束时间");
        return false;
      }
      request.branchid = request.branchidList ? JSON.parse(request.branchidList)[0] : "";
      dealNullQueryCondition(request);
      grid.setParams(JSON.stringify(request));
      grid.reload();
      grid2.clearAll();
    }
    //重置
    if (name == "car_Reset") {
      grid.getToolBarForm().clear();
      grid.getToolBarForm().setFormData({ startTime: startTime, endTime: endTime });
      grid.getToolBarForm().getDForm().setText("branchidList", "");
    }
    //发运确认
    if (name == "shipConfirm_print") {
      let data = getDeleteAll(grid);
      if (data == null || data == "") {
        layer.msg("请选择一行");
        return;
      }
      var dataid = grid.getCheckedIds();
      if (dataid == null || dataid == "") {
        dataid = grid.getSelectedRowId();
      }
      PlgDialog.open({
        title: "发运确认",
        offset: ["150px", "420px"],
        type: 1,
        shadeClose: true, //点击遮罩关闭
        content: "<div id=\"shipConfirmEjectGJ\" class=\"grid-container-full\" ></div>",
        area: ["550px", "300px"],
        btn: ["确定", "取消"],
        yes: function (index) {
          let dataitem = PoSingle_from1.getFormData();
          for (var i = 0; i < data.length; i++) {
            data[i] = grid.getRowData(data[i]);
            data[i].estimateTime = FormatTime(dataitem.estimateTime);
            data[i].urgentIdentify = dataitem.urgentIdentify;
            data[i].remark = dataitem.remark;
            data[i].branchid = dataitem.branchid;
            data[i].branchname = dataitem.branchname;
          }
          utilAjaxGJ(UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/shipConfirm/shipmentConfirm", "post", JSON.stringify(data), () => {
            layer.msg("成功");
            layer.close(index);
            grid.reload();
            grid2.clearAll();
          }, "application/json");
          //按钮【按钮一】的回调
        },
        btn2: function (index) {
          //按钮【按钮二】的回调
          layer.close(index);
        }
      });
      PoSingle_from1 = new PlgForm(shipConfirmFromData);
      PoSingle_from1.setFormData({ shipbillno: dataid });
    }
    //下载模板
    if (name == "dowloadMuban") {
      window.open("/download/发运导入确认.xlsx");
    }
    // 导出
    if (name === "export") {
      let request = grid.getToolBarForm().getFormData();
      request.startTime = request.startTime ? Prolog.formatDate(request.startTime) + " 00:00:00" : "";
      request.endTime = request.endTime ? Prolog.formatDate(request.endTime) + " 23:59:59" : "";
      if (request.startTime > request.endTime) {
        layer.msg("开始时间不能大于结束时间");
        return false;
      }
      request.branchid = request.branchidList ? JSON.parse(request.branchidList)[0] : "";
      request.pageNum = 0;
      request.pageSize = 0;
      dealNullQueryCondition(request);
      Prolog.exportFile(UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/shipConfirm/export", "发运导入确认.xls", "application/json", "post", request);
    }
    // 取消
    if (name == "clear") {
      let data = getDeleteAll(grid);
      if (data == null || data == "") {
        layer.msg("请选择一行");
        return;
      }
      for (var i = 0; i < data.length; i++) {
        data[i] = {
          "shipbillid": data[i]
        };
      }
      utilAjaxGJ(UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/shipConfirm/cancel", "post", JSON.stringify(data), (res) => {
        if (res.success) {
          layer.msg("成功");
          grid.reload();
          grid2.clearAll();
        }
      }, "application/json");
    }

  });

  // 运单修改
  window.shipConfirm_edit = function (rid, rdata) {
    PlgDialog.open({
      title: "运单修改",
      offset: ["150px", "420px"],
      type: 1,
      shadeClose: true, //点击遮罩关闭
      content: "<div id=\"shipConfirmEdit\" class=\"grid-container-full\" ></div>",
      area: ["550px", "300px"],
      btn: ["确定", "取消"],
      yes: function () {
        let { shipbillid, urgentIdentify, estimateTime, branchid, branchname, lineno, linenane, carrierId, carrierCode, carrierName } = PoSingle_from2.getFormData();
        if (estimateTime && !hhmmValidate.test(estimateTime)) {
          layer.msg("请输入正确的时间格式（例01:00）");
          return;
        }
        if (!branchid) {
          layer.msg("请选择配送中心");
          return;
        }
        if (!carrierId) {
          layer.msg("请选择承运商");
          return;
        }
        let request = {
          //list: [{ shipbillid }],
          shipbillid,
          urgentIdentify,
          estimateTime,
          branchid,
          branchname,
          lineno, linenane, carrierId, carrierCode, carrierName
        };
        let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
        Prolog.ajax({
          url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/shipConfirm/update", type: "post", contentType: "application/json", data: JSON.stringify(request),
          success: function (data) {
            PlgDialog.close(pload);
            if (data.success) {
              layer.closeAll();
              PlgDialog.msg(data.message);
              grid.reload();
              grid2.clearAll();
              return true;
            }
            return false;

          }, error: function () { PlgDialog.close(pload); return false; }
        });
      }
    });
    PoSingle_from2 = new PlgForm(shipConfirmEditFromData);
    rdata.branchnameList = rdata.branchid ? JSON.stringify([rdata.branchid]) : "[]";
    rdata.linenoList = rdata.lineno ? JSON.stringify([rdata.lineno]) : "[]";
    rdata.carrierList = rdata.carrierId ? JSON.stringify([rdata.carrierId]) : "[]";
    PoSingle_from2.setFormData(rdata);
    PoSingle_from2.setText("branchnameList", rdata.branchname || "");
    PoSingle_from2.setText("linenoList", rdata.linenane || "");
    PoSingle_from2.setText("carrierList", rdata.carrierName || "");
  };

  //分页参数
  var opts2 = {
    //terrace显示全部，card分页显示
    skin: "card",
    //renderer:"grid",
    columns: [
      { id: "lineid", name: "id", type: "ro", width: "80", hidden: true },
      { id: "shipbillno", name: "运单号", type: "ro" },
      { id: "itemno", name: "物料编号", type: "ro" },
      { id: "itemname", name: "物料名称", type: "ro" },
      {
        id: "itemtype", name: "物料类型", type: "ro", render: (v) => {
          return getSelectValue(dataSelete.ITEM_TYPE, v);
        }
      },
      { id: "pcs", name: "件数", type: "ro" },
      { id: "weight", name: "重量", type: "ro" },
      { id: "vol", name: "体积", type: "ro" },
      { id: "remark", name: "备注", type: "ro" }
    ],
    multiselect: false,

    url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/shipConfirm/detailQuery",//数据接口
    type: "post",//数据提交方式，默认为get
    contentType: "application/json",
    params: "{}",//查询提交参数，分页参数默认为pageNum,pageSize
    page: true, //是否启用分页
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };
  //分页参数 pageSize pageNum
  grid2 = new PlgGrid(opts2);
  grid2.renderTo("shipConfirm_xi");
  //单击事件
  grid.on("onRowSelect", function (id) {
    let rdata = grid.getRowData(id);
    grid2.setParams(JSON.stringify({ "shipbillid": id, "status": "10", branchid: rdata.branchid }));
    grid2.reload();
  });

  shipConfirmFromData = {
    renderer: "shipConfirmEjectGJ",
    items: [
      { type: "settings", PoSingle: "label-left", labelWidth: 90 },
      { type: "input", name: "shipbillno", label: "运单号:", width: 150 },
      { type: "newcolumn" },
      { type: "calendar", name: "estimateTime", label: "计划完成时间:", width: 150 },
      { type: "newcolumn" },
      {
        width: 150,
        type: "selectTable",
        placeholder: "请选择发货仓库",
        readonly: false,
        table: consignor_Table,
        tableWidth: 500,
        tableHeight: 400,
        fieldText: "companyname",
        fieldValue: "companycode",
        name: "branchname1",
        label: "发货仓库:",
        listener: function (consignorGrid) {
          setMethod(consignorGrid, consignor_Table, function (data) {
            var fromdata = PoSingle_from1.getFormData();
            data = fromdata.branchname1.length == 2 ? "" : data;
            var datad = {};
            datad.branchid = data.companyid;
            datad.branchname = data.companyname;
            PoSingle_from1.setFormData(datad);
          });
        }
      },
      { type: "newcolumn" },
      { type: "combo", readonly: true, name: "urgentIdentify", label: "急单标:", width: 150, options: dataSelete.URG_FLG },
      { type: "newcolumn" },
      { type: "input", name: "remark", label: "备注:", width: 400 },
      { type: "hidden", name: "branchid", label: "备注:" },
      { type: "hidden", name: "branchname", label: "备注:" }
    ]
  };
  shipConfirmEditFromData = {
    renderer: "shipConfirmEdit",
    items: [
      { type: "settings", PoSingle: "label-left", labelWidth: 90 },
      { type: "input", name: "shipbillno", label: "运单号:", width: 150, disabled: true, required: true },
      { type: "newcolumn" },
      {
        width: 150,
        type: "selectTable",
        placeholder: "请选择配送中心",
        readonly: false,
        table: consignor_Table,
        tableWidth: 500,
        tableHeight: 400,
        fieldText: "companyname",
        fieldValue: "companycode",
        name: "branchnameList",
        label: "配送中心:<span class='dhxform_item_required'>*</span>",
        listener: {
          "afterSelect": function (isSelected, selectId, sgrid) {
            let sdata = sgrid.getRowData(selectId);
            PoSingle_from2.setFormData({
              branchid: isSelected ? sdata.companycode : "",
              branchname: isSelected ? sdata.companyname : ""
            });
          }
        }
      },
      { type: "input", name: "branchid", label: "配送中心id:", width: 150, hidden: true },
      { type: "input", name: "branchname", label: "配送中心名称:", width: 150, hidden: true },
      { type: "newcolumn" },
      { type: "combo", readonly: true, name: "urgentIdentify", label: "急单标识:", width: 150, options: dataSelete.URG_FLG },
      { type: "newcolumn" },
      { type: "input", name: "estimateTime", label: "计划完成时间:", width: 150 },
      { type: "newcolumn" },
      {
        width: 150,
        type: "selectTable",
        placeholder: "请选择线路",
        readonly: false,
        table: lineTable,
        tableWidth: 500,
        tableHeight: 400,
        fieldText: "lineName",
        fieldValue: "lineCode",
        name: "linenoList",
        label: "线路:<span class='dhxform_item_required'>*<span>",
        listener: {
          "init": function (Grid) {
            // 注册按钮事件
            Grid.attachToolBarEvent("onButtonClick", function (name) {
              switch (name) {
                case "querycarr":
                  var formData = Grid.getToolBarForm().getFormData();
                  Grid.setParams(JSON.stringify(formData));
                  Grid.reload();
                  break;
                case "car_Reset":
                  Grid.getToolBarForm().clear();
                  break;
              }
            });
          },
          "afterSelect": function (isSelected, selectId, sgrid) {
            let sdata = sgrid.getRowData(selectId);
            PoSingle_from2.setFormData({
              lineno: isSelected ? sdata.lineCode : "",
              linenane: isSelected ? sdata.lineName : ""
            });
          }
        }
      },
      { type: "hidden", name: "lineno", label: "" },
      { type: "hidden", name: "linenane", label: "" },
      { type: "newcolumn" },
      {
        width: 150,
        type: "selectTable",
        placeholder: "请选择承运商",
        readonly: false,
        table: carrierTable,
        tableWidth: 500,
        tableHeight: 400,
        fieldText: "companyname",
        fieldValue: "companyid",
        name: "carrierList",
        label: "承运商:<span class='dhxform_item_required'>*<span>",
        listener: {
          "init": function (Grid) {
            // 注册按钮事件
            Grid.attachToolBarEvent("onButtonClick", function (name) {
              switch (name) {
                case "querycarr":
                  var { companycode } = Grid.getToolBarForm().getFormData();
                  Grid.setParams(JSON.stringify({ companycode }));
                  Grid.reload();
                  break;
                case "car_Reset":
                  Grid.getToolBarForm().clear();
                  break;
              }
            });
          },
          "afterSelect": function (isSelected, selectId, sgrid) {
            let sdata = sgrid.getRowData(selectId);
            PoSingle_from2.setFormData({
              carrierId: isSelected ? sdata.companyid : "",
              carrierCode: isSelected ? sdata.companycode : "",
              carrierName: isSelected ? sdata.companyname : ""
            });
          }
        }
      },
      { type: "hidden", name: "carrierId", label: "" },
      { type: "hidden", name: "carrierCode", label: "" },
      { type: "hidden", name: "carrierName", label: "" }
    ]
  };
};