function setConfig(params) {
  return Object.assign(
    {},
    {
      skin: 'terrace',
      multiselect: true,
      // imagePath: "../../prologui/dist/vendors/dhtmlx/grid/skins/web/imgs",
      type: 'get', //数据提交方式，默认为get
      params: (function() {
        return {
          //  "warehouseId": getLocalStrongSelectedWarehouseIds().toString(),
          // //  "company_id": Prolog.getLocalStorage('userinfo').p_organizationid,   // 默认值是0
          //  "deleteFlag": 0
        }
      })(), //查询提交参数，分页参数默认为pageNum,pageSize
      page: true, //是否启用分页
      totalCount: 'totalCount', //总记录数字段，默认totalCount
      toolbar: []
    },
    params
  )
}

Prolog.download = function(url, fileName, hasAuth) {
  var xhr = new XMLHttpRequest()
  xhr.open('GET', url, true) //get请求，请求地址，是否异步
  if (hasAuth) {
    xhr.setRequestHeader('Authorization', localStorage.getItem('authorization'))
  }
  xhr.responseType = 'blob' // 返回类型blo

  xhr.onload = function() {
    // 请求完成处理函数

    if (this.status === 200) {
      var blob = this.response // 获取返回值
      const a = document.getElementById('down')
      a.href = URL.createObjectURL(blob)
      a.download = fileName
      a.click()
      //   URL.revokeObjectUrl(blob)
    }
  }
  // 发送ajax请求
  xhr.send()
}

/*
elem	指向容器选择器，如：elem: '#id'。也可以是DOM对象	string/object	-
url	    服务端上传接口，返回的数据规范请详见下文	string	-
data	请求上传接口的额外参数。如：data: {id: 'xxx'}

headers	接口的请求头。如：headers: {token: 'sasasas'}。注：该参数为 layui 2.2.6 开始新增
accept	指定允许上传时校验的文件类型，可选值有：images（图片）、file（所有文件）、video（视频）、audio（音频）	string	images
acceptMime	规定打开文件选择框时，筛选出的文件类型，值为用逗号隔开的 MIME 类型列表。如：
            acceptMime: 'image/*'（只显示图片文件）
            acceptMime: 'image/jpg, image/png'（只显示 jpg 和 png 文件）
            注：该参数为 layui 2.2.6 开始新增	string	images
exts	允许上传的文件后缀。一般结合 accept 参数类设定。假设 accept 为 file 类型时，那么你设置 exts: 'zip|rar|7z' 即代表只允许上传压缩格式的文件。如果 accept 未设定，那么限制的就是图片的文件格式	string	jpg|png|gif|bmp|jpeg
auto	是否选完文件后自动上传。如果设定 false，那么需要设置 bindAction 参数来指向一个其它按钮提交上传	boolean	true
bindAction	指向一个按钮触发上传，一般配合 auto: false 来使用。值为选择器或DOM对象，如：bindAction: '#btn'	string/object	-
field	设定文件域的字段名	string	file
size	设置文件最大可允许上传的大小，单位 KB。不支持ie8/9	number	0（即不限制）
multiple	是否允许多文件上传。设置 true即可开启。不支持ie8/9	boolean	false
number	设置同时可上传的文件数量，一般配合 multiple 参数出现。注意：该参数为 layui 2.2.3 开始新增	number	0（即不限制）
drag	是否接受拖拽的文件上传，设置 false 可禁用。不支持ie8/9	boolean	true

回调
choose	选择文件后的回调函数。返回一个object参数，详见下文	function	-
before	文件提交上传前的回调。返回一个object参数（同上），详见下文	function	-
done	执行上传请求后的回调。返回三个参数，分别为：res（服务端响应信息）、index（当前文件的索引）、upload（重新上传的方法，一般在文件上传失败后使用）。详见下文	function	-
error	执行上传请求出现异常的回调（一般为网络异常、URL 404等）。返回两个参数，分别为：index（当前文件的索引）、upload（重新上传的方法）。详见下文	function	-
*/
Prolog.upload = function(opts, hasAuth) {
  var upload = layui.upload //得到 upload 对象
  if (hasAuth) {
    if (opts.headers) opts.headers['Authorization'] = 'Bearer ' + localStorage.getItem('authorization')
    else opts.headers = { Authorization: 'Bearer ' + localStorage.getItem('authorization') }
  }

  //创建一个上传组件

  upload.render(opts)
}

