/**
 * zzx
 * 2021.09.02
 * 近效期证件查询
 */
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 file_grid;

  // 跳转页面
  var carousel = layui.carousel;
  carousel.render({
    elem: "#nearValidityCertificate",
    autoplay: false,
    index: 0,
    arrow: "none",
    indicator: "none",
    anim: "fade",
    width: "100%", // 设置容器宽度
    height: "100%"
  });
  // 切换页面
  function changePanel(name) {
    var slideList = ["#nearValidityCertificate_main", "#nearValidityCertificate_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", "#nearValidityCertificate_view_return", function () {
    changePanel("#nearValidityCertificate_main");
  });

  // 获取默认时间
  var startTime = Prolog.formatDate(new Date()) + " 00:00:00";
  var endTime = getSpecDate(60, Prolog.formatDate(new Date())) + " 23:59:59";
  // 获取下拉框
  var dataSelect;
  getSelectGJ([
    { "objectcode": "CERTIFICATE_PROVIDER_TYPE" },
    { "objectcode": "CERTIFICATES_TYPE" }
  ], function (data) {
    dataSelect = data.data;
    dataSelect.CERTIFICATE_PROVIDER_TYPE.unshift({ "value": "", "text": "" });
    dataSelect.CERTIFICATES_TYPE.unshift({ "value": "", "text": "" });
  });

  // 司机table
  var driverTable = {
    // terrace显示全部，card分页显示
    skin: "card",
    // renderer:"grid",
    columns: [
      { id: "userId", name: "司机编号", type: "ro" },
      { id: "userName", 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: "userId", label: "司机编号:", width: 120 },
          { type: "newcolumn" },
          { type: "input", name: "userName", label: "司机名称:", width: 120 },
          { type: "newcolumn" },
          { type: "button", name: "querycarr", value: "查询" },
          { type: "newcolumn" },
          { type: "button", name: "car_Reset", value: "重置" }
        ]
      }
    ],
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/sysUserDuty/querySysUserDutyPop",
    pagebar: { type: "simple" },
    type: "post", // 数据提交方式，默认为get
    params: "{}", // 查询提交参数，分页参数默认为pageNum,pageSize
    contentType: "application/json",
    page: true, // 是否启用分页
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  // 车辆table
  var carTable = {
    // 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: "vehicleNo", label: "车辆编号:", width: 120 },
          { type: "newcolumn" },
          { type: "button", name: "querycarr", value: "查询" },
          { type: "newcolumn" },
          { type: "button", name: "car_Reset", value: "重置" }
        ]
      }
    ],
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/tBaseVehicle/queryPop",
    pagebar: { type: "simple" },
    type: "post", // 数据提交方式，默认为get
    params: "{}", // 查询提交参数，分页参数默认为pageNum,pageSize
    contentType: "application/json",
    page: true, // 是否启用分页
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  // 证件对象table
  var queryPopTable = {
    // 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: "input", name: "companyname", 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/queryCompanyPop",
    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: "paperid", name: "id", type: "ro", width: "130", hidden: true },
      { id: "papertypename", name: "证件类型", type: "ro", width: 120 },
      { id: "paperno", name: "证件编号", type: "ro", width: 120 },
      { id: "paperprovidortypeName", name: "证件对象类型", type: "ro", width: 120 },
      { id: "paperprovidor", name: "证件对象编号", type: "ro", width: 120 },
      { id: "paperprovidorname", name: "证件对象名称", type: "ro", width: 120 },
      { id: "paperauthority", name: "发证机构", type: "ro", width: 120 },
      { id: "fromdate", name: "证件有效期始", type: "ro", width: 120 },
      { id: "todate", name: "证件有效期止", type: "ro", width: 120 },
      { id: "daysremaining", name: "剩余过期天数", type: "ro", width: 120 },
      { id: "memo", name: "备注", type: "ro", width: 120 },
      {
        id: "op", name: "操作", type: "button", align: "left", width: 80, fixed: "right", render: function () {
          return "详情^nearValidityCertificate_view";
        }
      }
    ],
    toolbar: [
      { type: "settings", labelWidth: 130, labelAlign: "right" },
      {
        type: "row",
        list: [
          { type: "calendar", className: "layui-col-md4", name: "startTodate", label: "证件到期查询开始时间:", value: startTime, readonly: true },
          { type: "calendar", className: "layui-col-md4", name: "endTodate", label: "证件到期查询结束时间:", value: endTime, readonly: true },
          { type: "combo", className: "layui-col-md4", readonly: true, name: "paperprovidortype", label: "证件对象类型:", options: dataSelect.CERTIFICATE_PROVIDER_TYPE },
          { type: "combo", className: "layui-col-md4", readonly: true, name: "papertype", label: "证件类型:", options: dataSelect.CERTIFICATES_TYPE },
          { type: "input", className: "layui-col-md4", name: "paperno", label: "证件编号:" },
          { type: "input", className: "layui-col-md4", readonly: true, name: "paperprovidor", label: "证件对象:", placeholder: "请选择证件对象" },
          {
            type: "block", className: "layui-col-md4 form_btn_left",
            list: [
              { type: "button", className: "btn-normal", name: "master_search", value: "查 询" },
              { type: "newcolumn" },
              { type: "button", name: "master_reset", value: "重 置" }
            ]
          }
        ]
      }
    ],
    fixedLast: true, // 开启固定列，固定最后一行，倒数第二列不能隐藏
    multiselect: false, // 是否支持多选
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/pubPaperEarlyWarning/query", // 数据接口
    type: "post", // 数据提交方式，默认为get
    params: JSON.stringify({ startTodate: startTime, endTodate: endTime }),
    page: true, // 是否启用分页
    contentType: "application/json",
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  master_grid = new PlgGrid(master_grid_opts);
  master_grid.renderTo("nearValidityCertificate_master");
  master_grid.loadData();
  master_grid.attachToolBarEvent("onButtonClick", function (name) {
    switch (name) {
      case "master_search":
        var request = master_grid.getToolBarForm().getFormData();
        request.startTodate = request.startTodate ? Prolog.formatDate(request.startTodate) + " 00:00:00" : "";
        request.endTodate = request.endTodate ? Prolog.formatDate(request.endTodate) + " 23:59:59" : "";
        if (request.startTodate > request.endTodate) {
          layer.msg("开始时间不能大于结束时间");
          return false;
        }
        dealNullQueryCondition(request);
        master_grid.setParams(JSON.stringify(request));
        master_grid.reload();
        break;
      case "master_reset":
        master_grid.getToolBarForm().clear();
        master_grid.getToolBarForm().setFormData({ startTodate: startTime, endTodate: endTime });
        break;
    }
  });
  master_grid.getToolBarForm().attachComboEvent("paperprovidortype", "onChange", function () {
    master_grid.getToolBarForm().setFormData({ "paperprovidor": "" });
  });
  $("#nearValidityCertificate_master input[name=\"paperprovidor\"]").on("click", function () {
    const { paperprovidortype } = master_grid.getToolBarForm().getFormData();
    let dialog;
    switch (paperprovidortype) {
      case "1":
        dialog = queryPopTable;
        dialog.params = JSON.stringify({ "companytype": "Y" });
        break;
      case "2":
        dialog = driverTable;
        break;
      case "3":
        dialog = carTable;
        break;
      case "4":
        dialog = queryPopTable;
        dialog.params = JSON.stringify({ "companytype": "C" });
        break;
      case "5":
        dialog = queryPopTable;
        dialog.params = JSON.stringify({ "companytype": "V" });
        break;
      case "6":
        dialog = queryPopTable;
        dialog.params = JSON.stringify({ "companytype": "H" });
        break;

    }
    if (paperprovidortype) {
      paperprovidorDialog(dialog, paperprovidortype);
    }
  });
  // 弹窗
  function paperprovidorDialog(dialog, paperprovidortype) {
    PlgDialog.open({
      title: "请选择证件对象",
      shadeClose: true,
      type: 1, // 设置为1，手动控制dialog的开关
      area: ["850px", "500px"],
      content: "<div id =\"paperprovidor_dialog\"></div>" //iframe的url
    });
    $(".layui-layer-btn0").hide();
    let dialog_grid = new PlgGrid(dialog);
    dialog_grid.renderTo("paperprovidor_dialog");
    dialog_grid.reload();
    // 注册按钮事件
    dialog_grid.attachToolBarEvent("onButtonClick", function (name) {
      switch (name) {
        case "querycarr":
          var request = dialog_grid.getToolBarForm().getFormData();
          dialog_grid.setParams(JSON.stringify(request));
          dialog_grid.reload();
          break;
        case "car_Reset":
          dialog_grid.getToolBarForm().clear();
          break;
      }
    });
    // 注册表格双击选择事件
    dialog_grid.on("onRowSelect", function () {
      let data = dialog_grid.getSelectedRowData(), result;
      switch (paperprovidortype) {
        case "2":
          result = data.userId;
          break;
        case "3":
          result = data.vehicleNo;
          break;
        default:
          result = data.companycode;
          break;
      }
      master_grid.getToolBarForm().setFormData({ "paperprovidor": result });
      layer.closeAll();
    });
  }

  // 详情
  window.nearValidityCertificate_view = function (rid, rdata) {
    changePanel("#nearValidityCertificate_view");
    new PlgPanel({
      renderer: "nearValidityCertificate_view_details",
      skin: 2,
      header: {
        isShow: false
      },
      defaultBody: {
        layoutCol: 4,
        valueBj: true,
        cols: [
          [
            { label: "证件对象类型", value: rdata.paperprovidortypeName },
            { label: "证件对象", value: rdata.p_remark },
            { label: "有效期起", value: rdata.fromdate }
          ],
          [
            { label: "证件类型", value: rdata.papertypename },
            { label: "证件编号", value: rdata.paperno },
            { label: "有效期止", value: rdata.todate }
          ],
          [
            { label: "备注", value: rdata.memo },
            { label: "发证机构", value: rdata.paperauthority }
          ]
        ]
      }
    });

    // tab页
    new PlgTabs({
      renderer: "nearValidityCertificate_view_tabs", //挂载点
      indexActive: 0, //初始化默认选中项
      content: [
        {
          title: "图片",
          template:
            "<div style=\"height:100%;padding: 0px;\">" +
            "   <div class=\"layui-upload-list\" id=\"nearValidityCertificate_view_tabs_picture\"></div>" +
            "</div>"
        }, {
          title: "文件",
          template: "<div style=\"height:100%;padding: 0px;\">" +
            "<div class=\"layui-upload\"><button type=\"button\" class=\"layui-btn\" style='float:left;margin-left:5px' id=\"nearValidityCertificate_view_tabs_download\">批量下载</button></div>" +
            "<div id='nearValidityCertificate_view_tabs_file'></div></div>"
        }
      ]
    });

    getImgList({
      bizId: rdata.paperid,
      // bizId: "10000039",
      bizType: "0",
      enterpriseid: userGJ.p_enterpriseid
    });
    fileList({
      bizId: rdata.paperid + "file",
      // bizId: "10000039file",
      bizType: "0",
      enterpriseid: userGJ.p_enterpriseid
    });
  };

  // 查询图片
  var imgList = [];
  function getImgList(data) {
    imgList = [];
    $("#nearValidityCertificate_view_tabs_picture").html("");
    utilAjaxGJ("/app/biz-file/list", "post", data, (data) => {
      let imgListData = data.data;
      for (var i = 0; i < imgListData.length; i++) {
        imgList.push({ fileUrl: imgListData[i].file.fileUrl });
        $("#nearValidityCertificate_view_tabs_picture").append("<img onclick='showCustImg(this)' class='leftImg' src='" + imgListData[i].file.fileUrl + "'/>" +
          "<div class='deleteCustomerImg' id='" + imgListData[i].id);
      }
    });
  }
  //展示图片
  window.showCustImg = function (data) {
    let index = 0;
    for (let i = 0; i < imgList.length; i++) {
      let t = imgList[i];
      if (t.fileUrl == data.src) index = i;
    }
    imageView(imgList, index);
  };

  // 查询文件
  function fileList(parmas) {
    var file_grid_opts = {
      //terrace显示全部，card分页显示
      skin: "card",
      //renderer:"grid",
      columns: [
        { id: "id", name: "id", type: "ro", width: "100", hidden: true },
        { id: "originFileName", name: "文件名", type: "ro" },
        { id: "createDay", name: "上传时间", type: "ro" },
        { id: "fileSize", name: "大小", type: "ro" },
        {
          id: "op", name: "操作", type: "button", align: "center", fixed: "right", width: 100, render: function () {
            return "下载^nearValidityCertificate_download";
          }
        }
      ],
      // multiselect: true,
        url: "/app/biz-file/list", //数据接口
      type: "post", //数据提交方式，默认为get
      contentType: "application/json",
      params: "{}", //查询提交参数，分页参数默认为pageNum,pageSize
      page: false, //是否启用分页
      totalCount: "totalCount" //总记录数字段，默认totalCount
    };
    //分页参数 pageSize pageNum
    file_grid = new PlgGrid(file_grid_opts);
    file_grid.renderTo("nearValidityCertificate_view_tabs_file");
    getFileList(parmas);
  }
  //查询文件
  function getFileList(data) {
    utilAjaxGJ("/app/biz-file/list", "post", data, (data) => {
      let dList = data.data;
      for (var i = 0; i < dList.length; i++) {
        dList[i].originFileName = dList[i].file.originFileName;
        dList[i].createDay = dList[i].file.createDay;
        dList[i].fileSize = dList[i].file.fileSize / 1024 + "KB";
      }
      file_grid.getGrid().clearAll();
      //分组拆分条件查询
      file_grid.loadData({
        "success": true, "message": "查询成功", "code": "200", "data": {
          "list": dList, "totalCount": dList.length, "pageCount": 1, "pageNum": 1, "pageSize": dList.length, "startRow": 0, "endRow": dList.length
        }
      });
    });
  }

  // 下载
  window.nearValidityCertificate_download = function (rid) {
    Download([rid]);
  };
  // 批量下载
  $("#nearValidityCertificate_view_tabs_download").on("click", function () {
    let idList = [];
    let indexNum = file_grid.getGrid().getRowsNum();
    if (!indexNum) {
      layer.msg("没有数据");
      return;
    }
    for (let i = 0; i < indexNum; i++) {
      const element = file_grid.getRowData(file_grid.getRowId(i));
      dataList.push(element.id);
    }
    Download(idList);
  });
  function Download(ids) {
    Prolog.exportFile(
      "/app/biz-file/download2", "批量文件" + Prolog.formatDate(new Date(), "%YY%MM%DD") + ".zip", "", "get", { ids }, "application/zip"
    );
  }
};