/* eslint-disable no-console */
/* eslint-disable brace-style */
/* eslint-disable block-scoped-var */
/* eslint-disable no-unused-vars */
/* eslint-disable quotes */
/**
 * 2018.10.27
 * guoj
 * 公共方法
 */
//获取用户信息
var userGJ = JSON.parse(window.localStorage.getItem('userinfo'));
//异步调后台
function utilAjaxGJ(url, type, data, Callback, contentType) {
  let pload = PlgDialog.load(2, { shade: [0.6, '#fff'] });
  Prolog.ajax({
    url: url,
    type: type,
    data: data,
    contentType: contentType,
    success: function (da) {
      PlgDialog.close(pload);
      if (typeof da != 'object') {
        da = JSON.parse(da);
      }
      if (da.success != null && da.success == false) {
        if (
          url == '/outbound/inv-move-task-h/confirm-sernum' ||
          url == '/inbound/rcvh/get-by-loc' ||
          url == '/inbound/rcvh/get-by-containerno' ||
          url == '/basic/inv-ser-no/collect-serno' ||
          url == '/outbound/inv-move-task-h/confirm-task'
        ) {
          layer.msg(da.message);
          Callback(da);
          return false;
        }
        setTimeout(() => {
          layer.alert(da.message || '接口调用失败');
        }, 300);
        // Callback(da);
        return false;
      }
      Callback(da);
    },
    error: function () { }
  });
}
//同步调后台
function utilSyncAjaxGJ(url, type, data, Callback, contentType) {
  PlgDialog.load(2, { shade: [0.6, '#fff'] });
  Prolog.syncAjax({
    url: url,
    type: type,
    data: data,
    contentType: contentType,
    success: function (da) {
      layer.closeAll();
      if (typeof da != 'object') da = JSON.parse(da);

      if (da.success != null && da.success == false) {
        setTimeout(() => {
          layer.alert(da.message);
        }, 300);
        Callback(da);
        return;
      }
      Callback(da);
    },
    error: function () { }
  });
}
//弹出导入导出
function utilImportGJ(Template, url) {
  layer.open({
    title: '导入导出',
    shadeClose: true,
    area: ['800px', '480px'],
    btn: [],
    content: ' <div id="app2"></div>', //iframe的url
    yes: function (index, layero) {
      //如果设定了yes回调，需进行手工关闭
      layer.close(index);
    }
  });
  var config2 = {
    indexActive: 0, //初始化默认选中项
    skin: 'card',
    content: [
      {
        title: '批量导入',
        template:
          '<div id="pidao">1、上传文件格式支持xls、xlsx或者zone，大小不超过2MB。<br />2、云解析DNS会按照预定模板扫描您的文件，并导入数据。下载模板<br />3、每次最多可以导入500条解析记录，超出的部分将不会导入。<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /></div><button class="layui-btn layui-btn-sm layui-btn-primary" id="GJXIAZ"><i class="layui-icon" >&#xe605;</i> 下载模板</button><button class="layui-btn layui-btn-sm layui-btn-primary" id="GJDAOR"><i class="layui-icon" >&#xe7ea;</i> 导入</button>'
      },
      {
        title: '批量导出',
        template:
          '<div id="pichu">批量导出<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /></div><button class="layui-btn layui-btn-sm layui-btn-primary" id="GJexports3"><i class="layui-icon" >&#xe7ea;</i> 导出</button>'
      }
    ]
  };
  var tabs2 = new PlgTabs(config2).renderTo('app2').on(function (ele) {
    // eslint-disable-next-line no-console
    console.log(this);
  });
  //下载工作台模板
  document.querySelector('#GJXIAZ').onclick = function () {
    window.open(Template);
  };
  //导入
  document.querySelector('#GJDAOR').onclick = function () { };
  //导出
  document.querySelector('#GJexports3').onclick = function () {
    PlgDialog.msg('导出成功');
  };

  //文件上传
  layui.use('upload', function () {
    var $ = layui.jquery,
      upload = layui.upload;

    upload.render({
      elem: '#GJDAOR',
      url: url,
      accept: 'file',
      before: function (obj) {
        console.log(this.item);
      },
      done: function (res) {
        console.log(res);
      }
    });
  });
}
//弹出导入导出2
function utilImportGJ2(id, ImportId, exportId, url, Callback) {
  var config2 = {
    indexActive: 0, //初始化默认选中项
    skin: 'card',
    content: [
      {
        title: '批量导入',
        template:
          '<div id="pidao">1、上传文件格式支持xls、xlsx或者zone，大小不超过2MB。<br />2、云解析DNS会按照预定模板扫描您的文件，并导入数据。下载模板<br />3、每次最多可以导入500条解析记录，超出的部分将不会导入。<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /></div><button class="layui-btn layui-btn-sm layui-btn-primary" id="' +
          ImportId +
          '"><i class="layui-icon" >&#xe7ea;</i> 导入</button>'
      },
      {
        title: '批量导出',
        template:
          '<div id="pichu">批量导出<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /></div><button class="layui-btn layui-btn-sm layui-btn-primary" id="' +
          exportId +
          '"><i class="layui-icon" >&#xe7ea;</i> 导出</button>'
      }
    ]
  };
  var tabs2 = new PlgTabs(config2).renderTo(id).on(function (ele) {
    console.log(this);
  });
  //导出
  document.querySelector('#' + exportId + '').onclick = function () {
    PlgDialog.msg('导出成功');
    Callback();
  };
  //文件上传
  layui.use('upload', function () {
    var token = window.localStorage.getItem('authorization');
    if (token == null || token == '') {
      PlgDialog.msg('登录状态异常，请重新登录！');
      window.location.href = '/menu?path=login';
      return;
    }
    var $ = layui.jquery,
      upload = layui.upload;
    upload.render({
      elem: '#' + ImportId + '',
      url: url,
      accept: 'file',
      headers: { Authorization: token },
      contentType: 'multipart/form-data',
      before: function (obj) {
        console.log(this.item);
      },
      done: function (res) {
        console.log(res);
      }
    });
  });
}

