/**
   * 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 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" }], function (data) {
    data.data.TMS_REF_BILLTYPE.unshift({ "text": "", "value": "" });
    dataSelect = data.data;
  });
  let ddfrom;
  //跳转页面
  var carousel = layui.carousel;
  var car = carousel.render({
    elem: "#waybillConsolidation_div",
    autoplay: false,
    index: 0,
    arrow: "none",
    indicator: "none",
    anim: "fade",
    width: "100%", //设置容器宽度
    height: "100%"
  });
  //跳转方法
  var tt = "waybillConsolidation_zhu_div";

  function changePanel() {
    car.slide(tt);
    tt = tt == "waybillConsolidation_xi1" ? "waybillConsolidation_zhu_div" : "waybillConsolidation_xi1";
  }
  var grid;
  //配送中心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 = {
    //terrace显示全部，card分页显示
    skin: "card",
    //renderer:"grid",
    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: "shiptoCustomerName", name: "客户名称", type: "ro", width: "80" },
      { id: "shiptoAddress", 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: true,
    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-md2 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-md1 right",
            list: [
              { type: "button", className: "btn-addBtn btn-normal", name: "returnSave", value: "运单合并" }
            ]
          }
        ]
      }],
    beforeLoadData: function (res) {
      res.data.list.forEach((item, index) => {
        item.INDEX = index + "";
      });
      return res;
    },
    url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/tmsOrderCombine/query",//数据接口
    type: "post",//数据提交方式，默认为get
    contentType: "application/json",
    params: JSON.stringify({ sdate: sdate, edate: edate }),//查询提交参数，分页参数默认为pageNum,pageSize
    page: true, //是否启用分页
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };
  //分页参数 pageSize pageNum
  grid = new PlgGrid(opts);
  grid.renderTo("waybillConsolidation_zhu");
  grid.getToolBarForm().setFormData({ "systemId": "prolog-healthy-wms" });
  grid.loadData();
  //按钮添加方法
  grid.attachToolBarEvent("onButtonClick", function (name) {
    //查询
    if (name == "querycarr") {
      var jsonData = 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] : "";
      grid.setParams(JSON.stringify(jsonData));
      grid.reload();
    }
    //重置
    if (name == "car_Reset") {
      grid.getToolBarForm().getDForm().setText("branchid", "");
      grid.getToolBarForm().getDForm().setText("shiptoCustomerId", "");
      grid.getToolBarForm().getDForm().setText("consignor", "");
      grid.getToolBarForm().clear();
      grid.getToolBarForm().setFormData({ sdate: sdate, edate: edate });
    }
    //运单合并
    if (name == "returnSave") {
      let dataIds = getDeleteAll(grid);
      if (dataIds == null || dataIds == "") {
        layer.msg("请选择一行数据");
        return;
      }
      let dataItem = {
        casesBefore: 0,
        volBefore: 0,
        weightBefore: 0
      };
      if (dataIds.length < 2) {
        layer.msg("最少选择两条数据");
        return;
      }
      for (var i = 0; i < dataIds.length; i++) {
        dataIds[i] = grid.getRowData(dataIds[i]);
        if (i != 0 && dataIds[0].shiptoCustomerId != dataIds[i].shiptoCustomerId) {
          layer.msg("运单合并客户必须一致");
          return;
        }
        if (i != 0 && dataIds[0].billtype != dataIds[i].billtype) {
          layer.msg("运单合并运单类型必须一致");
          return;
        }
        if (i != 0 && dataIds[0].branchid != dataIds[i].branchid) {
          layer.msg("运单合并配送中心必须一致");
          return;
        }

        dataItem.casesBefore = Prolog.floatOper(dataItem.casesBefore, dataIds[i].rsumcases, "+");
        dataItem.volBefore = Prolog.floatOper(dataItem.volBefore, dataIds[i].rsumgoodsvol, "+");
        dataItem.weightBefore = Prolog.floatOper(dataItem.weightBefore, dataIds[i].rsumgoodsweight, "+");
        dataItem.shiptoCustomerName = dataIds[i].shiptoCustomerName;
        dataItem.shipbillid = dataIds[i].shipbillid;
      }
      dataItem.orderSum = dataIds.length;
      ddfrom = new PlgForm({
        renderer: "waybillConsolidation_xi",
        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-md6", disabled: true },
              { type: "input", name: "casesBefore", label: "合并前件数:", className: "layui-col-md6", disabled: true },
              { type: "input", name: "volBefore", label: "合并前体积:", className: "layui-col-md6", disabled: true },
              { type: "input", name: "weightBefore", label: "合并前重量:", className: "layui-col-md6", disabled: true },
              { type: "input", name: "orderSum", label: "合并订单数:", className: "layui-col-md12", disabled: true },
              { type: "input", name: "cases", label: "合并后件数:", className: "layui-col-md6", validate: "ValidNumeric", maxLength: 12, required: true },
              { type: "input", name: "vol", label: "合并后体积:", className: "layui-col-md6", validate: "ValidNumeric", maxLength: 12, required: true },
              { type: "input", name: "weight", label: "合并后重量:", className: "layui-col-md6", validate: "ValidNumeric", maxLength: 12, required: true },
              { type: "input", name: "memo", label: "合并备注:", className: "layui-col-md6" }
            ]
          }]
      });
      ddfrom.setFormData(dataItem);
      changePanel();
    }
  });
  //返回
  document.querySelector("#waybillConsolidation_back1").onclick = function () {
    changePanel();
  };
  //确认
  document.querySelector("#waybillConsolidation_save").onclick = function () {
    //信息比对
    let url = UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/tmsOrderCombine/tmsOrderCombine";
    //数据修改
    var feik = ddfrom.validate();
    if (!feik) {
      return;
    }
    let dataIds = getDeleteAll(grid);
    for (var i = 0; i < dataIds.length; i++) {
      dataIds[i] = grid.getRowData(dataIds[i]);
    }
    let datai = ddfrom.getFormData();
    if (datai.cases > datai.casesBefore) {
      layer.msg("合并后件数不能大于合并前件数");
      return;
    }
    if (datai.vol > datai.volBefore) {
      layer.msg("合并后体积不能大于合并前体积");
      return;
    }
    if (datai.weight > datai.weightBefore) {
      layer.msg("合并后重量不能大于合并前重量");
      return;
    }
    datai.list = dataIds;
    //调用ajax方法
    utilAjaxGJ(url, "post", JSON.stringify(datai), function (data) {
      if (data.success) {
        grid.reload();
        changePanel();
      }
    }, "application/json");
  };
};