/**
 *
 * @param {function} GridPlant hdw个人使用工厂函数
 */

function GridPlant(obj) {
  ;(this.isI18n = window.isI18n || false), //多语言默认false
    // enableSideBar: true,

    (this.idS = '') //
  this.rowId = ''
  this.PlgGridInstance = obj.instance
  this.addBtnUrl = obj.addBtnUrl
  this.delBtnUrl = obj.delBtnUrl
  this.downBtnUrl = obj.downBtnUrl
  this.exportBtnUrl = obj.exportBtnUrl
  this.importBtnUrl = obj.importBtnUrl
  this.fileText = obj.fileText || 'fileText' //中文模块名称
  this.moduleName = obj.moduleName //查日志使用的英文模块名称
  this.formDataArea = [750, 350]
  if (obj.instance.opts.formDataArea && obj.instance.opts.formDataArea.length > 0) {
    this.formDataArea[0] = obj.instance.opts.formDataArea[0] //弹框width
    this.formDataArea[1] = obj.instance.opts.formDataArea[1] //弹框height
  }
  this.t = (function(is) {
    if (is) {
      return (this.t = function(text) {
        return i18next.t(text)
      })
    } else {
      return (this.t = function(text) {
        return text
      })
    }
  })(this.isI18n)

  this.logBtn = function() {
    var _this = this

    if (!this.moduleName) {
      throw new Error('this.moduleName模块名称没定义')
    }
    var popUps = function(id, modulesName, contentContainer) {
      if (!id || !modulesName || !contentContainer) {
        throw new Error('当前传递的参数缺少值')
      }

      layer.open({
        type: 1, //此处以iframe举例
        title: `<div class="k-log-title">【${_this.t(modulesName)}】${_this.t('修改记录')}</div>`,
        area: ['470px', '430px'],
        shade: 0.3,
        shadeClose: true,
        offset: 'auto',
        content: contentContainer
      })
    }

    var paramsObj = {
      systemId: SYSTEMID, // 系统id
      bussinessKey1: this.moduleName, // 当前模块名
      bussinessKey2: this.rowId // 当前记录的id
    }
    var clearloading = Prolog.loading2()
    Prolog.syncAjax({
      url: APIS.ServiceLog.list + '?' + $.param(paramsObj),
      type: 'get',
      before: function() {},
      success: function(res) {
        if (res.success) {
          var obj = res.data
          var contentContainer = ''

          if (obj.length > 0) {
            obj.forEach(function(val) {
              contentContainer += `<li class="layui-timeline-item">
                  <i class="layui-icon layui-timeline-axis">&#xe63f;</i>
                    <div class="layui-timeline-content layui-text">
                      <h4 class="layui-timeline-title" id="updateTime">时间:<span class="k-log-createTime">${val.createTime}</span>----操作人: <span class="k-log-UserName">${val.userName}</span></h4>
                      <p class="k-log-des">
                        ${val.description}
                      </p>
                    </div>
                  </li>`
            })
          } else {
            contentContainer = `<li class="layui-timeline-item">
                <i class="layui-icon layui-timeline-axis">&#xe63f;</i>
                <div class="layui-timeline-content layui-text">
                  <h4 class="layui-timeline-title">
                        暂无日志
                      </h4>
                </div>
              </li>
                `
          }
          popUps(_this.rowId, _this.fileText, contentContainer)
        } else {
          console.error(res)
        }

        clearloading()
      },
      error: function(res) {
        console.error(res)
        clearloading()
      }
    })
  }

  this.addBtn = function() {
    this.formatForm(0, 'POST', this.t('新增'), this.addBtnUrl)
  }
  this.editBtn = function(type = 'PUT') {
    this.formatForm(1, type, this.t('编辑'), this.addBtnUrl)
  }
  this.delBtn = function(type = 'POST', param) {
    this.formatForm(3, type, this.t('是否删除数据'), this.delBtnUrl, param)
  }
  this.selectAllBtn = function() {
    this.formatForm(4, 'GET', '', this.addBtnUrl)
  }
  this.resetBtn = function() {
    this.formatForm(5, 'GET', '', this.addBtnUrl)
  }
  ;(this.exportBtn = function() {
    Prolog.download(
      this.exportBtnUrl + '?' + $.param(this.PlgGridInstance.getParams()),
      this.fileText + new Date().format('yyyy_MM_dd') + '.xls',
      true
    )
  }),
    (this.downBtn = function() {
      Prolog.download(this.downBtnUrl, `${this.fileText}.xls`, true)
    })
  this.deleteFlag = function(name, vlaue) {
    this.selectAllBtn()
  }
}