function getDeleteAll(grid) {
  var data = grid.getCheckedIds();
  if (data == null || data == '') {
    data = grid.getSelectedRowId();
  }
  if (data == null) {
    PlgDialog.msg('请选择行!');
    return;
  }
  data = data.split(',');
  return data;
}
//公共批量删除
function utilDelete(url, type, datas, Callback, contentType) {
  layer.open({
    title: '删除操作',
    content: '您确认要删除吗？',
    btn: ['确认', '取消'],
    yes: function (index, layero) {
      utilAjaxGJ(url, type, datas, Callback, contentType);
      layer.closeAll();
    },
    btn2: function (index, layero) {
      layer.closeAll();
    }
  });
}
//公共单个删除
function utilDeleteOne(grid, name, url, type, Callback, contentType) {
  var datas;
  var data = grid.getCheckedIds();
  if (data == null || data == '') {
    data = grid.getSelectedRowId();
  }
  if (data == null) {
    PlgDialog.msg('请选择行!');
    return;
  }
  datas = { id: data };
  layer.open({
    title: '删除操作',
    content: '您确认要删除吗？',
    btn: ['确认', '取消'],
    yes: function (index, layero) {
      utilAjaxGJ(url, type, datas, Callback, contentType);
      layer.closeAll();
    },
    btn2: function (index, layero) {
      layer.closeAll();
    }
  });
}
//公共查询下拉框
function getSelectGJ(data, Callback) {
  //查询下拉框
  utilSyncAjaxGJ(
    '/maindata/refdata/dtl/dd-list',
    'post',
    JSON.stringify(data),
    function (datas) {
      Callback(datas);
    },
    'application/json'
  );
}
//获取库别
function getDropDownWharehouseGJ() {
  var datas;
  utilSyncAjaxGJ('/basic/storeroom/list-all', 'post', { branchid: userGJ.p_companyid }, function (data) {
    datas = data.data;
    datas.unshift({ text: '', value: '' });
  });
  return datas;
}
//获取弹出框
function getEject(opts, top, left, Callback) {
  PlgDialog.open({
    title: '通用弹出框',
    offset: [top + 'px', left + 'px'],
    shadeClose: true, //点击遮罩关闭
    content: '<div id="EjectGJ" class="grid-container-full" ></div>',
    area: ['550px', '400px']
  });
  $('.layui-layer-btn0').hide();
  //分页参数 pageSize pageNum
  var gridGJ = new PlgGrid(opts);
  gridGJ.renderTo('EjectGJ');
  gridGJ.loadData();
  //按钮添加方法
  gridGJ.attachToolBarEvent('onButtonClick', function (name) {
    if (name == 'querycarr') {
      var fdata = gridGJ.getToolBarForm().getFormData();
      for (var key in fdata) {
        // eslint-disable-next-line no-console
        console.log(fdata.key);
        if (fdata[key] == '' || fdata[key] == null || fdata[key] == undefined) {
          fdata[key] = '%';
        }
      }
      if (opts.contentType == 'application/json') {
        var from_par = JSON.parse(opts.params);
        var jsonData = Object.assign(from_par, fdata);
        gridGJ.setParams(JSON.stringify(jsonData));
      } else {
        // eslint-disable-next-line no-redeclare
        var jsonData = Object.assign(opts.params, fdata);
        gridGJ.setParams(jsonData);
      }
      gridGJ.reload();
    }
    if (name == 'car_Reset') {
      gridGJ.getToolBarForm().clear();
    }
  });
  //双击事件
  gridGJ.on('onRowDblClicked', function (id, ids) {
    var data = gridGJ.getSelectedRowData();
    Callback(data);
  });
}
//打印服务
function PrintService(url, data, callback) {
  const moUrl = localStorage.getItem('printserviceip');
  var xhr = $.ajax({
    url: url || moUrl,
    timeout: 30000,
    type: 'POST',
    contentType: 'application/json',
    async: false,
    data: JSON.stringify(data), //报表数据
    dataType: 'json',
    success: function (msg) {
      callback(msg);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      console.error(XMLHttpRequest.status);
      callback(null);
    },
    complete: function (XMLHttpRequest, status) {
      //请求完成后最终执行参数
      if (status === 'timeout') {
        xhr.abort();
        callback(null);
      }
    }
  });
}
//根据value获取中文名称，datas数据集合，text数据值
function getSelectValue(datas, text) {
  var str = text;
  if (text == null) {
    str = '';
  } else if (datas == null) {
    str = text;
  } else {
    for (var i = 0; i < datas.length; i++) {
      if (datas[i].value == text) str = datas[i].text;
    }
  }
  return str;
}

