/**
 * zzx
 * 2020.10.14
 * 装车扫描-运输调度
 */
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 unscanned_grid, scanned_grid;
  var selectBranchid, selectloadbillid, selectloadbillno; // 选中的数据
  var textareas;

  // 配送中心table
  var branchTable = {
    // terrace显示全部，card分页显示
    skin: "card",
    // renderer:"grid",
    columns: [
      { id: "companyid", name: "id", type: "ro", width: "130", hidden: true },
      { id: "companycode", name: "配送中心编号", type: "ro" },
      { id: "companyname", name: "配送中心名称", type: "ro" }
    ],
    multiselect: false,
    toolbar: [
      { type: "settings", position: "label-left", width: 200, labelWidth: 100 },
      {
        type: "block", id: "bk", blockOffset: 0, list: [
          { type: "input", name: "companycode", label: "配送中心编号:", width: 120 },
          { type: "newcolumn" },
          { type: "button", name: "querycarr", value: "查询" },
          { type: "newcolumn" },
          { type: "button", name: "car_Reset", value: "重置" }
        ]
      }
    ],
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/pubCompany/queryCompanyBranch",
    pagebar: { type: "simple" },
    type: "post", // 数据提交方式，默认为get
    params: JSON.stringify({ companytype: "S" }), // 查询提交参数，分页参数默认为pageNum,pageSize
    contentType: "application/json",
    page: true, // 是否启用分页
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };

  // 未扫rgrid
  var unscanned_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, hidden: true },
      { 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: "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, hidden: true },
      { id: "urgentIdentifyName", name: "紧急标识", type: "ro", width: 120 },
      { 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 },
      { 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: "selectTable",
            className: "layui-col-md3",
            placeholder: "请选择当前站点",
            readonly: false,
            table: branchTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "companyname",
            fieldValue: "companyid",
            name: "branchidList",
            label: "当前站点:<span class='dhxform_item_required'>*<span>",
            listener: {
              "init": function (Grid) {
                // 注册按钮事件
                Grid.attachToolBarEvent("onButtonClick", function (name) {
                  switch (name) {
                    case "querycarr":
                      var { companycode } = Grid.getToolBarForm().getFormData();
                      Grid.setParams(JSON.stringify({ companycode, companytype: "S" }));
                      Grid.reload();
                      break;
                    case "car_Reset":
                      Grid.getToolBarForm().clear();
                      break;
                  }
                });
              },
              "afterSelect": function (isSelected, selectId, sgrid) {
                let sdata = sgrid.getRowData(selectId);
                selectBranchid = isSelected ? sdata.companyid : "";
                textareas[2].focus();
                // 清空数据
                unscanned_grid.clearAll();
                scanned_grid.clearAll();
                unscanned_grid.getToolBarForm().setItemLabel("info", "");
                scanned_grid.getToolBarForm().setItemLabel("info", "");
              }
            }
          },
          {
            type: "block", className: "layui-col-md9",
            list: [
              { type: "button", className: "btn-normal", name: "master_orderConfirm", value: "整单确认" },
              { type: "newcolumn" },
              { type: "button", className: "btn-normal", name: "master_loadingBillConfirm", value: "装车确认" }
            ]
          },
          { type: "input", className: "layui-col-md6 scan", name: "shipbillno", label: "扫描单号:" },
          { type: "input", className: "layui-col-md6", name: "reason", label: "扫描结果:", rows: 3, readonly: true },
          { type: "label", className: "layui-col-md12", name: "info", label: "", labelWidth: 800 }
        ]
      }
    ],
    fixedLast: false, // 开启固定列，固定最后一行，倒数第二列不能隐藏
    multiselect: false, // 是否支持多选
    url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/loadingScan/scan/v1.0", // 数据接口
    type: "post", // 数据提交方式，默认为get
    params: "{}", // 查询提交参数，分页参数默认为pageNum,pageSize
    page: false, // 是否启用分页
    contentType: "application/json",
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  unscanned_grid = new PlgGrid(unscanned_grid_opts);
  unscanned_grid.renderTo("schedulingLoadingScan_unscanned_grid");
  // 按钮点击事件
  unscanned_grid.attachToolBarEvent("onButtonClick", function (name) {
    switch (name) {
      case "master_orderConfirm":
        if (!selectloadbillid) {
          layer.msg("请扫描装车单号");
          return false;
        }
        orderConfirm("orderConfirm");
        break;

      case "master_loadingBillConfirm":
        if (!selectloadbillid) {
          layer.msg("请扫描装车单号");
          return false;
        }
        orderConfirm("loadingBillConfirm");
        break;
    }
  });

  textareas = document.getElementById("schedulingLoadingScan_unscanned_grid").getElementsByTagName("input");
  setTimeout(() => {
    textareas[2].focus();
  }, 500);
  textareas[2].onkeydown = function (key) {
    if (key.key == "Enter") {
      const { shipbillno } = unscanned_grid.getToolBarForm().getFormData();
      if (!selectBranchid) {
        layer.msg("请选择当前站点");
        return false;
      }
      if (!shipbillno) {
        layer.msg("请扫描单号");
        textareas[2].focus();
        return false;
      }
      /**
       * 若已选择单据，此处控制未扫已扫
       * 若未选择单据，此处扫描更新数据
       */
      if (selectloadbillid) {
        let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
        Prolog.ajax({
          url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/loadingScan/waybillScan/v1.0", type: "post", contentType: "application/json", data: JSON.stringify({
            branchid: selectBranchid,
            loadbillid: selectloadbillid,
            shipbillno
          }),
          success: function (res) {
            PlgDialog.close(pload);
            if (res.success) {
              unscanned_grid.getToolBarForm().setFormData({
                shipbillno: "",
                reason: res.data
              });
              textareas[2].focus();
              scan();
              return true;
            }
                        return false;

          }, error: function () { PlgDialog.close(pload); return false; }
        });
      }
      else {
        selectloadbillno = shipbillno;
        scan(true);
      }
    }
  };

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

  // 刷新主页面2个grid isFirst-true 通过扫描更新主单
  function scan(isFirst) {
    let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/loadingScan/scan/v1.0", type: "post", contentType: "application/json", data: JSON.stringify({
        branchid: selectBranchid,
        loadbillno: selectloadbillno
      }),
      success: function (res) {
        PlgDialog.close(pload);
        if (res.success) {
          layer.closeAll();

          unscanned_grid.clearAll();
          scanned_grid.clearAll();
          unscanned_grid.loadData({ "data": { "list": res.data.tmsLoadingBillDetailDTOW } });
          scanned_grid.loadData({ "data": { "list": res.data.tmsLoadingBillDetailDTOY } });
          selectloadbillid = res.data.loadbillid;
          unscanned_grid.getToolBarForm().setItemLabel("info", "装车单【" + selectloadbillno + "】未扫描装车单据");
          scanned_grid.getToolBarForm().setItemLabel("info", "装车单【" + selectloadbillno + "】已扫描装车单据");

          if (isFirst) {
            unscanned_grid.getToolBarForm().setFormData({
              shipbillno: "",
              reason: "装车单【" + selectloadbillno + "】扫描成功"
            });
          }
          textareas[2].focus();
        }
        else {
                    if (isFirst) {
            unscanned_grid.getToolBarForm().setItemLabel("info", "");
            scanned_grid.getToolBarForm().setItemLabel("info", "");
            unscanned_grid.getToolBarForm().setFormData({
              shipbillno: "",
              reason: "装车单【" + selectloadbillno + "】扫描失败"
            });
          }
          selectloadbillno = "";
        }
      }, error: function () { PlgDialog.close(pload); return false; }
    });
  }

  // 整单确认、装车确认
  function orderConfirm(event) {
    let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/loadingScan/" + event + "/v1.0", type: "post", contentType: "application/json", data: JSON.stringify({
        loadbillid: selectloadbillid,
        branchid: selectBranchid
      }),
      success: function (res) {
        PlgDialog.close(pload);
        if (res.success) {
          selectloadbillid = "";
          selectloadbillno = "";
          unscanned_grid.clearAll();
          scanned_grid.clearAll();
          unscanned_grid.getToolBarForm().setFormData({ reason: res.message });
          unscanned_grid.getToolBarForm().setItemLabel("info", "");
          scanned_grid.getToolBarForm().setItemLabel("info", "");
          return true;
        }
                return false;

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

  // 已扫grid
  var scanned_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, hidden: true },
      { 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: "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, hidden: true },
      { id: "urgentIdentifyName", name: "紧急标识", type: "ro", width: 120 },
      { 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 },
      { 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 "删除^schedulingScanned_del";
        }
      }
    ],
    toolbar: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          { type: "label", className: "layui-col-md12", name: "info", label: "", labelWidth: 800 }
        ]
      }
    ],
    pagebar: {
      buttons: [
        { text: "<i class='layui-icon layui-icon-delete'></i>删除", className: "plg-btn-normal", name: "scanned_delete" }
      ]
    },
    fixedLast: true, // 开启固定列，固定最后一行，倒数第二列不能隐藏
    multiselect: true, // 是否支持多选
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/vehicleManage/queryTVmFuelRecord", // 数据接口
    type: "post", // 数据提交方式，默认为get
    params: "{}", // 查询提交参数，分页参数默认为pageNum,pageSize
    page: false, // 是否启用分页
    contentType: "application/json",
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  scanned_grid = new PlgGrid(scanned_grid_opts);
  scanned_grid.renderTo("schedulingLoadingScan_scanned_grid");
  scanned_grid.attachPageBarEvent(function (name, ids) {
    if (name === "scanned_delete") {
      const list = ids.split(",").map(item => {
        const element = scanned_grid.getRowData(item);
        return {
          loadbillid: selectloadbillid,
          shipbillno: element.shipbillno,
          status: "20"
        };
      });
      loadingBillDelete(list);
    }
  });
  // 删除
  window.schedulingScanned_del = function (rid, rdata) {
    layer.open({
      title: "删除",
      content: "还未保存，是否删除？",
      btn: ["确认", "取消"],
      yes: function () {
        loadingBillDelete([{
          branchid: selectBranchid,
          loadbillid: selectloadbillid,
          shipbillno: rdata.shipbillno,
          status: "20"
        }]);
      }
    });
  };
  function loadingBillDelete(list) {
    let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/loadingScan/loadingBillDelete/v1.0", type: "post", contentType: "application/json", data: JSON.stringify(list),
      success: function (res) {
        PlgDialog.close(pload);
        if (res.success) {
          textareas[2].focus();
          scan();
          unscanned_grid.getToolBarForm().setFormData({
            shipbillno: "",
            reason: res.message
          });
          return true;
        }
                return false;

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