GridPlant.prototype.init = function() {
  var _this = this

  //分页点击d

  _this.PlgGridInstance.PageBarJump(function(obj, first) {
    _this.chekIds()
    _this.getRowId()
  })

  //注册layuiDate日期挂件

  var closeLoad
  Prolog.upload(
    {
      elem: $('#' + _this.PlgGridInstance.getPanelId() + ' .upload'),
      url: _this.importBtnUrl,
      accept: 'file', //普通文件
      exts: 'xls|xlsx',
      multiple: true,
      acceptMime: '.xls,.xlsx',
      before: function() {
        closeLoad = Prolog.loading2()
      },
      done: function(res, index, upload) {
        if (res.success) {
          layer.msg(res.message)
        } else {
          layer.open({
            type: 1,
            shade: false,
            title: false, //不显示标题
            content: res.message
          })
        }
        _this.PlgGridInstance.reload()
        closeLoad()
      },
      error: function(index, upload) {
        closeLoad()
        upload()
      }
    },
    true
  )

  setLayuiDate && setLayuiDate(_this.PlgGridInstance.getToolBarForm(), _this.PlgGridInstance.opts.toolbar, 'time')
  //注册事件
  //头部工具条按扭事件

  _this.PlgGridInstance.attachToolBarEvent('onchange', function(name, value) {
    if (name && _this.hasOwnProperty(name)) {
      _this[name](name, value)
    }
    return _this
  })
  //如果有右边栏
  if (_this.PlgGridInstance.opts.enableSideBar) {
    _this.PlgGridInstance.attachSideBarEvent('onButtonClick', function(name) {
      if (name && _this.hasOwnProperty(name)) {
        _this[name]()
      }
    })
  }

  _this.PlgGridInstance.attachToolBarEvent('onButtonClick', function(name) {
    if (name && _this.hasOwnProperty(name)) {
      _this[name]()
    } else if (name == 'plg-more-001') {
      _this.PlgGridInstance.resetSize()
    }
    return _this
  })
  _this.PlgGridInstance.attachEvent('onRowSelect', function(id, ind) {
    _this.getRowId()
  })

  _this.PlgGridInstance.attachEvent('onCheck', function(rId, cInd) {
    _this.chekIds()
  })
  _this.PlgGridInstance.attachEvent('onRowDblClicked', function(rId) {
    if (_this.PlgGridInstance.getSelectedRowData().deleteFlag === 1) {
      _this.logBtn()
    } else {
      _this.editBtn()
    }
  })
  _this.PlgGridInstance.attachEvent('onHeaderClick', function(ind, obj) {
    if (ind === 1) {
      _this.chekIds()
    }
    return _this
  })
  return _this
}