/*
 * @method 删除 PlgGrid 行数据
 * @param grid - grid控件
 * @param url {string} - 数据接口地址
 * @param type {string} - 数据接口请求类型，为空时默认post
 * @param contenttype {string} - 数据接口请求 contentType 类型，为空时默认application/x-www-form-urlencoded
 * @param param {object} - 请求参数名 {"id":0}
 * @author jiw
 * @deprecated 删除PlgGrid选中行数据，删除成功后reload
 */
Prolog.delGridRowData = function (grid, url, type, contenttype, param, multiselect) {
  if (multiselect === false) {
    if (grid.getSelectedRowId() == null && param.length < 1) {
      PlgDialog.msg('请选择行!');
      return;
    }
  } else {
    if (grid.getCheckedIds() == null) {
      PlgDialog.msg('请选择行!');
      return;
    }
  }

  PlgDialog.confirm(
    '是否确定删除？',
    {
      title: '删除提示',
      btn: ['确定', '取消'],
      zIndex: layer.zIndex
    },
    function (index) {
      PlgDialog.close(index);

      if (type === '') type = 'post';
      if (contenttype === '') contenttype = 'application/x-www-form-urlencoded';

      Prolog.ajax({
        url: url,
        type: type,
        contentType: contenttype,
        data: param,
        success: function (data) {
          if (typeof data != 'object') data = JSON.parse(data);
          if (data.success) {
            setTimeout(() => {
              PlgDialog.msg(data.message);
            }, 300);
            setTimeout(() => {
              grid.reload();
            }, 10);
          } else {
            setTimeout(() => {
              PlgDialog.alert(data.message == null ? '接口调用失败' : data.message);
            }, 300);
          }
        },
        error: function () {
          PlgDialog.msg('接口调用失败');
        }
      });
    }
  );
};

/*
 * @method 根据code获取中文名称
 * @param rsp {object}- rsp数据集合,[{"value":"0","text":"test"}]
 * @param code {string} - code数据值
 * @author jiw
 * @deprecated 遍历集合,匹配code,返回 text
 */
Prolog.getNameByID = function (rsp, code) {
  let str = code;
  if (code == null) {
    str = '';
  } else if (rsp == null) {
    str = code;
  } else {
    rsp.forEach(item => {
      if (item.value == code) str = item.text;
    });
  }
  return str;
};

/*
 * @method 将通用参数数据返回数据，生成下拉框所需格式
 * @param data {object}- data数据集合,[{"value":"0","text":"test"}]
 * @param addNsN {bool} - 是否首行为空
 * @author jiw
 * @deprecated 将通用参数数据返回数据，生成下拉框所需格式
 */
Prolog.bindRefdata = function (data, addNsN) {
  let res = [];
  if (addNsN) {
    res.push({ text: '', value: '' });
  }
  data.forEach(item => {
    res.push(item);
  });
  return res;
};

/*
 * @method 日期格式化
 * @param time {Date}- 要格式化的日期
 * @param format {string} - 返回格式；年%YY；月%MM；日%DD，时%hh，分%mm，秒%ss，毫秒%ff
 * @author jiw
 * @deprecated 返回指定格式日期，默认返回yyyy-mm-dd；例：fromatDate(new Date("2019-01-01"), "%YY-%MM-%DD")，执行后返回 2019-01-01
 */
