/**
 * zzx
 * 2020.07.10
 * 作业节点查询
 */
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, details_grid;

  // 跳转页面
  var carousel = layui.carousel;
  carousel.render({
    elem: "#jobNodeQuery",
    autoplay: false,
    index: 0,
    arrow: "none",
    indicator: "none",
    anim: "fade",
    width: "100%", // 设置容器宽度
    height: "100%"
  });
  // 切换页面
  function changePanel(name) {
    var slideList = ["#jobNodeQuery_main", "#jobNodeQuery_view"];
    for (var i = 0; i < slideList.length; i++) {
      if (slideList[i] == name) {
        $(name).css("display", "block");
      }
      else {
        $(slideList[i]).css("display", "none");
      }
    }
  }
  // 返回
  $(document).on("click", "#jobNodeQuery_view_return", function () {
    changePanel("#jobNodeQuery_main");
  });
  // 获取默认时间
  var startTime = Prolog.formatDate(new Date(), "%YY-%MM") + "-01 00:00:00";
  var endTime = Prolog.formatDate(new Date()) + " 23:59:59";
  // 获取下拉框
  var dataSelect;
  getSelectGJ([
    { "objectcode": "TIME_SECTION" }
  ], function (data) {
    dataSelect = data.data;
    dataSelect.TIME_SECTION.unshift({ "value": "", "text": "" });
  });

  // 配送中心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 customerTable = {
    // 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: 110 },
      {
        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/queryPubCompanyPopup",
    pagebar: { type: "simple" },
    type: "post", // 数据提交方式，默认为get
    params: JSON.stringify({ companytype: "4" }), // 查询提交参数，分页参数默认为pageNum,pageSize
    contentType: "application/json",
    page: true, // 是否启用分页
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };

  // 主页grid
  var master_grid_opts = {
    skin: "card",
    columns: [
      { id: "appointBillNo", name: "id", type: "ro", width: "130", hidden: true },
      { id: "branchid", name: "配送中心编号", type: "ro", width: 120 },
      { id: "branchname", name: "配送中心名称", type: "ro", width: 120 },
      { id: "appointBillNo", name: "预约单号", type: "ro", width: 120 },
      { id: "billdate", name: "单据时间", type: "ro", width: 120 },
      { id: "appointType", name: "预约类型", type: "ro", width: 120, render: function (v, rd) { return rd.appointTypeName ? rd.appointTypeName : v; } },
      { id: "customerId", name: "预约单位id", type: "ro", width: 120 },
      { id: "customerCode", name: "预约单位编号", type: "ro", width: 120 },
      { id: "customerName", name: "预约单位名称", type: "ro", width: 120 },
      { id: "appointVehicle", name: "预约车辆", type: "ro", width: 120 },
      { id: "appointDriver", name: "预约司机", type: "ro", width: 120 },
      { id: "billtype", name: "单据类型", type: "ro", width: 120, render: function (v, rd) { return rd.billtypeName ? rd.billtypeName : v; } },
      { id: "shipbillno", name: "运单号", type: "ro", width: 120 },
      { id: "rsumcases", 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: "appointDate", name: "预约日期", type: "ro", width: 120 },
      { id: "appointTime", name: "预约时间", type: "ro", width: 120 },
      { id: "appointPackage", name: "预约件数", type: "ro", width: 120 },
      { id: "status", name: "单据状态", type: "ro", width: 120, render: function (v, rd) { return rd.statusName ? rd.statusName : v; } },
      { id: "memo", name: "备注", type: "ro", width: 120 },
      {
        id: "op", name: "操作", type: "button", align: "left", width: 80, fixed: "right", render: function () {
          return "操作记录^jobNodeQuery_record";
        }
      }
    ],
    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: "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: "input", className: "layui-col-md3", name: "shipbillno", label: "运单号:" },
          { type: "input", className: "layui-col-md3", name: "refbillno", label: "业务单号:" },
          {
            type: "selectTable",
            className: "layui-col-md3",
            placeholder: "请选择客户",
            readonly: false,
            table: customerTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "companyname",
            fieldValue: "companyid",
            name: "customerIdList",
            label: "客户:",
            listener: function (Grid) {
              setMethod(Grid, customerTable, function () { });
            }
          },
          {
            type: "block", className: "layui-col-md3 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_export", value: "导 出" }
            ]
          }
        ]
      }
    ],
    fixedLast: true, // 开启固定列，固定最后一行，倒数第二列不能隐藏
    multiselect: false, // 是否支持多选
    url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/jobNodeQuery/query/v1.0", // 数据接口
    type: "post", // 数据提交方式，默认为get
    params: JSON.stringify({ startdate: startTime, enddate: endTime }),
    page: true, // 是否启用分页
    contentType: "application/json",
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  master_grid = new PlgGrid(master_grid_opts);
  master_grid.renderTo("jobNodeQuery_master");
  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] : "";
        dealNullQueryCondition(request);
        master_grid.setParams(JSON.stringify(request));
        master_grid.reload();
        break;
      case "master_reset":
        master_grid.getToolBarForm().clear();
        master_grid.getToolBarForm().setFormData({ startdate: startTime, enddate: endTime });
        master_grid.getToolBarForm().setText("branchidList", "");
        master_grid.getToolBarForm().setText("carrierIdList", "");
        break;
      case "master_export":
        unfilledWorktime_export();
        break;
    }
  });
  //主界面导出事件
  function unfilledWorktime_export() {
    let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    if (master_grid.getRowsNum() <= 0) {
      PlgDialog.close(pload);
      PlgDialog.msg("没有要导出的数据");
      return;
    }
    let url = UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/jobNodeQuery/tmsAppointBillExport";
    let name = "作业节点查询" + Prolog.formatDate(new Date(), "%YY%MM%DD") + ".xls";
    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) {
      PlgDialog.close(pload);
      layer.msg("开始时间不能大于结束时间");
      return false;
    }
    request.branchid = request.branchidList ? JSON.parse(request.branchidList)[0] : "";
    request.carrierId = request.carrierIdList ? JSON.parse(request.carrierIdList)[0] : "";
    Prolog.exportFile(url, name, "application/json", "post", request);
    PlgDialog.close(pload);
  }
  // 单击一行显示明细
  master_grid.on("onRowSelect", function (id) {
    let rdata = master_grid.getRowData(id);
    details_grid.setParams(JSON.stringify({ shipbillid: rdata.shipbillno, branchid: rdata.branchid }));
    details_grid.reload();
  });
  // 操作记录
  window.jobNodeQuery_record = function (rid, rdata) {
    $("#jobNodeQuery_view_steps").html("");
    sysOpEventQuery(rdata);
    changePanel("#jobNodeQuery_view");
  };

  // 获取操作记录
  function sysOpEventQuery(rdata) {
    let request = {
      shipbillid: rdata.shipbillid,
      shipbillno: rdata.shipbillno
    };
    let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/sysOpEvent/query/v1.0", type: "post", contentType: "application/json", data: JSON.stringify(request),
      success: function (res) {
        PlgDialog.close(pload);
        if (res.success) {
          PlgDialog.msg(res.message);
          renderRecord(res.data);
          return true;
        }
                return false;

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

  // 渲染操作记录页面
  function renderRecord(list) {
    // list = [
    //   {
    //     eventtime: "2020.04.22 11:47 星期三",
    //     eventremark: "订单已由本人签收，感谢您在京东购物，欢迎您再次光临！ 操作员：张三订单已由本人签收，感谢您在京东购物，欢迎您再次光临！ 操作员：张三订单已由本人签收，感谢您在京东购物，欢迎您再次光临",
    //     operatorname: "张三"
    //   }
    // ];
    let html = "";
    let length = list.length;
    list.forEach((item, index) => {
      let calssname = index === 0 ? "first_step" : "";
      let seq = index === 0 ? "√" : index === length - 1 ? "·" : "↑";
      html += "   <div class='el-step " + calssname + "'>";
      html += "      <div class='el-step__time'>";
      html += "          <div class='el-step__description'>" + item.eventtime + "</div>";
      html += "      </div>";
      html += "      <div class='el-step__head'>";
      html += "          <div class='el-step__line'></div>";
      html += "          <div class='el-step__icon'>";
      html += "              <div class='el-step__icon-inner'>" + seq + "</div>";
      html += "          </div>";
      html += "      </div>";
      html += "      <div class='el-step__main'>";
      html += "          <div class='el-step__description'>";
      html += "              " + item.eventremark + " 操作员：" + item.operatorname + "";
      html += "          </div>";
      html += "      </div>";
      html += "   </div>";
    });
    $("#jobNodeQuery_view_steps").html(html);

  }

  // 详情表grid
  var details_grid_opts = {
    skin: "card",
    columns: [
      { id: "lineid", name: "运单id", type: "ro", width: "130", hidden: true },
      { id: "shipbillno", name: "运单号", type: "ro" },
      { id: "itemno", name: "产品编号", type: "ro" },
      { id: "itemname", name: "产品名称", type: "ro" },
      { id: "itemtype", name: "物料类型", type: "ro", render: function (v, rd) { return rd.itemtypeName ? rd.itemtypeName : v; } },
      { id: "pcs", name: "件数", type: "ro" },
      { id: "weight", name: "重量", type: "ro" },
      { id: "vol", name: "体积", type: "ro" },
      { id: "remark", name: "备注", type: "ro" }
    ],
    fixedLast: false, // 开启固定列，固定最后一行，倒数第二列不能隐藏
    multiselect: false, // 是否支持多选
    url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/tmsShipbill/detailsQuery/v1.0", // 数据接口
    type: "post", // 数据提交方式，默认为get
    params: "{}",
    page: false, // 是否启用分页
    contentType: "application/json",
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  details_grid = new PlgGrid(details_grid_opts);
  details_grid.renderTo("jobNodeQuery_details");
};