/**
 * 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 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: "#vehicleInsuranceRegistration",
    autoplay: false,
    index: 0,
    arrow: "none",
    indicator: "none",
    anim: "fade",
    width: "100%", // 设置容器宽度
    height: "100%"
  });
  // 切换页面
  function changePanel(name) {
    var slideList = ["#vehicleInsuranceRegistration_main", "#vehicleInsuranceRegistration_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", "#vehicleInsuranceRegistration_deit_return", function () {
    changePanel("#vehicleInsuranceRegistration_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: "ACCID_TYPE" },
    { objectcode: "AUDIT_STATUS" }], function (data) {
      dataSelect = data.data;
      dataSelect.ACCID_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"
  };
  // （新增/修改）车牌号,承运商table
  var vehicleCarrierTable = {
    skin: "card",
    columns: [
      { id: "vehicleId", name: "id", type: "ro", width: "130", hidden: true },
      { id: "vehicleNo", name: "车牌号", type: "ro" },
      { id: "vehicleName", name: "车辆名称", type: "ro" },
      { id: "carrierId", name: "承运商ID", type: "ro", hidden: true },
      { id: "carrierName", name: "承运商", type: "ro" }
    ],
    multiselect: false,
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/tBaseVehicle/queryVehicleCarrier",
    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: "insurcode", name: "id", type: "ro", width: "130", hidden: true },
      { id: "branchid", name: "机构id", type: "ro", width: 120 },
      { id: "branchname", name: "机构牌号", type: "ro", width: 120 },
      { id: "insurcode", name: "保险单号", type: "ro", width: 120 },
      { id: "outdager", name: "出现日期", type: "ro", width: 120 },
      { id: "reportno", name: "报案编号", type: "ro", width: 120 },
      { id: "platenumber", name: "车牌号", type: "ro", width: 120 },
      { id: "reporter", name: "司机/报案人", type: "ro", width: 120 },
      { id: "ascriptionCompanyNo", name: "车辆归属单位", type: "ro", width: 120 },
      { id: "ascriptionCompanyName", name: "车辆归属单位名称", type: "ro", width: 120 },
      { id: "nonOperational", name: "使用性质", type: "ro", width: 120 },
      {
        id: "insurctype", name: "出现事故类型", type: "ro", width: 120, render: function (v) {
          return getSelectValue(dataSelect.ACCID_TYPE, v);
        }
      },
      { id: "dutyman", name: "责任人", type: "ro", width: 120 },
      { id: "resppro", name: "责任属性", type: "ro", width: 120 },
      { id: "amountdam", name: "定损金额", type: "ro", width: 120 },
      { id: "paidCustomer", name: "赔付单位/个人", type: "ro", width: 120 },
      { id: "amountcomp", name: "应赔付金额", type: "ro", width: 120 },
      { id: "amountact", 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 "修改^vehicleInsuranceRegistration_mod,删除^vehicleInsuranceRegistration_del";
        }
      }
    ],
    toolbar: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          { type: "calendar", className: "layui-col-md3", name: "startTime", label: "开始时间:", value: startTime },
          { type: "calendar", className: "layui-col-md3", name: "endTime", 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: "insurcode", 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: "reporter", label: "报案人:" },
          { type: "input", className: "layui-col-md3", name: "paidCustomer", 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/queryTVmInsuranceRegister", // 数据接口
    type: "post", // 数据提交方式，默认为get
    params: JSON.stringify({ startTime: startTime, endTime: endTime, statuses: ["5", "10"] }), // 查询提交参数，分页参数默认为pageNum,pageSize
    page: true, // 是否启用分页
    contentType: "application/json",
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  master_grid = new PlgGrid(master_grid_opts);
  master_grid.renderTo("vehicleInsuranceRegistration_master");
  master_grid.loadData();
  master_grid.attachToolBarEvent("onButtonClick", function (name) {
    switch (name) {
      case "master_search":
        var request = master_grid.getToolBarForm().getFormData();
        request.startTime = request.startTime ? Prolog.formatDate(request.startTime) + " 00:00:00" : "";
        request.endTime = request.endTime ? Prolog.formatDate(request.endTime) + " 23:59:59" : "";
        if (request.startTime > request.endTime) {
          layer.msg("开始时间不能大于结束时间");
          return false;
        }
        request.branchid = request.branchidList ? JSON.parse(request.branchidList)[0] : "";
        request.platenumber = request.platenumberList ? JSON.parse(request.platenumberList)[0] : "";
        request.statuses = ["5", "10"];
        dealNullQueryCondition(request);
        delete request.branchidList;
        delete request.platenumberList;
        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().setFormData({ startTime: startTime, endTime: endTime });
        break;
      case "master_add":
        $("#vehicleInsuranceRegistration_deit_form").html("");
        edit_form = new PlgForm(edit_form_opts);
        edit_form.enableItem("insurcode");
        $("#vehicleInsuranceRegistration_deit_title").html("新增");
        changePanel("#vehicleInsuranceRegistration_deit");
        break;
    }
  });

  // 单个删除
  window.vehicleInsuranceRegistration_del = function (rid) {
    tVmInsuranceDelete([{ insurcode: rid }]);
  };
  // 批量删除
  master_grid.attachPageBarEvent(function (name, ids) {
    let list = ids.split(",").map(item => {
      return { insurcode: item };
    });
    tVmInsuranceDelete(list);
  });
  function tVmInsuranceDelete(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/tVmInsuranceDelete", 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.vehicleInsuranceRegistration_mod = function (rid, rdata) {
    $("#vehicleInsuranceRegistration_deit_form").html("");
    edit_form = new PlgForm(edit_form_opts);
    rdata.branchidList = JSON.stringify([rdata.branchid]);
    rdata.platenumberList = JSON.stringify([rdata.platenumber]);
    edit_form.setFormData(rdata);
    edit_form.disableItem("insurcode");
    edit_form.setText("branchidList", rdata.branchname);
    edit_form.setText("platenumberList", rdata.platenumber);
    $("#vehicleInsuranceRegistration_deit_title").html("修改");
    changePanel("#vehicleInsuranceRegistration_deit");
  };

  // 编辑页form
  edit_form_opts = {
    renderer: "vehicleInsuranceRegistration_deit_form",
    items: [
      { type: "settings", labelAlign: "left", labelWidth: 95 },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md3", name: "insurcode", 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: "input", className: "layui-col-md3", name: "reportno", label: "报案编号:", required: true },
          { type: "calendar", className: "layui-col-md3", name: "outdager", label: "报案时间:", dateFormat: "%Y-%m-%d %H:%i:%s", enableTime: true, required: true }
        ]
      },
      {
        type: "row",
        list: [
          {
            type: "selectTable",
            className: "layui-col-md3",
            placeholder: "请选择车牌号",
            readonly: false,
            table: vehicleCarrierTable,
            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 : "",
                  ascriptionCompanyNo: isSelected ? sdata.carrierId : "",
                  ascriptionCompanyName: isSelected ? sdata.carrierName : ""
                });
              }
            }
          },
          { type: "hidden", name: "platenumber", label: "车牌号:" },
          { type: "input", className: "layui-col-md3", name: "reporter", label: "报案人:", required: true },
          { type: "input", className: "layui-col-md3", name: "ascriptionCompanyName", label: "车辆归属:", disabled: true, required: true },
          { type: "hidden", name: "ascriptionCompanyNo", label: "车辆归属code:" },
          { type: "input", className: "layui-col-md3", name: "nonOperational", label: "使用性质:", required: true }
        ]
      },
      {
        type: "row",
        list: [
          { type: "combo", className: "layui-col-md3", readonly: true, name: "insurctype", label: "事故类型:", options: dataSelect.ACCID_TYPE, required: true },
          { type: "input", className: "layui-col-md3", name: "dutyman", label: "责任人:", required: true },
          { type: "input", className: "layui-col-md3", name: "resppro", label: "责任属性:", required: true },
          { type: "input", className: "layui-col-md3", name: "amountdam", label: "定损金额:", required: true, validate: "Money_11bit" }
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md3", name: "paidCustomer", label: "赔付单位:", required: true },
          { type: "input", className: "layui-col-md3", name: "amountcomp", label: "应赔付金额:", required: true, validate: "Money_11bit" },
          { type: "input", className: "layui-col-md3", name: "amountact", label: "实际赔付金额:", required: true, validate: "Money_11bit" }
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md6", name: "memo", label: "备注:", rows: 3 }
        ]
      }
    ]
  };

  // 保存
  $("#vehicleInsuranceRegistration_deit_save").on("click", function () {
    let vdate = edit_form.validate();
    if (!vdate) return false;
    let formData = edit_form.getFormData();
    if (!formData.branchname) {
      layer.msg("请选择配送中心");
      return false;
    }
    if (!formData.platenumber) {
      layer.msg("请选择车牌号");
      return false;
    }
    formData.outdager = formData.outdager ? Prolog.formatDate(formData.outdager, "%YY-%MM-%DD %hh:%mm:%ss") : "";
    delete formData.branchidList;
    delete formData.platenumberList;
    let url = $("#vehicleInsuranceRegistration_deit_title").html() === "新增" ? UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/vehicleManage/tVmInsuranceSave" : UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/vehicleManage/tVmInsuranceUpdate";
    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("#vehicleInsuranceRegistration_main");
          master_grid.reload();
          return true;
        }
                return false;
      }, error: function () { PlgDialog.close(pload); return false; }
    });
  });
};