Prolog.formatDate = function (time, format) {
  if (time == '' || time == null) return '';
  let dt = new Date(time);
  let y = dt.getFullYear();
  let m = dt.getMonth() + 1 < 10 ? '0' + (dt.getMonth() + 1) : dt.getMonth() + 1;
  let d = dt.getDate() < 10 ? '0' + dt.getDate() : dt.getDate();
  let hh = dt.getHours() < 10 ? '0' + dt.getHours() : dt.getHours();
  let mm = dt.getMinutes() < 10 ? '0' + dt.getMinutes() : dt.getMinutes();
  let ss = dt.getSeconds() < 10 ? '0' + dt.getSeconds() : dt.getSeconds();
  let ff = dt.getMilliseconds();

  if (format == null || format == '' || format == undefined) {
    return y + '-' + m + '-' + d;
  }

  let arr = format.split('%');
  if (arr.length > 0) {
    let res = '';
    for (let i = 0; i < arr.length; i++) {
      let t = arr[i];
      if (t.substring(0, 2) == 'YY') {
        res += y;
      } else if (t.substring(0, 2) == 'MM') {
        res += m;
      } else if (t.substring(0, 2) == 'DD') {
        res += d;
      } else if (t.substring(0, 2) == 'hh') {
        res += hh;
      } else if (t.substring(0, 2) == 'mm') {
        res += mm;
      } else if (t.substring(0, 2) == 'ss') {
        res += ss;
      } else if (t.substring(0, 2) == 'ff') {
        res += ff;
      }
      if (i < arr.length - 1) res += t.substring(2);
    }
    return res;
  }
};

/*
* @method 导出xls并下载文件
* @param url {string}- 接口地址
* @param filename {string} - 文件全名，可为空，默认xls
* @param mtype {string} - 请求类型；可为空，默认get
* @param ctype {string} - Content-Type类型；可为空，默认 application/x-www-form-urlencoded
* @param data {string} - 请求参数；传JSON格式
* @author jiw
* @deprecated 调用接口并下载文件

    if (grid.getRowsNum() <= 0) {
        PlgDialog.msg("没有要导出的数据");
        return;
    }
    let url = "/export/v1.0";
    let name = "报表" + (Prolog.formatDate(new Date(), "%YY%MM%DD")) + ".xls"
    let par = grid.getSideBarForm().getFormData();
    Prolog.exportFile(url, name, "application/json", "post", par);
    Prolog.exportFile(url, name, "", "get", par);
    Prolog.exportFile(url, name, "", "post", par);

*/
Prolog.exportFile = function (url, filename, ctype, mtype, data, type) {
  let pload = PlgDialog.load(2, { shade: [0.6, '#fff'] });
  mtype = mtype.toLowerCase();
  ctype = ctype.toLowerCase();
  if (!ctype) ctype = 'application/x-www-form-urlencoded';
  if (!mtype) mtype = 'get';
  if (!filename) filename = '导出文件' + Prolog.formatDate(new Date(), '%YY%MM%DD') + '.xls';
  if (data == null || data == '') data = {};

  if (mtype == 'post' && ctype == 'application/json') {
    data = JSON.stringify(data);
  } else {
    ctype = 'application/x-www-form-urlencoded';
    let d = '';
    for (var key in data) {
      d += '&' + key + '=' + data[key];
    }
    data = d.substring(1);
    if (mtype == 'get') {
      url = url + '?' + data;
    }
  }
  if (!type) {
    type = 'text/xls';
  }
  //   type = 'application/zip';
  var token = localStorage.getItem('authorization');
  var xhr = new XMLHttpRequest();
  xhr.open(mtype, url);
  xhr.setRequestHeader('Authorization', token);
  xhr.setRequestHeader('Content-Type', ctype);
  xhr.responseType = 'blob';
  xhr.onreadystatechange = function () {
    PlgDialog.close(pload);
    if (xhr.readyState == 4 && xhr.status == 200) {
      var blob = new Blob([xhr.response], { type: type });
      var csvUrl = URL.createObjectURL(blob);
      var link = document.createElement('a');
      link.href = csvUrl;
      link.download = filename;
      link.click();
    }
  };
  xhr.send(data);
};

/*
 * @method 生成圆形
 * @param color {string} - 颜色
 * @author jiw
 * @deprecated 生成不同颜色的圆形
 */
