import api from '@/api'
import router from '../router'
import { Message } from 'element-ui'
import Permission from '@/utils/permissions'
import showPermissionDialog from "@/utils/model/noPermission/index";
import { Base64 } from 'js-base64';
import Config from '@/config'
import moment from "moment";
import Cookies from "js-cookie";
export default {
  //滚动到顶部
  scrollToTop(){
    setTimeout(()=>{
      // 假设你有一个元素的ID是'myElement'
      const elements = document.getElementsByClassName('el-loading-parent--relative');
      if(elements && elements.length>0){
        for(var i = 0;i<elements.length;i++){
          var element = elements[i]
          element.scrollTo(
            {
                top: 0 ,
                behavior: "instant"
            }
          )
        }
      }
     },100)
  },
  /**
   * 防抖
   * @param {Function} func 
   * @param {Number} duration 
   * @returns 
   */
  debounce(func, duration = 500) {
    let timer;
    return () => {
      clearTimeout(timer)
      timer = setTimeout(func, duration)
    }
  },
  /**
   * 节流
   * @param {Function} func 
   * @param {Number} delay 
   * @returns 
   */
  throttle(func, delay = 2000) {
    let flag = true
    return () => {
      if (!flag) return;
      flag = false;
      setTimeout(() => {
        func()
        flag = true
      }, delay)
    }
  },

  /**
   * 树形数据转成扁平数据
   * @param {Array} data 树形数据
   * @param {Object} prop 配置
   * @returns 
   */
treeToArray(data,prop={children:children}){
  let res = []
  data.forEach(el=>{
    res.push(el)
    el[prop.children] && res.push(...this.treeToArray(el[prop.children])) 
  })
  return res
},
  
  //对象转数组
  objectToArray(val){
    var data = []
    if (Object.keys(val).length > 0) {
      Object.keys(val).forEach(item => {
        if(val[item]){
          data.push(
            {
              key: item,
              value: val[item]
            }
          )
        }
        
      })
    } else {
      return []
    }
    return data
  },
  //转简单数组
  ArrayToArray(data){
    var arr = []
    data.forEach(item => {
      if (item.type == 3) {
        arr.push({
          key:item.value,
          value:item.searchValue.map(itemValue => {
            return itemValue.value
          })
        })
      } else {
        arr.push({
          key:item.value,
          value:item.searchValue.label
        })
      }
    })
    return arr
  },

  /**
   * 获取uuid
   * @param {*} len 长度
   * @param {*} radix 进制
   * @returns 
   */
  uuid(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [], i;
    radix = radix || chars.length;
    if (len) {
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
    } else {
      var r;
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random()*16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }
    return uuid.join('');
  },

  /**
   * 从检索式中获取栏位和值
   * @param {String} queryString 
   * @returns {Array}
   */
  extractFieldsAndValues(queryString) {
    let result = []
    var obj = {
        field:'',
        value:[]
    }
    var sign = ['and','AND','OR','or','NOT','not']
    var arr = queryString.split(/(\s+ and | AND | OR | or | NOT | not \s+)/g)
    var regex = /\s/
    var regex1 = /^["].*["]$|^['].*[']$|^[“].*[”]$|^[‘].*[’]$/
    var regex2 = /['"’‘“”]/
    var values = []
    for(var i = 0;i<arr.length;i++){
      if(sign.includes(arr[i].trim())){
          values.push(arr[i])
          continue;
      }
      // if(regex.test(arr[i])){
      //     if(!regex1.test(arr[i])){
      //         var str = `"${arr[i]}"`
      //         values.push(str)
      //     }
      //     continue;
      // }
      values.push(arr[i])
    }
    var StringRegex = /[()]/g
    var longStr = ''
    for (let i = 0; i < values.length; i++){
        let item = values[i].trim()
        var index = item.indexOf('=')
        if(index==-1){
          index = item.indexOf('≡')
        }
        if(index!=-1){
          var field = item.substring(0,index)
          var value = item.substring(index+1,item.length)
          field = field.replace(StringRegex,'')
          value = value.replace(StringRegex,'').trim()
          obj = {
            field:field.trim(),
            value:[]
          }
          if(regex2.test(value)){//如果包含了引号
            if(regex1.test(value)){
              obj.value.push(value.replace(/['"’‘“”]/g,''))
            }else{
              longStr += value
            }
          }else{
            obj.value.push(value)
          }
          result.push(obj)
        }else{
          // if(longStr){
          //   var value = values[i].replace(StringRegex,'')
          //   longStr = longStr + value
          // }
          // if(regex2.test(item)){
          //   obj.value.push(longStr.replace(/['"’‘“”]/g,''))
          //   longStr = ''
          //   continue
          // }

          if(regex2.test(item)){//如果包含了引号
            if(regex1.test(item)){
              obj.value.push(item.replace(/['"’‘“”]/g,''))
              longStr = ''
            }else{
              longStr += values[i]
            }
          }else{
            if(longStr){
              var value = values[i].replace(StringRegex,'')
              longStr = longStr + value
            }
          }
          if(!sign.includes(item)){
              item = item.replace(StringRegex,'')
              var value = item.trim()
              if(regex2.test(item)){//如果包含了引号
                if(regex1.test(value)){
                  obj.value.push(value.replace(/['"’‘“”]/g,''))
                }else{
                  longStr += item
                }
              }else{
                obj.value.push(value)
              }
          }
            
        }



        // if(regex1.test(item)){
        //     if(!sign.includes(item)){
        //         item = item.replace(StringRegex,'')
        //         obj.value.push(item)
        //     }
        // }else{
        //     var index = item.indexOf('=')
        //     if(index==-1){
        //       index = item.indexOf('≡')
        //     }
        //     if(index!=-1){
        //         var field = item.substring(0,index)
        //         var value = item.substring(index+1,item.length)
        //         field = field.replace(StringRegex,'')
        //         value = value.replace(StringRegex,'')
        //         obj = {
        //             field:field,
        //             value:[value]
        //         }
        //         result.push(obj)
        //     }else{
        //         if(!sign.includes(item)){
        //             item = item.replace(StringRegex,'')
        //             obj.value.push(item)
        //         }
                
        //     }
        // }
    }
    var resultObj = {}
    for(var i = 0;i<result.length;i++){
      var item = result[i]
      if(resultObj[item.field]){
        resultObj[item.field] = [...new Set(resultObj[item.field].concat(item.value))]
      }else{
        resultObj[item.field] = [...new Set(item.value)]
      }
    }
    return resultObj
  },

  /**
   * 有空格添加引号
   * @param {String} val 
   * @returns 
   */
  AddQuotationMarks(val){
    var sign = ['and','AND','OR','or','NOT','not']
    if(typeof val != 'string'){
      val = val.toString()
    }
    var arr = val.split(/(\s+ and | AND | OR | or | NOT | not \s+)/g)
    var regex = /\s/
    var regex1 = /^["].*["]$|^['].*[']$|^[“].*[”]$|^[‘].*[’]$/
    var values = []
    for(var i = 0;i<arr.length;i++){
      if(sign.includes(arr[i].trim())){
        values.push(arr[i])
        continue;
      }
      if(regex.test(arr[i])){
        if(!regex1.test(arr[i])){
          var str = `"${arr[i]}"`
          values.push(str)
        }
        continue;
      }
      values.push(arr[i])
    }
    return values
  },

  //object转字符串
  objectToString(val) {
    var data = []
    if (val.constructor == Object) {
      if (Object.keys(val).length > 0) {
        Object.keys(val).forEach(item => {
          data.push(
            {
              key: item,
              value: val[item]
            }
          )
        })
      } else {
        return ''
      }
    } else if (val.constructor == Array) {
      if (val.length > 0) {
        data = val
      } else {
        return ''
      }
    } else {
      return val
    }
    // 生成字符串
    var str = ''
    data.forEach(item => {
      var value = ''
      if (Array.isArray(item.value)) {
        value = '('
        item.value.forEach((i,index)=>{
          if(/\s/.test(i)){
            value += `"${i}"`
          }else{
            value += i
          }
          if(index!= item.value.length- 1){
            value += ' OR '
          }
        })
        value += ')'
      } else {
        if (item.value) {
          // var values = this.AddQuotationMarks(item.value)
          // value = values.join('')
          value = `(${item.value})`
        } else {
          return
        }
      }
      if (str) {
        str = str + ' AND ' + item.key + '=' + value
      } else {
        str = str + item.key + '=' + value
      }

    })
    return str
  },

  /**
   * 导出Excel
   * @param {string} head excel头，可为空
   * @param {String} body excel体，可为空
   * @param {String} worksheetName  excel的worksheet名，可为空
   * @param {String} ExcelName excel文件名，可为空
   */
  exportExcel(head, body, worksheetName='Sheet1', ExcelName){
    // Worksheet名
    const worksheet = worksheetName
    const uri = 'data:application/vnd.ms-excel;base64,'

    //文件名
    if(!ExcelName){
      ExcelName = moment().format('YYYYMMDDHHmmss')
    }
    // 下载的表格模板数据
    const template = `<html xmlns:o="urn:schemas-microsoft-com:office:office"
      xmlns:x="urn:schemas-microsoft-com:office:excel"
      xmlns="http://www.w3.org/TR/REC-html40">
      <head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
      <x:Name>${worksheet}</x:Name>
      <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
      </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
      </head><body><table><tr>${head}</tr>${body}</table></body></html>`
    // 下载模板
    let link = document.createElement('a')
    link.setAttribute('href', uri + window.btoa(unescape(encodeURIComponent(template))))
    link.setAttribute('download', ExcelName + '.xls')
    link.click()
    link = null
  },
  /**
   * 获取字段列表
   * @param {Array} array 
   * @param {Function} fun 
   * @param {Object} props 
   * @returns 
   */
  getField(array, fun, props) {
    var type = {
      'Array': '3',
      'DateTime': '2',
      'String': '1'
    }

    //获取规范数据
    var keys = []
    var arr = []
    if (props) {
      keys = Object.keys(props)
    }
    //获取所需要的数据
    var newArray = array.filter(item => {
      return fun(item)
    })
    if (keys.length > 0) {
      newArray.forEach(item => {
        var obj = {}
        keys.forEach(key => {
          if (key == 'type') {
            obj[key] = type[item[props[key]]] || item[props[key]]
          }else if(key == 'value' && props.value == 'value'){
            obj[key] = item.field
          }else{
            obj[key] = item[props[key]]
          }

        })
        // 过滤不需要的数据
        if (['id'].includes(obj.value) == false) {
          arr.push(obj)
        }
      })
      return arr;
    }
    return newArray
  },

  /**
   * 获取表格数据
   * @author zhuliu
   * @param {object} row 当前行数据
   * @param {object} field 对应的栏位
   * @param {String} prop 数据类型为数组对象时所需要使用的字段
   * @param {object} data 需要获取对应label值时的字典对象（包含数据以及配置及{data,prop}）
   * @param {object} data.prop
   * @return {String} 返回值
   * @example
   * getColumnData({value:1},{type:'String',value:'value'}) //返回字符串1 
   */
  getColumnData(row, field, prop, data) {
    if(field.type == 'function'){
      return field.useFunction(row)
    }
    var text = this.getDataByField(row,field.value || field.field)
    
     if (field.type == 'Array') {
      if (text && text.length > 0) {
        if (prop) {
          return text.map(item => {
            return item[prop]
          }).join('、')
        }
        return text.join('、')
      } else {
        return '--'
      }
    } else if (field.type == 'Object') {
      if (!text) {
        return '--'
      }
      if (prop) {
        return text[prop]
      }
      return text.name
    }
    else {
      
      if (data) {
        if (data.data.constructor == Array) {
          var dataProp = data.prop || {
            label: 'label',
            value: 'value'
          }
          var obj = data.data.find(item => {
            return item[dataProp.value] == text
          })
          if (obj) {
            return obj[dataProp.label]
          } else {
            return '--'
          }
        } else {
          return data.data[text]
        }

      }
      if (text == '0') {
        return '0'
      }
      return text || ''
    }
  },
   /**
   * 根据配置的栏位获取数据
   */
   getDataByField(row,field){
    const parts = this.getFieldArray(field) 
    let current = row;  
      
    for (let i = 0; i < parts.length; i++) {  
        if (current && current.hasOwnProperty(parts[i])) {  
            current = current[parts[i]];  
        } else {  
            // 如果路径中的某一部分不存在，则返回undefined或自定义的默认值  
            return ''; // 或者你可以返回null、默认值等  
        }  
    }  
    return current; 
  },
  getFieldArray(field){
    return field.split('.')
  },

  //查看专利图片
  patentImage(data,field='path'){
    if(!data){
      return ''
    }
    // var dX1xbeyMT58WO = Cookies.get('dX1xbeyMT58WO')
    // if(!dX1xbeyMT58WO){
    //   Cookies.set('dX1xbeyMT58WO','5PmKdpvCP9bvUci.pbGtu16Dh4CPxOm_DwOEyLPAyeQD0ln01UVd.rbIhcx9Honn8aIfY0d1rRf6hkDWhtb7YhG')
    //   Cookies.set('dX1xbeyMT58WP','CcCkuLpOrY_fA5N26x4cgIjVxdpE4Il3jL5fAxCXFPY578HQoUmh1zGL9dykhJr2P_zq.UQMBIssHdE6B.XyBgaXPCk06Bh8VlyxFsdElTROT6U0FyBMd.YP3XAgavun25yQ8k1vWEVrdSvd7HA4ocHB1TE44Tcp1emTWETTEfxS7snPE4bi4LAQsO8LH8n0f8B813.iIQpUKAxqJEnLvOH5y6HlY989xBYGcP4oc.G')
    // }
    var url = ''
    if(typeof data == 'string'){
      url = data
    }
    var arr = data.map(item=>{
      return item[field]
    })
    url = arr[0]

    console.log(url)
    return url.replace('https://pss-system.cponline.cnipa.gov.cn','')
    
  },

  //查看图片1
  checkViewer(guid) {
    if(!guid){
      return ''
    }
    return `/api/fileManager/downloadFile?fileId=${guid}`
  },

  //查看图片2
  checkGuid(guid,type='pdf') {
    if(!guid){
      return ''
    }
    var src = this.checkViewer(guid)
    var previewUrl = src + '&fullfilename='+guid +'.'+type
    return `${Config.staticURL}/onlinePreview?url=` + encodeURIComponent(Base64.encode(Config.url+previewUrl))
  },

  //跳转预览界面
  previewFile(data,guid,type='pdf'){
    var FileUrl = this.checkGuid(guid,type)
    const router1 = router.resolve({
      path: '/checkFile',
      query: {
        // ...data,
        fileName:data.fileName,
        FileUrl: FileUrl,
        guid:guid
      }
    })
    window.open(router1.href, '_blank');
  },

   //查看专利详情
   checkPatentDetails(patentNo,projectId) {
      router.push(
        {
          path: '/patentDetails/' + patentNo,
          query: {
            projectId: projectId,
          }
        }
      )
  },

  /**
   * 查看显示栏位管理
   * @param {*} type //表格类型
   * @param {*} patentObj 参数配置
   * @param {*} url 接口名称
   * @returns 
   */
  async getCustomField(type, patentObj = {},url) {
    var params = {
      tableName: type,
      ...patentObj,
    }
    var apiItem = ''
    if(url){
      apiItem = url
    }else{
      // apiItem = Object.keys(patentObj).length > 0 ? 'getTableColumns':'getCustomField'
      apiItem = 'getTableColumns'
    }
    
    var a = []
    await api[apiItem](params).then((response) => {
      if (response.code == 200) {
        a = response.data.data
      }
    }).catch(error => {
      return []
    });
    return a
  },


  /**
   * 获取排序字段(sortProp:{order})
   * @param {Object} param0 {sort,column, prop, order,sortProp,defaultValue,multiple}
   * @returns 
   */
  getSortData({ sort, column, prop, order, sortProp, defaultValue, multiple }) {
    var sortProp1 = sortProp || {
      "orderBy": "orderBy",
      "orderType": 'orderType'
    }
    if (multiple) {
      var sortData = sort
    } else {
      var sortData = []
    }
    if (order == null) {
      if (defaultValue) {
        this.sort = [defaultValue]
      }
      this.sort = [
        {
          "orderBy": "createTime",
          "orderType": 1
        }
      ]
    } else {
      var orderType = {
        ascending: 0,
        descending: 1
      }
      var params = sortData.find(item => {
        return item[sortProp1.orderBy] == prop
      })
      if (params) {
        params[sortProp1.orderType] = orderType[order]
      } else {
        params = {}
        params[sortProp1.orderBy] = prop
        params[sortProp1.orderType] = orderType[order]
        sortData.push(params)
      }
    }
    return sortData
  },

  //显示表头数据
  renderHeaderMethods(h, { column }, message) {
    if(!column.sortable){
      return column.label
    }
    var message = '点击升序'
    switch (column.order) {
      case "":
        message = '点击升序'
        break;
      case "ascending":
        message = '点击降序'
        break;
      case 'descending':
        message = '点击取消排序'
        break
    }
    return [
      ,
      h(
        'el-tooltip',
        {
          props: {
            content: message, // 鼠标悬停时要展示的文字提示
            placement: 'top' // 悬停内容展示的位置
          }
        },
        [h('span', column.label)] // 图标
      )
    ]
  },

  /**
   * 跳转到导入专利界面
   * @param {Object} data 导入的参数
   * @param {*} type 导入类型
   * @param {*} params 其他数据
   */
  toImportParent(data, type,params={}) {
    if(!(Permission.FunPermissions('xiaoshi/patentImport'))){
      showPermissionDialog()
      return false
    }
    var types = {
      1: '/import',
      2: '/PatentNoImport',
      4: '/conditionImport'
    }
    var query = {
      ...params
    }
    if(data){
      if(data.type){
        data.type += ''
      }
      query.importData = JSON.stringify(data)
    }
    router.push(
      {
        path: types[type],
        query: query
      }
    )
  },
  // 校验文件是否全部上传并处理文件的guid
  allUploadFile(form) {
    var arr =[]
    let allUpload = this.validFile(form.systemFileList,arr)
    if (allUpload) {
      Message.warning('文件未全部上传，请耐心等待')
      return false
    }
    if(form.systemFileList && form.systemFileList.length>0){
      form.fileGuids = form.systemFileList.map(item => {
        return item.guid
      })
    }else{
      form.fileGuids = []
    }
    
  },
  //校验文件是否全部上传
  validFile(data,arr) {
    if (data && data.length > 0) {
      for(var i =0;i<data.length;i++){
        if(data[i] && data[i].guid){
          arr.push(data[i].guid)
        }else{
          return true
        }
      }
      return false
    } else {
      return false
    }
  },
  //校验是否全部上传
  checkUploadFile(data) {
    if(!data){
      return []
    }
    var arr = []
    let allUpload = this.validFile(data,arr)
    if (allUpload) {
      Message.warning('文件未全部上传，请耐心等待')
      return false
    }

    return arr
  },




}
