/**
 * zzx
 * 2020.09.24
 * 车辆违章登记
    */
    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, 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: "#vehicleViolateRegistration",
    autoplay: false,
    index: 0,
    arrow: "none",
    indicator: "none",
    anim: "fade",
    width: "100%", // 设置容器宽度
    height: "100%"
  });
  // 切换页面
  function changePanel(name) {
    var slideList = ["#vehicleViolateRegistration_main", "#vehicleViolateRegistration_deit"];
    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", "#vehicleViolateRegistration_deit_return", function () {
    changePanel("#vehicleViolateRegistration_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: "ILLEGAL_TYPE" },
    { objectcode: "AUDIT_STATUS" },
    { objectcode: "YES_OR_NO" }], function (data) {
      dataSelect = data.data;
      dataSelect.ILLEGAL_TYPE.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 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"
  };

  // 主页grid
  var master_grid_opts = {
    skin: "card",
    columns: [
      { id: "illegalNo", name: "id", type: "ro", width: "130", hidden: true },
      { id: "branchid", name: "机构id", type: "ro", width: 120 },
      { id: "branchname", name: "机构牌号", type: "ro", width: 120 },
      { id: "illegalNo", name: "违章单号", type: "ro", width: 120 },
      { id: "illegalTime", name: "违章发生时间", type: "ro", width: 120 },
      {
        id: "illegalType", name: "违章类别", type: "ro", width: 120, render: function (v) {
          return getSelectValue(dataSelect.ILLEGAL_TYPE, v);
        }
      },
      { id: "illegalAdd", name: "违章地点", type: "ro", width: 120 },
      { id: "illegalPerson", name: "违章人员", type: "ro", width: 120 },
      { id: "vehicleCode", name: "车辆编号", type: "ro", width: 120 },
      { id: "forfeit", name: "罚款", type: "ro", width: 120 },
      { id: "minusPoints", name: "扣分", type: "ro", width: 120 },
      { id: "discoverTime", name: "发现时间", type: "ro", width: 120 },
      { id: "discoverPerson", name: "发现人", type: "ro", width: 120 },
      { id: "disposeTime", name: "违章处理时间", type: "ro", width: 120 },
      {
        id: "punishPostpone", name: "是否延期处罚", type: "ro", width: 120, render: function (v) {
          return getSelectValue(dataSelect.YES_OR_NO, v);
        }
      },
      { id: "postponeDay", name: "延期处罚天数", type: "ro", width: 120 },
      { id: "undertaker", name: "承担对象", type: "ro", width: 120 },
      { id: "amountLossG", name: "货物损失金额", type: "ro", width: 120 },
      { id: "amountLossV", name: "车辆损失", type: "ro", width: 120 },
      { id: "compensate", name: "理赔收入", type: "ro", width: 120 },
      { id: "punishment", 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 "修改^vehicleViolateRegistration_mod,删除^vehicleViolateRegistration_del";
        }
      }
    ],
    toolbar: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          { type: "calendar", className: "layui-col-md3", name: "sdate", label: "开始时间:", value: startTime },
          { type: "calendar", className: "layui-col-md3", name: "edate", 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: "illegalNo", label: "违章单号:" },
          {
            type: "selectTable",
            className: "layui-col-md3",
            placeholder: "请选择车牌号",
            readonly: false,
            table: vehicleTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "vehicleNo",
            fieldValue: "vehicleNo",
            name: "vehicleCodeList",
            label: "车牌号:",
            listener: function (Grid) {
              setMethod(Grid, vehicleTable, function () { });
            }
          },
          { type: "input", className: "layui-col-md3", name: "illegalPerson", label: "违章人员:" },
          { type: "combo", className: "layui-col-md3", readonly: true, name: "illegalType", label: "违章类别:", options: dataSelect.ILLEGAL_TYPE },
          {
            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/queryTVmIllegalRecordRegister", // 数据接口
    type: "post", // 数据提交方式，默认为get
    params: JSON.stringify({ sdate: startTime, edate: endTime, flag: "inputQuery" }), // 查询提交参数，分页参数默认为pageNum,pageSize
    page: true, // 是否启用分页
    contentType: "application/json",
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  master_grid = new PlgGrid(master_grid_opts);
  master_grid.renderTo("vehicleViolateRegistration_master");
  master_grid.loadData();
  master_grid.attachToolBarEvent("onButtonClick", function (name) {
    switch (name) {
      case "master_search":
        var request = master_grid.getToolBarForm().getFormData();
        request.sdate = request.sdate ? Prolog.formatDate(request.sdate) + " 00:00:00" : "";
        request.edate = request.edate ? Prolog.formatDate(request.edate) + " 23:59:59" : "";
        if (request.sdate > request.edate) {
          layer.msg("开始时间不能大于结束时间");
          return false;
        }
        request.branchid = request.branchidList ? JSON.parse(request.branchidList)[0] : "";
        request.vehicleCode = request.vehicleCodeList ? JSON.parse(request.vehicleCodeList)[0] : "";
        request.flag = "inputQuery";
        dealNullQueryCondition(request);
        delete request.branchidList;
        delete request.vehicleCodeList;
        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("vehicleCodeList", "");
        master_grid.getToolBarForm().setFormData({ sdate: startTime, edate: endTime });
        break;
      case "master_add":
        changePanel("#vehicleViolateRegistration_deit");
        $("#vehicleViolateRegistration_deit_title").html("新增");
        editFormCreated();
        break;
    }
  });
  // 单个删除
  window.vehicleViolateRegistration_del = function (rid) {
    tVmIllegalRecordDelete([{ illegalNo: rid }]);
  };
  // 批量删除
  master_grid.attachPageBarEvent(function (name, ids) {
    let list = ids.split(",").map(item => {
      return { illegalNo: item };
    });
    tVmIllegalRecordDelete(list);
  });
  function tVmIllegalRecordDelete(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/tVmIllegalRecordDelete", type: "post", contentType: "application/json", data: JSON.stringify(idList),
          success: function (data) {
            PlgDialog.close(pload);
            if (data.success) {
              layer.closeAll();
              PlgDialog.msg(data.message);
              master_grid.reload();
              return true;
            }
            return false;

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

  // 修改
  window.vehicleViolateRegistration_mod = function (rid, rdata) {
    changePanel("#vehicleViolateRegistration_deit");
    $("#vehicleViolateRegistration_deit_title").html("修改");
    editFormCreated(rdata);
  };

  // 注册编辑页form
  function editFormCreated(rdata) {
    $("#vehicleViolateRegistration_deit_form").html("");
    var edit_form_opts = {
      renderer: "vehicleViolateRegistration_deit_form",
      items: [
        { type: "settings", labelAlign: "left", labelWidth: 95 },
        {
          type: "row",
          list: [
            { type: "input", className: "layui-col-md3", name: "illegalNo", 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: "calendar", className: "layui-col-md3", name: "illegalTime", label: "违章发生时间:", dateFormat: "%Y-%m-%d %H:%i:%s", enableTime: true, required: true },
            { type: "combo", className: "layui-col-md3", readonly: true, name: "illegalType", label: "违章类别:", options: dataSelect.ILLEGAL_TYPE, required: true }
          ]
        },
        {
          type: "row",
          list: [
            { type: "input", className: "layui-col-md6", name: "illegalAdd", label: "违章地点:", required: true },
            { type: "input", className: "layui-col-md3", name: "illegalPerson", label: "违章人:", required: true }
          ]
        },
        {
          type: "row",
          list: [
            {
              type: "selectTable",
              className: "layui-col-md3",
              placeholder: "请选择车牌号",
              readonly: false,
              table: vehicleTable,
              tableWidth: 600,
              tableHeight: 500,
              fieldText: "vehicleNo",
              fieldValue: "vehicleNo",
              name: "vehicleCodeList",
              label: "车牌号:<span class='dhxform_item_required'>*</span>",
              listener: {
                "afterSelect": function (isSelected, selectId, sgrid) {
                  let sdata = sgrid.getRowData(selectId);
                  edit_form.setFormData({
                    vehicleCode: isSelected ? sdata.vehicleNo : ""
                  });
                }
              }
            },
            { type: "hidden", name: "vehicleCode", label: "车牌号:" },
            { type: "input", className: "layui-col-md3", name: "forfeit", label: "罚款:", validate: "Money_11bit" },
            { type: "input", className: "layui-col-md3", name: "minusPoints", label: "扣分:", validate: "Money_11bit" },
            { type: "calendar", className: "layui-col-md3", name: "discoverTime", label: "发现时间:", dateFormat: "%Y-%m-%d %H:%i:%s", enableTime: true, required: true }
          ]
        },
        {
          type: "row",
          list: [
            { type: "input", className: "layui-col-md3", name: "discoverPerson", label: "发现人:" },
            { type: "calendar", className: "layui-col-md3", name: "disposeTime", label: "违章处理时间:", dateFormat: "%Y-%m-%d %H:%i:%s", enableTime: true, required: true },
            { type: "combo", className: "layui-col-md3", readonly: true, name: "punishPostpone", label: "是否延期处罚:", options: dataSelect.YES_OR_NO },
            { type: "input", className: "layui-col-md3", name: "postponeDay", label: "延期处罚天数:", validate: "Money_11bit" }
          ]
        },
        {
          type: "row",
          list: [
            { type: "input", className: "layui-col-md3", name: "undertaker", label: "承担对象:" },
            { type: "input", className: "layui-col-md3", name: "amountLossG", label: "货物损失金额:", validate: "Money_11bit" },
            { type: "input", className: "layui-col-md3", name: "amountLossV", label: "车辆损失:", validate: "Money_11bit" },
            { type: "input", className: "layui-col-md3", name: "compensate", label: "理赔收入:", validate: "Money_11bit" }
          ]
        },
        {
          type: "row",
          list: [
            { type: "input", className: "layui-col-md3", name: "punishment", label: "公司处罚:", validate: "Money_11bit" }
          ]
        },
        {
          type: "row",
          list: [
            { type: "input", className: "layui-col-md6", name: "memo", label: "备注:", rows: 3 }
          ]
        }
      ]
    };
    edit_form = new PlgForm(edit_form_opts);

    // 发生时间、发现时间、处理时间时间顺序逻辑
    // var data = {
    //   illegalTime: null,
    //   discoverTime: null,
    //   disposeTime: null
    // };
    // var nowDate = FormatDateTime(new Date());
    // var event = {
    //   illegalTime: function (value) {
    //     edit_form.getCalendar("discoverTime").setSensitiveRange(value, dateCompare(data.disposeTime, nowDate));
    //     edit_form.getCalendar("disposeTime").setSensitiveRange(value, null);
    //   },
    //   discoverTime: function (value) {
    //     edit_form.getCalendar("illegalTime").setSensitiveRange(null, dateCompare(value, nowDate));
    //     edit_form.getCalendar("disposeTime").setSensitiveRange(value, null);
    //   },
    //   disposeTime: function (value) {
    //     edit_form.getCalendar("illegalTime").setSensitiveRange(null, dateCompare(value, nowDate));
    //     edit_form.getCalendar("discoverTime").setSensitiveRange(data.illegalTime, dateCompare(value, nowDate));
    //   }
    // };
    // edit_form.attachEvent("onInputChange", function (name, value) {
    //   if (["illegalTime", "discoverTime", "disposeTime"].includes(name)) {
    //     data[name] = value;
    //     event[name](value);
    //   }
    // });

    // edit_form.getCalendar("illegalTime").setSensitiveRange(null, nowDate);
    // edit_form.getCalendar("discoverTime").setSensitiveRange(null, nowDate);

    // 赋值
    if (rdata) {
      rdata.branchidList = JSON.stringify([rdata.branchid]);
      rdata.vehicleCodeList = JSON.stringify([rdata.vehicleCode]);
      rdata.gsCodeList = JSON.stringify([rdata.gsCode]);
      edit_form.setFormData(rdata);
      edit_form.disableItem("illegalNo");
      edit_form.setText("branchidList", rdata.branchname);
      edit_form.setText("vehicleCodeList", rdata.vehicleCode);
      edit_form.setText("gsCodeList", rdata.gsCode);
    }
    else {
      edit_form.enableItem("illegalNo");
    }
  }

  // function dateCompare(date1, date2) {
  //   if (!date1) {
  //     return date2;
  //   }
  //   else if (date1 > date2) {
  //     return date2;
  //   }
  //   return date1;
  // }

  // 保存
  $("#vehicleViolateRegistration_deit_save").on("click", function () {
    let vdate = edit_form.validate();
    if (!vdate) return false;
    let formData = edit_form.getFormData();
    let nowDate = new Date().getTime();

    if (!formData.branchname) {
      layer.msg("请选择配送中心");
      return false;
    }
    if (!formData.vehicleCode) {
      layer.msg("请选择车牌号");
      return false;
    }
    if (formData.illegalTime.getTime() > nowDate) {
      layer.msg("违章发生时间不可晚于系统当前时间");
      return false;
    }
    if (formData.illegalTime.getTime() > formData.discoverTime.getTime()) {
      layer.msg("违章发生时间不可晚于发现时间");
      return false;
    }
    if (formData.illegalTime.getTime() > formData.disposeTime.getTime()) {
      layer.msg("违章发生时间不可晚于违章处理时间");
      return false;
    }
    if (formData.discoverTime.getTime() > nowDate) {
      layer.msg("发现时间不可晚于系统当前时间");
      return false;
    }
    if (formData.discoverTime.getTime() > formData.disposeTime.getTime()) {
      layer.msg("发现时间不可晚于违章处理时间");
      return false;
    }

    formData.illegalTime = formData.illegalTime ? Prolog.formatDate(formData.illegalTime, "%YY-%MM-%DD %hh:%mm:%ss") : "";
    formData.discoverTime = formData.discoverTime ? Prolog.formatDate(formData.discoverTime, "%YY-%MM-%DD %hh:%mm:%ss") : "";
    formData.disposeTime = formData.disposeTime ? Prolog.formatDate(formData.disposeTime, "%YY-%MM-%DD %hh:%mm:%ss") : "";
    delete formData.branchidList;
    delete formData.vehicleCodeList;

    let url = $("#vehicleViolateRegistration_deit_title").html() === "新增" ? UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/vehicleManage/tVmIllegalRecordSave" : UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/vehicleManage/tVmIllegalRecordUpdate";
    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("#vehicleViolateRegistration_main");
          master_grid.reload();
          return true;
        }
                return false;
      }, error: function () { PlgDialog.close(pload); return false; }
    });
  });
};