Prolog.getCircle = function (color) {
  let arr = ['yellow', 'green', 'black', 'red', 'blue'];
  if (arr.indexOf(color) == -1) color = 'black';
  let str = '<span class="plg-span-' + color + '"></span>';
  return str;
};

/*
 * @method 验证是否IPV4
 * @param ip {string} - ip地址
 * @author jiw
 * @deprecated
 */
Prolog.isIP = function (ip) {
  var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
  return reg.test(ip);
};

/*
 * @method 绑定下拉数据JSON
 * @param rsp {object} - 绑定的变量
 * @param data {object} - 源数据
 * @param addNsN {object} - 是否增加空行
 * @author jiw
 * @deprecated
 */
Prolog.bindRefdata = function (rsp, data, addNsN) {
  if (addNsN) {
    rsp.push({ text: '', value: '' });
  }
  for (var i = 0; i < data.length; i++) {
    rsp.push({ text: data[i].text, value: data[i].value });
  }
};

//设置下拉表格方法
function setMethod(grid, table, Callback) {
  //工具栏按钮事件
  grid.attachToolBarEvent('onButtonClick', function (name) {
    if (name == 'querycarr') {
      var fdata = grid.getToolBarForm().getFormData();
      for (var key in fdata) {
        if (fdata[key] == '' || fdata[key] == null || fdata[key] == undefined) {
          if (key == 'likeItemcode' || key == 'itemid') {
            fdata[key] = '%';
          }
        }
      }
      if (table.contentType == 'application/json') {
        var from_par = JSON.parse(table.params);
        var jsonData = Object.assign(from_par, fdata);
        grid.setParams(JSON.stringify(jsonData));
      } else {
        // eslint-disable-next-line no-redeclare
        var jsonData = Object.assign(table.params, fdata);
        grid.setParams(jsonData);
      }
      grid.reload();
    }
    if (name == 'car_Reset') {
      grid.getToolBarForm().clear();
    }
  });
  //单击事件
  grid.on('onRowSelect', function (id, ind) {
    var data = grid.getSelectedRowData();
    Callback(data, id, ind);
  });
}
//返回 2015-03-19 格式
function FormatDate(datetime) {
  if (datetime == null) {
    return null;
  }
  var y = datetime.getFullYear();
  var m = datetime.getMonth() + 1;
  m = m < 10 ? '0' + m : m;
  var d = datetime.getDate();
  d = d < 10 ? '0' + d : d;
  return y + '-' + m + '-' + d;
}
//返回 2009-06-12 17:18:05 格式
function FormatDateTime(datetime) {
  if (datetime == null) {
    return '';
  }
  var year = datetime.getFullYear();
  var month = datetime.getMonth() + 1; //js从0开始取
  var date = datetime.getDate();
  var hour = datetime.getHours();
  var minutes = datetime.getMinutes();
  var second = datetime.getSeconds();
  if (month < 10) {
    month = '0' + month;
  }
  if (date < 10) {
    date = '0' + date;
  }
  if (hour < 10) {
    hour = '0' + hour;
  }
  if (minutes < 10) {
    minutes = '0' + minutes;
  }
  if (second < 10) {
    second = '0' + second;
  }
  var time = year + '-' + month + '-' + date + ' ' + hour + ':' + minutes + ':' + second; //2009-06-12 17:18:05
  return time;
}
//返回  17:18 格式
function FormatTime(datetime) {
  if (datetime == null) {
    return null;
  }
  var hour = datetime.getHours();
  var minutes = datetime.getMinutes();
  if (hour < 10) {
    hour = '0' + hour;
  }
  if (minutes < 10) {
    minutes = '0' + minutes;
  }
  var time = hour + ':' + minutes; //17:18
  return time;
}
/*
 * @method 返回  17:18:50 格式
 * @param datetime {Date} - 时间对象
 * @author zzx
 * @deprecated
 */
function FormatSecond(datetime) {
  if (datetime == null) {
    return null;
  }
  var hour = datetime.getHours();
  var minutes = datetime.getMinutes();
  var seconds = datetime.getSeconds();
  if (hour < 10) {
    hour = '0' + hour;
  }
  if (minutes < 10) {
    minutes = '0' + minutes;
  }
  if (seconds < 10) {
    seconds = '0' + seconds;
  }
  var time = hour + ':' + minutes + ':' + seconds; //17:18
  return time;
}
//from去重
function setFormDataGJ(plgform, data) {
  var fromData = plgform.getFormData();
  for (var key in fromData) {
    fromData[key] = data[key];
  }
  plgform.setFormData(fromData);
}

