/**
 * zzx
 * 2020.09.16
 * 车辆加油登记
    */
    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 nowTime = Prolog.formatDate(new Date()) + " 00:00";
  var master_grid, edit_form_opts, edit_form;
var userinfo = {
  p_id: '',
  p_username: '',
  p_workernumber: '',
  p_nickname: '',
  p_phone: null,
  p_email: null,
  p_companyid: '',
  p_enterpriseid: '',
  p_organizationid: '',
  p_companyname: '',
  p_orgname: '',
  p_enterprisename: '',
  p_usertype: '',
  p_lastlogindate: '',
  p_lastmodipassdate: null,
  p_validdate: '',
  p_import_batchno: null,
  p_data_source: null,
  forceModifyPasswdFlag: false,
  vehicle: null,
}

  // 跳转页面
  var carousel = layui.carousel;
  carousel.render({
    elem: "#vehicleFuelingRegistration",
    autoplay: false,
    index: 0,
    arrow: "none",
    indicator: "none",
    anim: "fade",
    width: "100%", // 设置容器宽度
    height: "100%"
  });
  // 切换页面
  function changePanel(name) {
    var slideList = ["#vehicleFuelingRegistration_main", "#vehicleFuelingRegistration_deit"];
    for (var i = 0; i < slideList.length; i++) {
      if (slideList[i] == name) {
        $(name).css("display", "block");
      }
      else {
        $(slideList[i]).css("display", "none");
      }
    }
  }
  // 返回
  $("#vehicleFuelingRegistration_deit_return").on("click", function () {
    changePanel("#vehicleFuelingRegistration_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: "AUDIT_STATUS" }], function (data) {
      dataSelect = data.data;
    }
  );

  // 配送中心table
  var branchTable = {
    skin: "card",
    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 vehicleTable = {
    skin: "card",
    columns: [
      { id: "vehicleId", name: "id", type: "ro", width: "130", hidden: true },
      { id: "vehicleNo", name: "车牌号", type: "ro" },
      { id: "vehicleName", name: "车辆名称", type: "ro" }
    ],
    multiselect: false,
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/tBaseVehicle/queryVehicleInfo",
    type: "post",
    pagebar: { type: "simple" },
    contentType: "application/json",
    params: JSON.stringify({ companyId: userinfo.p_companyid }),
    page: true,
    totalCount: "totalCount"
  };
  // 加油站table
  var gsTable = {
    skin: "card",
    columns: [
      { id: "gsCode", name: "id", type: "ro", width: "130", hidden: true },
      { id: "gsCode", name: "加油站编号", type: "ro" },
      { id: "gsName", 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: "gsCode", label: "加油站编号:", width: 120 },
          { type: "newcolumn" },
          { type: "button", name: "querycarr", value: "查询" },
          { type: "newcolumn" },
          { type: "button", name: "car_Reset", value: "重置" }
        ]
      }
    ],
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/partnerGasStation/pop",
    pagebar: { type: "simple" },
    type: "post", // 数据提交方式，默认为get
    params: "{}", // 查询提交参数，分页参数默认为pageNum,pageSize
    contentType: "application/json",
    page: true, // 是否启用分页
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };

  // 主页grid
  var master_grid_opts = {
    skin: "card",
    columns: [
      { id: "billno", name: "id", type: "ro", width: "130", hidden: true },
      { id: "branchid", name: "机构id", type: "ro", width: 120 },
      { id: "branchname", name: "机构牌号", type: "ro", width: 120 },
      { id: "billno", name: "加油单号", type: "ro", width: 120 },
      { id: "platenumber", name: "车牌号", type: "ro", width: 120 },
      { id: "gsCode", name: "加油站编号", type: "ro", width: 120 },
      { id: "gsName", name: "加油站", type: "ro", width: 120 },
      { id: "oiltype", name: "油型", type: "ro", width: 120 },
      { id: "oilPrice", name: "油价", type: "ro", width: 120 },
      { id: "oilDate", name: "加油时间", type: "ro", width: 120 },
      { id: "oilPerson", name: "加油人", type: "ro", width: 120 },
      { id: "oilQuantity", name: "加油量", type: "ro", width: 120 },
      { id: "odometer", name: "里程数", type: "ro", width: 120 },
      { id: "amount", name: "金额", type: "ro", width: 120 },
      { id: "audittime", name: "审核时间", type: "ro", width: 120 },
      { id: "auditperson", name: "审核人", type: "ro", width: 120 },
      {
        id: "status", name: "状态", type: "ro", width: 120, render: function (v) {
          return getSelectValue(dataSelect.AUDIT_STATUS, v);
        }
      },
      { id: "memo", name: "备注", type: "ro", width: 120 },
      {
        id: "op", name: "操作", type: "button", align: "left", fixed: "right", width: "100", render: function () {
          return "修改^vehicleFuelingRegistration_mod,删除^vehicleFuelingRegistration_del";
        }
      }
    ],
    toolbar: [
      { type: "settings", labelWidth: 90, 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: "billno", label: "加油单号:" },
          {
            type: "selectTable",
            className: "layui-col-md3",
            placeholder: "请选择车牌号",
            readonly: false,
            table: vehicleTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "vehicleNo",
            fieldValue: "vehicleNo",
            name: "platenumberList",
            label: "车牌号:",
            listener: function (Grid) {
              setMethod(Grid, vehicleTable, function () { });
            }
          },
          { type: "input", className: "layui-col-md3", name: "oilPerson", label: "加油人:" },
          {
            type: "selectTable",
            className: "layui-col-md3",
            placeholder: "请选择加油站",
            readonly: false,
            table: gsTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "gsName",
            fieldValue: "gsCode",
            name: "gsCodeList",
            label: "加油站:",
            listener: function (Grid) {
              setMethod(Grid, gsTable, function () { });
            }
          },
          //{ type: "input", className: "layui-col-md3", name: "gsCode", label: "加油站编号:" },
          {
            type: "block", className: "layui-col-md2 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-md1 right",
            list: [
              { type: "button", className: "btn-normal", name: "master_add", value: "<i class='layui-icon layui-icon-add-1'></i>新 增" }
            ]
          }
        ]
      }
    ],
    pagebar: {
      buttons: [
        { text: "<i class='layui-icon layui-icon-delete'></i>删除", className: "plg-btn-normal", name: "pagebar_delete" }
      ]
    },
    fixedLast: true, // 开启固定列，固定最后一行，倒数第二列不能隐藏
    multiselect: true, // 是否支持多选

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/vehicleManage/queryTVmFuelRecordRegister", // 数据接口
    type: "post", // 数据提交方式，默认为get
    params: JSON.stringify({ startdate: startTime, enddate: endTime, statuses: ["5", "10"] }), // 查询提交参数，分页参数默认为pageNum,pageSize
    page: true, // 是否启用分页
    contentType: "application/json",
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  master_grid = new PlgGrid(master_grid_opts);
  master_grid.renderTo("vehicleFuelingRegistration_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.platenumber = request.platenumberList ? JSON.parse(request.platenumberList)[0] : "";
        request.gsCode = request.gsCodeList ? JSON.parse(request.gsCodeList)[0] : "";
        request.statuses = ["5", "10"];
        dealNullQueryCondition(request);
        delete request.branchidList;
        delete request.platenumberList;
        delete request.gsCodeList;
        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("platenumberList", "");
        master_grid.getToolBarForm().setText("gsCodeList", "");
        master_grid.getToolBarForm().setFormData({ startdate: startTime, enddate: endTime });
        break;
      case "master_add":
        $("#vehicleFuelingRegistration_deit_form").html("");
        edit_form = new PlgForm(edit_form_opts);
        edit_form.enableItem("billno");
        $("#vehicleFuelingRegistration_deit_title").html("新增");
        changePanel("#vehicleFuelingRegistration_deit");
        break;
    }
  });
  // 单个删除
  window.vehicleFuelingRegistration_del = function (rid) {
    tVmFuelRecordDelete([{ billno: rid }]);
  };
  // 批量删除
  master_grid.attachPageBarEvent(function (name, ids) {
    let list = ids.split(",").map(item => {
      return { billno: item };
    });
    tVmFuelRecordDelete(list);
  });
  function tVmFuelRecordDelete(idList) {
    layer.open({
      title: "删除",
      content: "是否删除？",
      btn: ["确认", "取消"],
      yes: function () {
        let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
        Prolog.ajax({
          url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/vehicleManage/tVmFuelRecordDelete", type: "post", contentType: "application/json", data: JSON.stringify(idList),
          success: function (res) {
            PlgDialog.close(pload);
            if (res.success) {
              layer.closeAll();
              PlgDialog.msg(res.message);
              master_grid.reload();
              return true;
            }
                        return false;

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

  // 修改
  window.vehicleFuelingRegistration_mod = function (rid, rdata) {
    $("#vehicleFuelingRegistration_deit_form").html("");
    edit_form = new PlgForm(edit_form_opts);
    rdata.branchidList = JSON.stringify([rdata.branchid]);
    rdata.platenumberList = JSON.stringify([rdata.platenumber]);
    rdata.gsCodeList = JSON.stringify([rdata.gsCode]);
    edit_form.setFormData(rdata);
    edit_form.disableItem("billno");
    edit_form.setText("branchidList", rdata.branchname);
    edit_form.setText("platenumberList", rdata.platenumber);
    edit_form.setText("gsCodeList", rdata.gsName);
    $("#vehicleFuelingRegistration_deit_title").html("修改");
    changePanel("#vehicleFuelingRegistration_deit");
  };

  // 编辑页form
  edit_form_opts = {
    renderer: "vehicleFuelingRegistration_deit_form",
    items: [
      { type: "settings", labelAlign: "left", labelWidth: 90 },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md3", name: "billno", label: "加油单号:", required: true },
          {
            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);
                edit_form.setFormData({
                  branchid: isSelected ? sdata.companyid : "",
                  branchname: isSelected ? sdata.companyname : ""
                });
              }
            }
          },
          { type: "hidden", name: "branchid", label: "配送中心id:" },
          { type: "hidden", name: "branchname", label: "配送中心名称:" },
          {
            type: "selectTable",
            className: "layui-col-md3",
            placeholder: "请选择车牌号",
            readonly: false,
            table: vehicleTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "vehicleNo",
            fieldValue: "vehicleNo",
            name: "platenumberList",
            label: "车牌号:<span class='dhxform_item_required'>*</span>",
            listener: {
              "afterSelect": function (isSelected, selectId, sgrid) {
                let sdata = sgrid.getRowData(selectId);
                edit_form.setFormData({
                  platenumber: isSelected ? sdata.vehicleNo : ""
                });
              }
            }
          },
          { type: "hidden", name: "platenumber", label: "车牌号:" },
          {
            type: "selectTable",
            className: "layui-col-md3",
            placeholder: "请选择加油站",
            readonly: false,
            table: gsTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "gsName",
            fieldValue: "gsCode",
            name: "gsCodeList",
            label: "加油站:<span class='dhxform_item_required'>*</span>",
            listener: {
              "init": function (Grid) {
                // 注册按钮事件
                Grid.attachToolBarEvent("onButtonClick", function (name) {
                  switch (name) {
                    case "querycarr":
                      var { gsCode } = Grid.getToolBarForm().getFormData();
                      Grid.setParams(JSON.stringify({ gsCode }));
                      Grid.reload();
                      break;
                    case "car_Reset":
                      Grid.getToolBarForm().clear();
                      break;
                  }
                });
              },
              "afterSelect": function (isSelected, selectId, sgrid) {
                let sdata = sgrid.getRowData(selectId);
                edit_form.setFormData({
                  gsCode: isSelected ? sdata.gsCode : "",
                  gsName: isSelected ? sdata.gsName : ""
                });
              }
            }
          },
          { type: "hidden", name: "gsCode", label: "加油站编号:" },
          { type: "hidden", name: "gsName", label: "加油站名称:" }
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md3", name: "oiltype", label: "油型:", required: true, validate: "Money_11bit" },
          { type: "input", className: "layui-col-md3", name: "oilPrice", label: "油价:", required: true, validate: "Money_11bit" },
          {
            type: "calendar",
            className: "layui-col-md3",
            name: "oilDate",
            label: "加油时间:",
            required: true,
            enableTime: true,
            dateFormat: "%Y-%m-%d %H:%i",
            minutesInterval: 1,
            value: nowTime
        },
          { type: "input", className: "layui-col-md3", name: "oilPerson", label: "加油人:", required: true }
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md3", name: "oilQuantity", label: "加油量:", required: true, validate: "Money_11bit" },
          { type: "input", className: "layui-col-md3", name: "odometer", label: "里程数:", required: true, validate: "Money_11bit" },
          { type: "input", className: "layui-col-md3", name: "amount", label: "金额:", required: true, validate: "Money_11bit" }
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md6", name: "memo", label: "备注:", rows: 3 }
        ]
      }
    ]
  };

  // 保存
  $("#vehicleFuelingRegistration_deit_save").on("click", function () {
    let vdate = edit_form.validate();
    if (!vdate) {
      layer.msg("数字格式录入失败,请输入纯数字格式");
      return false;
    }

    let formData = edit_form.getFormData();

    // formData.branchid = "001";
    // formData.branchname = "配送中心01";
    // formData.platenumber = "鄂AZ0X81";
    // formData.gsCode = "001";
    // formData.gsName = "加油站01";

    if (!formData.branchname) {
      layer.msg("请选择配送中心");
      return false;
    }
    if (!formData.platenumber) {
      layer.msg("请选择车牌号");
      return false;
    }
    if (!formData.gsCode) {
      layer.msg("请选择加油站");
      return false;
    }
    formData.oilDate = formData.oilDate ? Prolog.formatDate(formData.oilDate, "%YY-%MM-%DD %hh:%mm:%ss") : "";
    delete formData.branchidList;
    delete formData.platenumberList;
    delete formData.gsCodeList;
    // console.log(formData, 111);
    // return;
    let url = $("#vehicleFuelingRegistration_deit_title").html() === "新增" ? UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/vehicleManage/tVmFuelRecordSave" : UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/vehicleManage/tVmFuelRecordUpdate";
    let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url, type: "post", contentType: "application/json", data: JSON.stringify(formData),
      success: function (res) {
        PlgDialog.close(pload);
        if (res.success) {
          PlgDialog.msg(res.message);
          changePanel("#vehicleFuelingRegistration_main");
          master_grid.reload();
          return true;
        }
                return false;
      }, error: function () { PlgDialog.close(pload); return false; }
    });
  });
};