/**
 * zzx
 * 2020.08.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, edit_form;
  var token = Prolog.reloadToken();
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 pload;
  var bizId;
  var deleteImgIdList = []; // 需要删除的图片id list
  var uploadImgNum = 0; // 需要上传的图片数量

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

  // 获取默认时间
  var startTime = Prolog.formatDate(new Date(), "%YY-%MM") + "-01 00:00:00";
  var endTime = Prolog.formatDate(new Date()) + " 23:59:59";
  // 获取下拉框
  var dataSelect = {
    TMS_ABNORMAL_TYPE: [],
    TMS_VEHICLE_TYPE: [],
    TIME_SECTION: [],
    ACCEPT_OR_NOT: [],
    AUDIT_FLOW_STATUS: []
  };
  getSelectGJ([
    { "objectcode": "TMS_ABNORMAL_TYPE" }, { "objectcode": "ACCEPT_OR_NOT" }, { "objectcode": "AUDIT_FLOW_STATUS" }], function (data) {
      dataSelect = data.data;
      dataSelect.TMS_ABNORMAL_TYPE.unshift({ "value": "", "text": "" });
      dataSelect.AUDIT_FLOW_STATUS.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
  };

  // 主页grid
  var master_grid_opts = {
    skin: "card",
    columns: [
      { id: "seqno", name: "id", type: "ro", width: "130", hidden: true },
      {
        id: "status", name: "状态", type: "ro", width: 120, render: function (v) {
          return getSelectValue(dataSelect.AUDIT_FLOW_STATUS, v);
        }
      },
      { id: "branchname", name: "配送中心", type: "ro", width: 120 },
      { id: "seqno", name: "异常编号", type: "ro", width: 120 },
      {
        id: "abnormalType", name: "异常类型", type: "ro", width: 120, render: function (v) {
          return getSelectValue(dataSelect.TMS_ABNORMAL_TYPE, v);
        }
      },
      { id: "relationBillno", name: "关联单号", type: "ro", width: 120 },
      { id: "relationVoucherno", name: "关联车牌", type: "ro", width: 120 },
      { id: "abnormalDescription", name: "异常原因", type: "ro", width: 180 },
      { id: "createperson", name: "异常上报人", type: "ro", width: 120 },
      { id: "createtime", name: "异常上报时间", type: "ro", width: 120 },
      { id: "abnormalLocation", name: "异常上报地点", type: "ro", width: 120 },
      {
        id: "acceptOrNot", name: "是否受理", type: "ro", width: 120, render: function (v) {
          return getSelectValue(dataSelect.ACCEPT_OR_NOT, v);
        }
      },
      { id: "acceptDescription", name: "受理结果", type: "ro", width: 120 },
      { id: "auditPerson", name: "审核人", type: "ro", width: 120 },
      { id: "auditDate", name: "审核时间", type: "ro", width: 120 },
      { id: "memo", name: "备注", type: "ro", width: 120 },
      {
        id: "op", name: "操作", type: "button", align: "left", fixed: "right", width: "100", render: function () {
          return "查看图片^abnormalReport_imageview,修改^abnormalReport_edit,删除^abnormalReport_del";
        }
      }
    ],
    toolbar: [
      { type: "settings", labelWidth: 70, 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: "relationBillno", label: "关联单号:" },
          { type: "combo", className: "layui-col-md3", readonly: true, name: "abnormalType", label: "异常类型:", options: dataSelect.TMS_ABNORMAL_TYPE },
          { type: "input", className: "layui-col-md3", name: "relationVoucherno", label: "关联车牌:" },
          { type: "combo", className: "layui-col-md3", readonly: true, name: "status", label: "审核状态:", options: dataSelect.AUDIT_FLOW_STATUS },
          {
            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: "新 增" }
            ]
          }
        ]
      }
    ],
    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_BUSINESS_SERVICE+"/abnormalReport/abnormalReportQuery", // 数据接口
    type: "post", // 数据提交方式，默认为get
    params: JSON.stringify({ startTime, endTime }),
    page: true, // 是否启用分页
    contentType: "application/json",
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  master_grid = new PlgGrid(master_grid_opts);
  master_grid.renderTo("abnormalReport_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] : "";
        dealNullQueryCondition(request);
        delete request.branchidList;
        master_grid.setParams(JSON.stringify(request));
        master_grid.reload();
        break;
      case "master_reset":
        master_grid.getToolBarForm().clear();
        master_grid.getToolBarForm().setFormData({ startTime, endTime });
        master_grid.getToolBarForm().setText("branchidList", "");
        break;
      case "master_add":
        edit_form.clear();
        edit_form.setText("branchidList", "");
        deleteImgIdList = [];
        uploadImgNum = 0;
        $("#abnormalReport_imgList").html("");
        changePanel("#abnormalReport_edit");
        break;
    }
  });

  // 注册详情页form表单
  let uploadLabel = "";
  uploadLabel += "异常图片:";
  uploadLabel += "<button type='button' class='layui-btn' id='abnormalReport_upload_btn' style='margin-left: 10px;'>上传图片</button>";
  uploadLabel += "<div class=\"layui-upload-list\">";
  uploadLabel += "  <blockquote class='layui-elem-quote layui-quote-nm' style='margin-top: 10px;'>";
  uploadLabel += "    <div class='layui-upload-list' id='abnormalReport_imgList'></div>";
  uploadLabel += "  </blockquote>";
  uploadLabel += "  <p id=\"abnormalReport_text\"></p>";
  uploadLabel += "</div>";

  var edit_form_opts = {
    renderer: "abnormalReport_edit_form",
    items: [
      { type: "settings", labelAlign: "left", labelWidth: 90 },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md3 no-border", name: "seqno", label: "异常编号:", readonly: true },
          {
            type: "selectTable",
            className: "layui-col-md3",
            placeholder: "请选择配送中心",
            readonly: false,
            table: branchTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "companyname",
            fieldValue: ["companyid", "companyname"],
            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;
                  }
                });
              },
              "afterClose": function (text, value) {
                if (!value) return;
                let selectedData = JSON.parse(value);
                if (selectedData.length > 0) {
                  edit_form.setItemValue("branchid", selectedData[0].companyid);
                  edit_form.setItemValue("branchname", selectedData[0].companyname);
                }
                else {
                  edit_form.setItemValue("branchid", "");
                  edit_form.setItemValue("branchname", "");
                }
              }
            }
          },
          { type: "hidden", name: "branchid", label: "配送中心id:" },
          { type: "hidden", name: "branchname", label: "配送中心名称:" },
          { type: "combo", className: "layui-col-md3", readonly: true, name: "abnormalType", label: "异常类型:", options: dataSelect.TMS_ABNORMAL_TYPE, required: true }
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md3", name: "relationBillno", label: "关联单号:", required: true },
          { type: "input", className: "layui-col-md3", name: "relationVoucherno", label: "关联车牌:", required: true }
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md6", name: "abnormalDescription", label: "异常描述:", rows: 3 }
        ]
      },
      {
        type: "row",
        list: [
          { type: "label", className: "layui-col-md9 type_label", name: "", label: uploadLabel, labelWidth: 800 },
          { type: "hidden", name: "imgurl", label: "图片上传地址:" }
        ]
      }
    ]
  };
  edit_form = new PlgForm(edit_form_opts);

  layui.use("upload", function () {
    var upload = layui.upload;
    var uploadInst = upload.render({
      elem: "#abnormalReport_upload_btn",
      url: "/app/biz-file/upload",
      headers: {
        Authorization: token
      },
      data: {
        bizId: function () {
          return bizId;
        },
        bizType: 0,
        enterpriseid: userinfo.p_enterpriseid,
        indexCol1: "02"
      },
      accept: "images",
      acceptMime: "image/*",
      field: "files",
      multiple: true,
      auto: false,
      bindAction: "#abnormalReport_edit_imgsave",
      size: 10 * 1024,
      choose: function (obj) {
        var files = this.files = obj.pushFile();
        //预读本地文件示例，不支持ie8
        obj.preview(function (index, file, result) {
          uploadImgNum++;
          let html = "";
          html += "<div style='display: inline-block;margin-right: 20px;'>";
          html += "   <img src='" + result + "' alt='" + file.name + "' class='abnormalReport_upload_image'>";
          html += "   <button class='layui-btn layui-btn-xs layui-btn-danger image_delete'>删除</button>";
          html += "</div>";
          let htmljs = $(html);
          // 删除
          htmljs.find(".image_delete").on("click", function () {
            delete files[index]; // 删除对应的文件
            htmljs.remove();
            uploadInst.config.elem.next()[0].value = ""; //清空 input file 值，以免删除后出现同名文件不可选
            uploadImgNum--;
          });
          // 点击展示
          htmljs.find(".abnormalReport_upload_image").on("click", function () {
            imageView([{ fileUrl: result }]);
          });

          $("#abnormalReport_imgList").append(htmljs);
        });
      },
      done: function (res, index) {
        // 上传成功
        if (res.success) {
          return delete this.files[index];
        }
        PlgDialog.close(pload);
        return layer.msg("图片上传失败");
      },
      allDone: function (obj) {
        // 当文件全部被提交后触发
        if (obj.total === obj.successful) {
          PlgDialog.close(pload);
          PlgDialog.msg("保存成功");
          changePanel("#abnormalReport_master");
          master_grid.reload();
        }
      },
      error: function () {
        //演示失败状态，并实现重传
        var errorText = $("#abnormalReport_text");
        errorText.html("<span style=\"color: #FF5722;\">上传失败</span> <a class=\"layui-btn layui-btn-xs demo-reload\">重试</a>");
        errorText.find(".demo-reload").on("click", function () {
          uploadInst.upload();
        });
      }
    });
  });

  // 查看图片
  window.abnormalReport_imageview = function (rid) {
    let request = {
      bizId: rid,
      bizType: 0,
      enterpriseid: userinfo.p_enterpriseid,
      indexCol1: "02"
    };
    querySysPicture(request).then(res => {
      imageView(res);
    });
  };

  // 修改
  window.abnormalReport_edit = function (rid, rdata) {
    deleteImgIdList = [];
    uploadImgNum = 0;
    let request = {
      bizId: rid,
      bizType: 0,
      enterpriseid: userinfo.p_enterpriseid,
      indexCol1: "02"
    };
    querySysPicture(request).then(res => {
      bizId = rid;
      rdata.branchidList = JSON.stringify([{ companyid: rdata.branchid, companyname: rdata.branchname }]);
      edit_form.setFormData(rdata);
      $("#abnormalReport_imgList").html("");
      edit_form.setText("branchidList", rdata.branchname);
      res.forEach(item => {
        let html = "";
        html += "<div style='display: inline-block;margin-right: 20px;' id='abnormalReport_" + item.id + "'>";
        html += "   <img src='" + item.fileUrl + "' class='abnormalReport_upload_image style='height: 100px;''>";
        html += "   <button class='layui-btn layui-btn-xs layui-btn-danger image_delete_old'>删除</button>";
        html += "</div>";
        let htmljs = $(html);
        // 删除
        htmljs.find(".image_delete_old").on("click", function () {
          deleteImgIdList.push(item.id);
          $("#abnormalReport_" + item.id).css("display", "none");
        });
        // 点击展示
        htmljs.find(".abnormalReport_upload_image").on("click", function () {
          getImgDataRecon(res, item.fileUrl);
        });
        $("#abnormalReport_imgList").append(htmljs);
      });
      changePanel("#abnormalReport_edit");
    });
  };

  // 图片放大
  function getImgDataRecon(res, src) {
    for (let i = 0; i < res.length; i++) {
      let rd = res[i];
      if (rd.fileUrl == src) {
        imageView(res, i);
        return;
      }
    }
  }

  // 删除
  window.abnormalReport_del = function (rid) {
    abnormalReportRemove([{ seqno: rid }]);
  };
  // 批量删除
  master_grid.attachPageBarEvent(function (name, ids) {
    let list = ids.split(",").map(item => {
      return { seqno: item };
    });
    abnormalReportRemove(list);
  });
  function abnormalReportRemove(idList) {
    layer.open({
      title: "删除",
      content: "是否删除？",
      btn: ["确认", "取消"],
      yes: function () {
        let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
        Prolog.ajax({
          url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/abnormalReport/abnormalReportRemove", 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; }
        });
      }
    });
  }

  // 保存
  $("#abnormalReport_edit_save").on("click", function () {
    let feik = edit_form.validate();
    if (!feik) return false;
    let { abnormalDescription, abnormalType, auditOpinion, branchid, branchname, relationBillno, relationVoucherno, seqno } = edit_form.getFormData();
    if (!branchid) {
      layer.msg("请选择配送中心");
      return;
    }
    if (!Prolog.isCarID(relationVoucherno)) {
      layer.msg("请输入正确的车牌");
      return;
    }
    let url = seqno ? UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/abnormalReport/abnormalReportUpdate" : UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/abnormalReport/abnormalReportAdd";
    let request = {
      abnormalDescription,
      abnormalType,
      auditOpinion,
      branchid,
      branchname,
      relationBillno,
      relationVoucherno,
      seqno
    };
    pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url, type: "post", contentType: "application/json", data: JSON.stringify(request),
      success: function (res) {
        if (res.success) {
          if (!seqno) bizId = res.data.seqno;
          if (!deleteImgIdList.length && !uploadImgNum) {
            PlgDialog.close(pload);
            PlgDialog.msg(res.message);
            changePanel("#abnormalReport_master");
            master_grid.reload();
          }
          else {
            bizFileDel().then(() => {
              if (!uploadImgNum) {
                PlgDialog.close(pload);
                PlgDialog.msg("保存成功");
                changePanel("#abnormalReport_master");
                master_grid.reload();
              }
              else {
                $("#abnormalReport_edit_imgsave").click();
              }
            });
          }
          return true;
        }
        PlgDialog.close(pload);
                return false;
      }, error: function () { PlgDialog.close(pload); return false; }
    });
  });

  // 删除已上传图片
  function bizFileDel() {
    return new Promise((resolve, reject) => {
      if (!deleteImgIdList.length) {
        resolve();
      }
      else {
        Prolog.ajax({
          url: "/app/biz-file/del", type: "post", contentType: "application/x-www-form-urlencoded", traditional: true, data: { ids: deleteImgIdList },
          success: function (data) {
            PlgDialog.close(pload);
            if (data.success) {
              resolve();
            }
            else {
              PlgDialog.alert(data.message || "接口调用失败");
              reject();
            }
            return false;

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