GridPlant.prototype.beforeRender = function(callback) {
  if (typeof callback == 'function') {
    this.beforeRender = callback
    this.beforeRender()
    return this
  }
}
//使用layui的data
function setLayuiDate(GridForm, arr, portName, typeValue) {
  if (!typeValue) typeValue = 'input'
  arr.forEach(function(item, index) {
    if (item.type == typeValue && item.name == portName) {
      var f = item.dateFormat || 'yyyy/MM/dd',
        t = item.dateType || 'date'

      GridForm.getInput(portName).setAttribute('readonly', true)

      layui.laydate.render({
        elem: GridForm.getInput(portName),
        type: t,
        lang: i18next.language,
        format: f,
        value: item.value,
        // theme: '#0959a7',
        //showBottom: false,
        change: function(value, date, endDate) {
          $('.layui-laydate-content')
            .off()
            .on('click', 'li', function() {
              value.substring(0, 19)
              value.replace(/-/g, '/')
              GridForm.setItemValue(portName, value ? value : '')
              $('.layui-laydate').remove() //删除
            })
        },
        done: function(value, date, endDate) {
          value.substring(0, 19)
          value.replace(/-/g, '/')
          GridForm.setItemValue(portName, value ? value : '')
        }
      })
      return false
    } else {
      if (item.list && item.list.length > 0) {
        setLayuiDate(GridForm, item.list, portName)
      }
      return false
    }
  })
}
GridPlant.prototype.formatForm = function(
  num,
  type,
  title,
  protUrl,
  param = {
    id: this.idS
  }
) {
  var _this = this
  //num=0 add num=1 edit num=3 del num=4 搜索 reset=5重制
  if (num === 3) {
    //del

    layer.confirm(
      title,
      {
        title: _this.t('提示'),
        btn: [_this.t('确定'), _this.t('取消')] //按钮
      },
      function(index) {
        var close = PlgDialog.loading2()
        Prolog.ajax({
          url: protUrl,
          type: type,
          data: param,
          dataType: 'json',
          success: function(data) {
            if (data.success) {
              _this.PlgGridInstance.reload()
              _this.chekIds()
            }
            layer.msg(_this.t(data.message))
            close()
            layer.close(index)
            _this.delBtnAfter()
          },
          error: function() {
            close()
          }
        })
      },
      function() {
        close()
      }
    )
    return
  } else if (num === 4) {
    //搜索
    // var WarehouseIds=getLocalStrongSelectedWarehouseIds();
    // getLocalStrongSelectedWarehouseIds()&& this.PlgGridInstance.getToolBarForm().setItemValue("warehouseId", WarehouseIds.toString())
    var fdata = this.PlgGridInstance.getToolBarForm().getFormData()

    if (fdata.startTime && fdata.endTime) {
      if (fdata.endTime.valueOf() - fdata.startTime.valueOf() < 0) {
        PlgDialog.msg('结束时间不得早于开始时间，请重新选择')
        this.PlgGridInstance.getToolBarForm()
          .getInput('startTime')
          .select()

        return false
      }
    }

    if (fdata['time']) {
      fdata['time'] = new Date(fdata['time'])
    }

    var obj = {}
    for (key in fdata) {
      if (fdata[key]) {
        obj[key] = fdata[key]
      }
    }

    this.selectAllBtnAfter(obj)

    var getToolBarForm = this.PlgGridInstance.getToolBarForm().getDForm()
    // //如果是无效数据就把chark隐藏
    // if (obj.deleteFlag && obj.deleteFlag === 1) {
    //   this.PlgGridInstance.setColumnHidden(1, true);
    //   getToolBarForm.hideItem("downBtn")
    //   getToolBarForm.hideItem("exportBtn")
    //   getToolBarForm.hideItem("exportBtn")
    //   getToolBarForm.hideItem("addBtn")
    //   getToolBarForm.hideItem("importBtn");
    //   getToolBarForm.hideItem("editBtn");
    //   getToolBarForm.hideItem("delBtn");

    // } else {
    //   obj.deleteFlag = 0;
    //   this.PlgGridInstance.setColumnHidden(1, false);
    //   getToolBarForm.showItem("downBtn")
    //   getToolBarForm.showItem("exportBtn")
    //   getToolBarForm.showItem("exportBtn")
    //   getToolBarForm.showItem("addBtn")
    //   getToolBarForm.showItem("importBtn");
    //   getToolBarForm.showItem("editBtn");
    //   getToolBarForm.showItem("delBtn");

    // }

    this.PlgGridInstance.setParams(obj)
    this.PlgGridInstance.reload()
    this.getRowId()
    this.chekIds()
    return
  } else if (num === 5) {
    var dform = this.PlgGridInstance.getToolBarForm()

    if (_this.PlgGridInstance.opts.enableSideBar) dform = this.PlgGridInstance.getSideBarForm()

    dform.clear()
    dform.getDForm().checkItem('deleteFlag', 0)
    dform.setItemValue('warehouseId', getLocalStrongSelectedWarehouseIds())

    return
  }

  _this.PlgGridInstance.showDialog(num, title, _this.formDataArea[0], _this.formDataArea[1], {
    url: protUrl,
    type: type,
    saveAfter: function(gridForm, data) {
      if (data.time && typeof data.time === 'string') {
        data.time = new Date(data.time)
      }
      if (data.id == '') {
        data.id = 0
      }
      if (data.warehouseName == '') {
        data.warehouseName = WAREHOUSE_CATEGORY.length > 0 && WAREHOUSE_CATEGORY[0].text
      }
      if(num==0){
        if(data.authorizedGrantTypes && data.authorizedGrantTypes.length>0){
          data.authorizedGrantTypes = data.authorizedGrantTypes.join(",");
        }else{
          data.authorizedGrantTypes = 'client_credentials';
        }
        
      }
      _this.showDialogSaveBtn(gridForm, data)

      return data
    },
    resetAfter: _this.showDialogResetBtn
  })
  //新增或修改弹出时的From表单
  var GridForm = _this.PlgGridInstance.getGridForm()

  setLayuiDate && setLayuiDate(GridForm, _this.PlgGridInstance.opts.formData, 'time')

  _this.showDialogAfter && _this.showDialogAfter(GridForm)

  if (num === 1 && type == 'PUT') {
    _this.editBtnAfter && _this.editBtnAfter(GridForm)
  }

  GridForm.attachEvent('onchange', function(name, value, state) {
    if (name == 'warehouseId') {
      var opt = Array.prototype.slice.call(GridForm.getSelect('warehouseId').children).filter(function(item) {
        return value == item.value
      })
      GridForm.setItemValue('warehouseName', opt[0].text)
    } else if (name == 'typeId') {
      var opt = Array.prototype.slice.call(GridForm.getSelect('typeId').children).filter(function(item) {
        return value == item.value
      })
      GridForm.setItemValue('type', opt[0].text)
    }
    _this.formOnChange && _this.formOnChange(name, value, GridForm)

    return
  })
  return
}
GridPlant.prototype.showDialogAfter = function(callback) {
  if (typeof callback === 'function') {
    return (this.showDialogAfter = callback)
  }
}
;(GridPlant.prototype.showDialogSaveBtn = function(callback) {
  if (typeof callback === 'function') {
    return (this.showDialogSaveBtn = callback)
  } else {
    return null
  }
}),
  (GridPlant.prototype.selectAllBtnAfter = function(callback) {
    if (typeof callback === 'function') {
      return (this.selectAllBtnAfter = callback)
    } else {
      return null
    }
  }),
  (GridPlant.prototype.editBtnAfter = function(callback) {
    if (typeof callback === 'function') {
      return (this.editBtnAfter = callback)
    }
  })