//导入事件公共方法
function uploadImportGJ(url, classname, Callback) {
  layui.use('upload', function () {
    var token = window.localStorage.getItem('authorization');
    if (token == null || token == '') {
      PlgDialog.msg('登录状态异常，请重新登录！');
      window.location.href = '/menu?path=login';
      return;
    }
    var upload = layui.upload;
    upload.render({
      elem: classname,
      url: url,
      headers: { Authorization: token },
      accept: 'file', //普通文件
      contentType: 'multipart/form-data',
      done: function (res) {
        if (res.success) {
          Callback(res);
        } else {
          PlgDialog.alert(res.message);
        }
      },
      error: function (index) {
        console.log(index);
      }
    });
  });
}

/**
 * 获取指定日期：
 * @param {number} days 指定日期的前后N天
 * @param {string} date 指定日期
 * @param {string} format 指定格式
 * @returns {string} 返回时间
 */
function getSpecDate(days, date, format) {
  days = days || 0;
  let currDate = date ? new Date(date) : new Date();
  let specTime = currDate.setDate(currDate.getDate() + days);
  const formatDate = (date, format) => {
    const padStart = (value, length, char) => {
      value = value + '';
      return value.padStart(length, char);
    };
    if (!date) return '--';
    let _date = date;
    format = format || 'YYYY-MM-DD';
    let splitArr = format.split(/(YYYY|MM|DD|hh|mm|ss)+/);

    if (typeof date !== 'object') {
      _date = new Date(date);
    }

    return splitArr
      .map(item => {
        if (item === 'YYYY') {
          return _date.getFullYear();
        }

        if (item === 'MM') {
          return padStart(_date.getMonth() + 1, 2, 0);
        }

        if (item === 'DD') {
          return padStart(_date.getDate(), 2, 0);
        }

        if (item === 'hh') {
          return padStart(_date.getHours(), 2, 0);
        }
        if (item === 'mm') {
          return padStart(_date.getMinutes(), 2, 0);
        }
        if (item === 'ss') {
          return padStart(_date.getSeconds(), 2, 0);
        }
        return item;
      })
      .join('');
  };
  return formatDate(specTime, format);
}

/*
 * @method 删除请求条件中属性值为空的属性
 * @param obj {} - 请求数据
 * @author zzx
 * @deprecated
 */
function dealNullQueryCondition(obj) {
  for (var p in obj) {
    if (obj[p] === '' || obj[p] !== 0 && obj[p] !== false && !obj[p] && (typeof obj[p] !== 'boolean' || typeof obj[p] !== 'number')) {
      delete obj[p];
    }
  }
}
/*
 * @method 获取系统信息
 * @author jiw
 * @deprecated 返回系统信息，系统名，版本号
 */
Prolog.getSysInfo = function () {
  let info = {
    sysid: 'plg-std-tms',
    sysname: 'UPCloud Solution For TMS',
    version: '1.0.2'
  };
  return info;
};

//返回 当前天前七天2015-03-19 格式
function ship_FormatDate(datetime) {
  datetime.setTime(datetime.getTime() - 7 * 24 * 60 * 60 * 1000);
  return FormatDate(datetime);
}

/*
 * @method 验证车牌是否正确
 * @param no {string} - 车牌号
 * @author jiw
 * @deprecated
 */
Prolog.isCarID = function (no) {
  var reg = /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/;
  return reg.test(no);
};

/*
 * @method 验证手机号是否正确
 * @param no {string} - 手机号
 * @author jiw
 * @deprecated
 */
Prolog.isMobileNo = function (no) {
  var reg = /^1[3456789]\d{9}$/;
  return reg.test(no);
};

/*
 * @method 验证座机号是否正确
 * @param no {string} - 座机号
 * @author jiw
 * @deprecated
 */
Prolog.isLandlineNo = function (no) {
  var reg = /0\d{2,3}-\d{7,8}/;
  return reg.test(no);
};

/*
 * @method 验证邮箱是否正确
 * @param no {string} - 邮箱
 * @author jiw
 * @deprecated
 */
Prolog.isEmail = function (no) {
  var reg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
  return reg.test(no);
};

/*
 * @method 获取图片url
 * @author zzx
 * @param request 接口请求参数
 */
function querySysPicture(request) {
  let pload = PlgDialog.load(2, { shade: [0.6, '#fff'] });
  return new Promise((resolve, reject) => {
    Prolog.ajax({
      url: '/business/sysFile/querySysPicture',
      type: 'post',
      contentType: 'application/json',
      data: JSON.stringify(request),
      success: function (res) {
        PlgDialog.close(pload);
        if (res.success) {
          resolve(res.data);
        } else {
          reject(res);
        }
      },
      error: function () {
        PlgDialog.close(pload);
        return false;
      }
    });
  });
}

