/**
 * zzx
 * 2020.10.20
 * 启运登记
 */
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 master_grid;
  // 获取默认时间
  var startTime = Prolog.formatDate(new Date(), "%YY-%MM") + "-01 00:00:00";
  var endTime = Prolog.formatDate(new Date()) + " 23:59:59";

  // 配送中心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
  };
  // 承运商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
  };

  // 主页grid
  var master_grid_opts = {
    skin: "card",
    columns: [
      { id: "loadbillid", name: "装车单id", type: "ro", width: "130", 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: 120 },
      { 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 },
      { 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: "coldBillNumber", name: "冷链运单数", type: "ro", width: 120 },
      { id: "memo", name: "备注", type: "ro", width: 120 }
      // {
      //   id: "status", name: "状态", type: "ro", width: 120, render: function (v) {
      //     return getSelectValue(dataSelect.AUDIT_STATUS, v);
      //   }
      // },
      // {
      //   id: "op", name: "操作", type: "button", align: "left", fixed: "right", width: "100", render: function () {
      //     return "启运登记^shipmentsRegistration_registration";
      //   }
      // }
    ],
    toolbar: [
      { type: "settings", labelWidth: 70, labelAlign: "right" },
      {
        type: "row",
        list: [
          { type: "calendar", className: "layui-col-md3", name: "startdate", label: "开始时间:", value: startTime },
          { type: "calendar", className: "layui-col-md3", name: "enddate", label: "结束时间:", value: endTime },
          { type: "input", className: "layui-col-md3", name: "loadbillno", label: "装车单号:" },
          {
            type: "selectTable",
            className: "layui-col-md3",
            placeholder: "请选择配送中心",
            readonly: false,
            table: branchTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "companyname",
            fieldValue: "companyid",
            name: "branchidList",
            label: "配送中心:",
            listener: function (Grid) {
              setMethod(Grid, branchTable, function () { });
            }
          },
          {
            type: "selectTable",
            className: "layui-col-md3",
            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-md6 form_btn_left",
            list: [
              { type: "button", className: "btn-normal", name: "master_search", value: "查 询" },
              { type: "newcolumn" },
              { type: "button", name: "master_reset", value: "重 置" }
            ]
          },
          {
            type: "block", className: "layui-col-md3 right",
            list: [
              { type: "button", className: "btn-normal", name: "master_registration", value: "启运登记" }
            ]
          }
        ]
      }
    ],
    fixedLast: false, // 开启固定列，固定最后一行，倒数第二列不能隐藏
    multiselect: true, // 是否支持多选
    url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/departureRegistration/summaryQuery/v1.0", // 数据接口
    type: "post", // 数据提交方式，默认为get
    params: JSON.stringify({ startdate: startTime, enddate: endTime, status: "30" }), // 查询提交参数，分页参数默认为pageNum,pageSize
    page: true, // 是否启用分页
    contentType: "application/json",
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  master_grid = new PlgGrid(master_grid_opts);
  master_grid.renderTo("shipmentsRegistration");
  master_grid.loadData();
  master_grid.attachToolBarEvent("onButtonClick", function (name) {
    switch (name) {
      case "master_search":
        var request = master_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.branchid = request.branchidList ? JSON.parse(request.branchidList)[0] : "";
        request.carrierid = request.carrieridList ? JSON.parse(request.carrieridList)[0] : "";
        request.status = "30";
        dealNullQueryCondition(request);
        delete request.branchidList;
        delete request.carrieridList;
        master_grid.setParams(JSON.stringify(request));
        master_grid.reload();
        break;
      case "master_reset":
        master_grid.getToolBarForm().clear();
        master_grid.getToolBarForm().setText("branchidList", "");
        master_grid.getToolBarForm().setText("carrieridList", "");
        master_grid.getToolBarForm().setFormData({ startdate: startTime, enddate: endTime });
        break;
      case "master_registration":
        var ids = master_grid.getCheckedIds();
        if (!ids) {
          layer.msg("请选择数据");
          return false;
        }
        registrationDialog(ids);
        break;
    }
  });

  // 启运登记弹窗
  function registrationDialog(ids) {
    let coldBillNumberTotal = ids.split(",").map(item => master_grid.getRowData(item).coldBillNumber).reduce((a, b) => a + b);
    let dialogForm;
    PlgDialog.open({
      title: "启运登记",
      shadeClose: true,
      type: 1, // 设置为1，手动控制dialog的开关
      area: ["400px", "250px"],
      btn: ["启运登记", "取消"],
      content: "<div id =\"shipmentsRegistration_dialog\"></div>", //iframe的url
      yes: function (index) {
        var feik = dialogForm.validate();
        if (!feik) {
          return;
        }
        let { shipmilefrom, shiptemperature } = dialogForm.getFormData();
        if (shipmilefrom < 0) {
          layer.msg("启运里程不能为负数");
          return false;
        }
        register(ids, { shipmilefrom, shiptemperature }, index);
      },
      btn2: function (index) {
        PlgDialog.close(index); // 如果设定了yes回调，需进行手工关闭
      },
      success: function () {
        // 当你需要在层创建完毕时即执行一些语句，可以通过该回调。success会携带两个参数，分别是当前层DOM当前层索引。如：
      }
    });
    let dialogForm_opts = {
      renderer: "shipmentsRegistration_dialog",
      items: [
        { type: "settings", labelAlign: "left", labelWidth: 90 },
        {
          type: "row",
          list: [
            { type: "input", className: "layui-col-md12", name: "shipmilefrom", label: "启运里程:", required: true, validate: "ValidNumeric" }
          ]
        },
        {
          type: "row",
          list: [
            { type: "input", className: "layui-col-md12", name: "shiptemperature", label: "启运温度:", validate: "ValidNumeric", required: coldBillNumberTotal > 0, hidden: coldBillNumberTotal === 0 }
          ]
        }
      ]
    };
    dialogForm = new PlgForm(dialogForm_opts);
  }

  function register(ids, { shipmilefrom, shiptemperature }, index) {
    const list = ids.split(",").map(item => {
      let element = master_grid.getRowData(item);
      return {
        loadbillid: element.loadbillid,
        loadbillno: element.loadbillno,
        shipmilefrom: shipmilefrom,
        coldBillNumber: element.coldBillNumber,
        shiptemperature: shiptemperature
      };
    });
    let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/departureRegistration/register/v1.0", type: "post", contentType: "application/json", data: JSON.stringify(list),
      success: function (res) {
        PlgDialog.close(pload);
        if (res.success) {
          PlgDialog.close(index);
          PlgDialog.msg(res.message);
          master_grid.reload();
          return true;
        }
                return false;

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