GridPlant.prototype.delBtnAfter = function(callback) {
  if (typeof callback === 'function') {
    return (this.delBtnAfter = callback)
  } else {
    return null
  }
}

GridPlant.prototype.showDialogResetBtn = function(callback) {
  if (typeof callback === 'function') {
    this.showDialogResetBtn = callback
    return this
  }
}
GridPlant.prototype.formOnChange = function(callback) {
  if (typeof callback === 'function') {
    return (this.formOnChange = callback)
  }
}
GridPlant.prototype.getRowId = function() {
  this.rowId = this.PlgGridInstance.getSelectedRowId()
  if (this.rowId && this.rowId.indexOf(',') == -1) {
    this.PlgGridInstance.getToolBarForm().enableItem('logBtn')
    //如果是无效数据就禁用编辑按钮
    if (this.PlgGridInstance.getSelectedRowData().deleteFlag !== 1) {
      this.PlgGridInstance.getToolBarForm().enableItem('editBtn')
    }
  } else {
    this.PlgGridInstance.getToolBarForm().disableItem('logBtn')
    this.PlgGridInstance.getToolBarForm().disableItem('editBtn')
  }

  return this
}

GridPlant.prototype.chekIds = function() {
  this.idS = this.PlgGridInstance.getCheckedIds()
  if (this.idS) {
    this.PlgGridInstance.getToolBarForm().enableItem('delBtn')
  } else {
    this.PlgGridInstance.getToolBarForm().disableItem('delBtn')
  }

  return this
}

// 获取版本号
function getVersion() {
  var version
  if (!version) {
    $.ajaxSettings.async = false
    $.get('/ops/getVersion', function(res) {
      version = res.version
    })
    $.ajaxSettings.async = true
  }

  return version
}

//表格圖片配置
;(Prolog.GridImageBasePath = './prologui/dist/images/PlgGrid/'),
  (Prolog.reloadToken = function() {
    Prolog.token = 'Bearer ' + localStorage.getItem('authorization')
  }),
  /**
   * 判断是否已登录（支持携带access_token和expir登录）
   */
  (Prolog.isLogined = function() {
    var tk = null
    var exp = null
    var P_GET = Prolog.getRequestParams()
    if (P_GET['access_token'] && P_GET['expir']) {
      tk = P_GET['access_token']
      exp = P_GET['expir']
      localStorage.setItem('authorization', tk)
      localStorage.setItem('token_expir', exp)
    } else {
      tk = 'Bearer ' + localStorage.getItem('authorization')
      exp = localStorage.getItem('token_expir')
    }
    if (tk != null && tk != '' && exp != null && exp != '') {
      var expir = parseInt(exp)
      var b = new Date().getTime() > expir ? false : true
      return b
    } else {
      return false
    }
  })