/*
 * @method 弹窗查看图片
 * @author zzx
 * @param res 图片list
 * @param index 默认打开图片索引
 */
function imageView(res, index) {
  if (res.length == 0) {
    PlgDialog.msg('没有要查看的图片数据');
    return;
  }
  let ul = document.createElement('ul');
  for (let i = 0; i < res.length; i++) {
    let li = document.createElement('li');
    let img = new Image();
    img.src = res[i].fileUrl;
    li.appendChild(img);
    ul.appendChild(li);
  }
  let viewer = new Viewer(ul, {
    hidden: function () {
      //关闭后清理
      ul.remove();
      $('#viewer' + viewer.id).remove();
    },
    url: 'src'
  });
  viewer.view(index || 0);
}

/*
 * @method 验证是否为整数
 * @param val {string} - 数字
 * @author jiw
 * @deprecated
 */
Prolog.isInt = function (val) {
  let reg = /^-?[1-9]\d*$/;
  return reg.test(val);
};

/*
 * @method 将一个浮点数转成整数，返回整数和倍数。如 3.14 >> 314，倍数是 100
 * @param floatNum {number} 小数
 * @return {object}
 * {times:100, num: 314}
 * @author jiw
 */
function toInteger(floatNum) {
  var ret = { times: 1, num: 0 };
  if (Prolog.isInt(floatNum) || floatNum === 0) {
    ret.num = floatNum;
    return ret;
  }

  let strfi = floatNum + '';
  let list = strfi.split('.');
  ret.times = Number('1'.padEnd(list[1].length + 1, 0));
  ret.num = Number(list[0] + list[1]);

  // var dotPos = strfi.indexOf(".");
  // var len = strfi.substr(dotPos + 1).length;
  // var times = Math.pow(10, len);
  // var intNum = parseInt(floatNum * times + 0.5, 10);
  // ret.times = times;
  // ret.num = intNum;
  return ret;
}

/*
 * @method 浮点数实现加减乘除运算，确保不丢失精度
 * 思路：把小数放大为整数（乘），进行算术运算，再缩小为小数（除）
 * @param a {number} 运算数1
 * @param b {number} 运算数2
 * @param op {string} 运算类型，有加减乘除（+|-|*|/）
 * @author jiw
 * @deprecated  示例： Prolog.floatOper(10.908, 10, "-") //0.908
 */
Prolog.floatOper = function (a, b, op) {
  var o1 = toInteger(Number(a));
  var o2 = toInteger(Number(b));
  var n1 = o1.num;
  var n2 = o2.num;
  var t1 = o1.times;
  var t2 = o2.times;
  var max = t1 > t2 ? t1 : t2;
  var result = null;
  switch (op) {
    //加
    case '+':
      // 两个小数位数相同
      if (t1 === t2) {
        result = n1 + n2;
      }
      // o1 小数位 大于 o2
      else if (t1 > t2) {
        result = n1 + n2 * (t1 / t2);
      }
      // o1 小数位 小于 o2
      else {
        result = n1 * (t2 / t1) + n2;
      }
      return result / max;
    //减
    case '-':
      // 两个小数位数相同
      if (t1 === t2) {
        result = n1 - n2;
      }
      // t1 小数位 大于 t2
      else if (t1 > t2) {
        result = n1 - n2 * (t1 / t2);
      }
      // t1 小数位 小于 t2
      else {
        result = n1 * (t2 / t1) - n2;
      }
      return result / max;
    //乘
    case '*':
      result = n1 * n2 / (t1 * t2);
      return result;
    //除
    case '/':
      result = n1 / n2 * (t2 / t1);
      return result;
  }
};

// 获取右上角消息弹窗数据
function alertMessage_count() {
  Prolog.ajax({
    url: '/maindata/alertMessage/count',
    type: 'post',
    contentType: 'application/json',
    data: '{}',
    success: function (res) {
      if (res.success) {
        $('#remind-box-badge').html(res.data.alertMessageQuantity);
      }
    },
    error: function () { }
  });
}

// 自定义事件监听
class EventEmitter {
  constructor() {
    this._events = {};
  }
  on(event, callback) {
    //监听 event 事件,触发时调用 callback 函数
    let callbacks = this._events[event] || [];
    callbacks.push(callback);
    this._events[event] = callbacks;
    return this;
  }
  off(event, callback) {
    //停止监听 event 事件
    let callbacks = this._events[event];
    this._events[event] = callbacks && callbacks.filter(fn => fn !== callback);
    return this;
  }
  offByName(event) {
    //停止监听 event 事件
    for (const key in this._events) {
      if (key.includes(event)) {
        delete this._events[key];
      }
    }
    return this;
  }
  emit(event, ...args) {
    //触发事件,并把参数传给事件的处理函数
    const callbacks = this._events[event];
    callbacks.forEach(fn => fn.apply(null, args));
    return this;
  }
}

//实例化
const eve = new EventEmitter();

// 页面扩展字段方法
function extendedFieldList({ list, className = 'layui-col-md3' }, callback) {
  let gird_opts_list = [],
    form_opts_list = [],
    date_list = [];
  list.forEach(item => {
    gird_opts_list.push({ id: item.fieldName, name: item.displayName, type: 'ro', width: 120 });
    // 文本输入框
    if (item.fieldType === '1') {
      form_opts_list.push({ type: 'input', name: item.fieldName, label: item.displayName + ':', className });
    }
    // 数字输入框
    else if (item.fieldType === '2') {
      form_opts_list.push({ type: 'input', name: item.fieldName, label: item.displayName + ':', className, validate: 'Money_11bit' });
    }
    // 日期输入框
    else if (item.fieldType === '3') {
      form_opts_list.push({ type: 'calendar', name: item.fieldName, label: item.displayName + ':', className, readonly: true, enableTime: true, minutesInterval: 1, dateFormat: '%Y-%m-%d %H:%i:%s' });
      date_list.push(item.fieldName);
    }
    // 单选框
    else if (item.fieldType === '4') {
      let options = item.fieldChoiceValue.split(',').map(el => {
        return { value: el, text: el };
      });
      options.unshift({ value: '', text: '' });
      form_opts_list.push({ type: 'combo', name: item.fieldName, label: item.displayName + ':', className, options, readonly: true });
    }
  });
  callback && callback({ gird_opts_list, form_opts_list, date_list });
}

// 导入弹窗
function importDialog({ id, importUrl, downloadUrl, downloadName }) {
  const dialog_id = id + '_dialog';
  PlgDialog.open({
    title: '导入',
    shadeClose: true,
    type: 1, // 设置为1，手动控制dialog的开关
    area: ['500px', '300px'],
    content: '<div id =' + dialog_id + '></div>' //iframe的url
  });
  let dialogForm_opts = {
    renderer: dialog_id,
    items: [
      { type: 'settings', labelAlign: 'right', labelWidth: 75 },
      {
        type: 'row',
        list: [{ type: 'input', className: 'layui-col-md12 importName', name: 'importName', label: '导入文件:', readonly: true, placeholder: '点击选择导入文件' }]
      },
      {
        type: 'row',
        list: [
          {
            type: 'block',
            className: 'layui-col-md12 right',
            list: [
              { type: 'button', name: 'dialog_import', className: 'dialog_import btn-normal', value: '导入' },
              { type: 'newcolumn' },
              { type: 'button', name: 'dialog_download', className: 'btn-normal', value: '下载模板' },
              { type: 'newcolumn' },
              { type: 'button', name: 'dialog_cancel', value: '取消' }
            ]
          }
        ]
      }
    ]
  };
  dialogForm = new PlgForm(dialogForm_opts);
  // 初始化上传
  var uploadInst = layui.upload.render({
    headers: {
      Authorization: localStorage.getItem('authorization')
    },
    elem: '.importName',
    url: importUrl,
    size: 10 * 1024,
    accept: 'file',
    exts: 'xlsx|xls',
    field: 'file',
    auto: false,
    bindAction: '.dialog_import',
    choose: function (obj) {
      obj.preview(function (index, file) {
        dialogForm.setItemValue('importName', file.name);
      });
    },
    before: function () {
      pload = PlgDialog.load(2, { shade: [0.6, '#fff'] });
    },
    done: function (res) {
      PlgDialog.close(pload);
      if (res.success) {
        layer.closeAll();
        PlgDialog.msg(res.message);
        master_grid.reload();
      } else {
        setTimeout(() => {
          PlgDialog.alert(res.message || '接口调用失败');
        }, 300);
      }
    },
    error: function () {
      PlgDialog.close(pload);
      PlgDialog.msg('接口调用失败');
    }
  });

  // 表单按钮点击事件
  dialogForm.attachEvent('onButtonClick', function (name) {
    if (name === 'dialog_download') {
      let name = downloadName || '模板文件';
      Prolog.exportFile(downloadUrl, name + '.xlsx', '', 'post');
    } else if (name === 'dialog_import') {
      if (!dialogForm.getItemValue('importName')) {
        layer.msg('请选择导入文件');
        return false;
      }
    } else if (name === 'dialog_cancel') {
      layer.closeAll();
    }
  });
}
