
import Vue from 'vue'
import 'normalize.css/normalize.css' // A modern alternative to CSS resets

import ElementUI from 'element-ui'
import { getBasicDataAllSelect, getFrontInternationalizationList, getCurrentPublishInfo } from '@/api/dictionary/dictionary'
import './assets/css/theme-blue/index.css' // 浅绿色主题
import './assets/css/iconfont/index.css' // 阿里巴巴图标库
import i18n from './lang'
import '@/styles/index.scss' // global css

import vcrontab from "vcrontab";
Vue.use(vcrontab); //使用方式：

import App from './App'
import store from './store'
import router from './router'
import WHITELIST from "./utils/whiteList"
import '@/icons' // icon
import '@/permission' // permission control
import md5 from 'js-md5'
import VueClipboard from 'vue-clipboard2'
Vue.use(VueClipboard)
import permission from './utils/permission'
Vue.use(permission)

import Viewer from 'v-viewer'
import './assets/css/viewer.css'


Vue.use(Viewer)

Viewer.setDefaults({
  Options: {
    'inline': true,
    'button': true,
    'navbar': true,
    'title': true,
    'toolbar': true,
    'tooltip': true,
    'movable': true,
    'zoomable': true,
    'rotatable': true,
    'scalable': true,
    'transition': true,
    'fullscreen': true,
    'keyboard': true,
    'url': 'data-source'
  }
})

import hasPermi from './directive/permission'
Vue.use(hasPermi)

// set ElementUI lang to EN
// Vue.use(ElementUI, { locale, size: 'medium' })
// 如果想要中文版 element-ui，按如下方式声明
// Vue.use(ElementUI)
Vue.use(ElementUI, {
  i18n: (key, value) => i18n.t(key, value),
  size: 'medium'
})
import upload from '@/components/element-ui/upload'
Vue.use(upload)

import adaptive from '@/directive/adaptive/index'
// 表格自适应指令
Vue.use(adaptive)
import dialogDrag from '@/directive/dialogDrag'
// 窗口拖拽
Vue.use(dialogDrag)
if (!String.prototype.replaceAll) {
  String.prototype.replaceAll = function (str, newStr) {
    // 正则表达式
    if (Object.prototype.toString.call(str).toLowerCase() === '[object regexp]') {
      return this.replace(str, newStr)
    }
    // 字符串
    return this.replace(new RegExp(str, 'g'), newStr)
  }
}
import { parseTime, resetForm, selectDictLabel, selectDictLabels, handleTree, params } from '@/utils/ruoyi'
import { xfHasPermi } from '@/utils/hasPermi'
// 字典数据组件
import DictTag from '@/components/DictTag'
import DictData from '@/components/DictData'
import { getBasicDataSelect } from '@/api/dictionary/dictionary'
import { checkConfig } from '@/const/check/index'
// 全局方法挂载
var $q = params
Vue.prototype.checkConfig = checkConfig
Vue.prototype.$q = $q()
Vue.prototype.hasPermi = xfHasPermi
Vue.prototype.getDicts = getBasicDataSelect
Vue.prototype.selectDictLabel = selectDictLabel
Vue.prototype.selectDictLabels = selectDictLabels
Vue.component('DictTag', DictTag)
// 全局方法挂载
Vue.prototype.parseTime = parseTime
Vue.prototype.resetForm = resetForm
Vue.prototype.selectDictLabel = selectDictLabel
// Vue.prototype.download = download
Vue.prototype.handleTree = handleTree
Vue.prototype.$EventBus = new Vue()
Vue.prototype.$getObjectName = (url) => {
  // console.log(url,'url')
  // console.log(Vue.prototype.OSSclientConfig.viewEndpoint,'url')
  var value = url;
  let basePath = Vue.prototype.OSSclientConfig.viewEndpoint;
  if (Vue.prototype.OSSclientConfig.ObjectStoreUse === 'AliyunOSS') {
    basePath = Vue.prototype.OSSclientConfig.endPoint.split('https://').length > 1 ? Vue.prototype.OSSclientConfig.endPoint.split('https://')[1] : Vue.prototype.OSSclientConfig.endPoint;
  }
  return value.split(basePath)[1];
}
Vue.prototype.getGuid = (text) => {
  text = md5(text)
  let t1, t2, t3, t4, t5, t6, t7, t8, t9, t10
  t1 = text.substr(0, 2)
  t2 = text.substr(2, 2)
  t3 = text.substr(4, 2)
  t4 = text.substr(6, 2)
  t5 = text.substr(8, 2)
  t6 = text.substr(10, 2)
  t7 = text.substr(12, 2)
  t8 = text.substr(14, 2)
  t9 = text.substr(16, 4)
  t10 = text.substr(20, 12)
  console.log(`${t4 + t3 + t2 + t1}-${t6 + t5}-${t8 + t7}-${t9}-${t10}`)
  return `${t4 + t3 + t2 + t1}-${t6 + t5}-${t8 + t7}-${t9}-${t10}`
}
///50350000-3e2c-0016-eb4c-08db926b69d6/Image/84410000-3e10-0016-d156-08da242403fe/50350000-3e2c-0016-414e-08db926d9135/50350000-3e2c-0016-fd9d-08db926d9137/1.2.156.110002.21.2019.1.9.84822154.1/1.3.12.2.1107.5.1.4.73793.30000019010509500386600308609/1.3.12.2.1107.5.1.4.73793.30000019010509500386600308616/7fba7d7e-b3b3-d989-fa54-82e41f87a6ed
// Vue.prototype.getGuid('1.2.156.110002.21.2019.1.9.84822154.11.3.12.2.1107.5.1.4.73793.300000190105095003866003086091.3.12.2.1107.5.1.4.73793.3000001901050950038660030861650350000-3e2c-0016-eb4c-08db926b69d6')
//7fba7d7e-b3b3-d989-fa54-82e41f87a6ed
Vue.prototype.$validatePassword = (rule, value, callback) => {
  var lang = zzSessionStorage.getItem('lang') ? zzSessionStorage.getItem('lang') : 'zh'
  /* eslint-disable */
  var reg1 = eval(process.env.VUE_APP_PASSWORD_FOR_PERMISSION) ? new RegExp(`${process.env.VUE_APP_PASSWORD_FOR_REGULAR}`) : /.*/g; //密码必须是8位以上、必须含有字母、数字、特殊符号
  if (!reg1.test(value)) {
    callback(lang === 'zh' ? new Error("密码必须包含：1）8 – 32 个字符；2）至少1个数字；3) 至少1个大写字母；4）至少1个小写字母；5）至少1个特殊字符 (~!-@#$%^&*_+?)") : new Error('Passwords must have: 1) 8 - 32 characters; 2) At least 1 number; 3) At least 1 uppercase letter; 4) At least 1 lowercase letter; 5) At least 1 special character (~!-@#$%^&*_+?) '))
  } else {
    callback();
  }
}

DictData.install()

import global_ from './components/Global'
Vue.prototype.GLOBAL = global_
Vue.config.productionTip = false
Vue.prototype.$upload = () => {
  _vm.$forceUpdate()
}
Vue.prototype.fileToBlob = (file) => {
  // 创建 FileReader 对象
  const reader = new FileReader()
  return new Promise(resolve => {
    // FileReader 添加 load 事件
    reader.addEventListener('load', (e) => {
      let blob
      if (typeof e.target.result === 'object') {
        blob = new Blob([e.target.result])
      } else {
        blob = e.target.result
      }
      resolve(blob)
    })
    // FileReader 以 ArrayBuffer 格式 读取 File 对象中数据
    reader.readAsArrayBuffer(file)
  })
}

var _vm
async function VueInit() {
  var params
  if (~window.location.href.indexOf('/readingDicoms') || ~window.location.href.indexOf('/noneDicomReading') || ~window.location.href.indexOf('/criterionquestions')) {
    params = $q('TrialReadingCriterionId')
  }
  var res = await getBasicDataAllSelect(params)
  var Internationalization = await getFrontInternationalizationList()
  Vue.prototype.$tl = Internationalization.Result
  let zhMessages = {}, enMessages = {}
  Vue.prototype.$tl.forEach(v => {
    // zhMessages[v.Description + '_' + v.Code] = v.ValueCN
    // enMessages[v.Description + '_' + v.Code] = v.Value
    zhMessages[v.Code] = v.ValueCN
    enMessages[v.Code] = v.Value
  })
  // 获取版本信息
  let PublishInfo = await getCurrentPublishInfo();
  Vue.prototype.$version = PublishInfo.Result;
  i18n.mergeLocaleMessage('zh', zhMessages)
  i18n.mergeLocaleMessage('en', enMessages)
  let d = function (code) {
    var dictInfo = res.Result
    var lang = zzSessionStorage.getItem('lang') ? zzSessionStorage.getItem('lang') : 'zh'
    try {
      for (var code in dictInfo) {
        var dictList = (dictInfo[code] && dictInfo[code].length > 0) ? dictInfo[code].map(dict => {
          return {
            id: dict.Id,
            label: lang === 'zh' ? dict.ValueCN : dict.Value,
            value: dict.DataTypeEnum === 3 ? eval(dict.Code) : dict.IsEnumInt ? parseInt(dict.Code) : dict.Code,
            raw: Object.assign({}, dict),
            IsBaseLineUse: false,
            IsFollowVisitUse: false
          }
        }) : []
        dictInfo[code] = dictList
      }
    } catch (e) {
      console.error(e)
    }
    return dictInfo
  }()
  Vue.prototype.$d = d
  Vue.prototype.$fd = function (code, v, type) {
    try {
      // code === 'YesOrNo' ? console.log(d) : ''
      type = type || 'value'
      return d[code].find(i => {
        return i[type] === v
      }) ? d[code].find(i => {
        return i[type] === v
      }).label : ''
    } catch (e) {
      console.log(e)
    }
  }
  Vue.prototype.$updateDictionary = function () {
    Vue.prototype.$d = function (code) {
      var dictInfo = res.Result
      var lang = zzSessionStorage.getItem('lang') ? zzSessionStorage.getItem('lang') : 'zh'
      try {
        for (var code in dictInfo) {
          var dictList = (dictInfo[code] && dictInfo[code].length > 0) ? dictInfo[code].map(dict => {
            return {
              id: dict.raw.Id,
              label: lang === 'zh' ? dict.raw.ValueCN : dict.raw.Value,
              value: dict.raw.DataTypeEnum === 3 ? eval(dict.raw.Code) : dict.raw.IsEnumInt ? parseInt(dict.raw.Code) : dict.raw.Code,
              raw: Object.assign({}, dict.raw),
              IsBaseLineUse: false,
              IsFollowVisitUse: false
            }
          }) : []
          _vm.$set(dictInfo, code, dictList)
        }
      } catch (e) {
        console.error(e)
      }
      return dictInfo
    }()
    _vm.$forceUpdate()
  }
  Vue.prototype.$reg = () => {
    // if (localStorage.getItem('CompanyInfo')) {
    //   let { EmailRegexStr } = JSON.parse(localStorage.getItem('CompanyInfo'))
    //   if (EmailRegexStr) {
    //     return { EmailRegexStr }
    //   }
    // } else if (Vue.prototype.$companyInfo) {
    //   let { EmailRegexStr } = Vue.prototype.$companyInfo
    //   if (EmailRegexStr) {
    //     return { EmailRegexStr }
    //   }
    // }
    return { EmailRegexStr: '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$' };
  }
  Vue.prototype.$path = []
  var t = function (key) {
    // if (![Vue.prototype.toPath + '_' + key].includes(Vue.prototype.$path)) {
    if (!~Vue.prototype.$path.indexOf(key)) {
      // Vue.prototype.$path.push(Vue.prototype.toPath + '_' + key)
      Vue.prototype.$path.push(key)
    }
    // return i18n.t(Vue.prototype.toPath + '_' + key)
    return i18n.t(key)
  }
  Vue.prototype.$t = t
  _vm = new Vue({
    el: '#app',
    router,
    store,
    i18n,
    data: {
      unlock: {
        my_username: null,
        my_password: null
      }
    },
    render: h => h(App)
  }).$mount('#app')
  var isLock = zzSessionStorage.getItem('isLock')
  var isOpen = false
  let count = 0;
  if (eval(process.env.VUE_APP_LOGIN_FOR_PERMISSION)) {
    setInterval(() => {
      var lang = zzSessionStorage.getItem('lang') ? zzSessionStorage.getItem('lang') : 'zh'
      if (WHITELIST.includes(_vm.$route.path)) {
        return
      }
      if (_vm.$store.state.user.userId !== zzSessionStorage.getItem('userId')) {
        window.location.href = `/login`
        zzSessionStorage.removeItem('lastWorkbench')
        _vm.$alert(lang === 'en' ? 'The same browser only allows one user account to be logged in at a time.' : '同一浏览器只允许同时登陆一个账户', {
          type: 'warning',
        })
      }
    }, 3000)
  }
  const waitOperate = (callback, second, callback2, second2) => {
    let x;
    let y;
    let timer;
    //监听键盘
    function countTime() {
      count++
      localStorage.setItem('count', count)
      if (count == parseInt(second2) || isLock === 'true') {
        callback2();
      }
      if (count >= second) {
        callback();
        count = 0;
        localStorage.removeItem('count')
        // clearInterval(timer);
      }
    }
    var blob = new Blob([document.querySelector('#worker').textContent]);
    var url = window.URL.createObjectURL(blob);
    var worker = new Worker(url);
    worker.onmessage = function (e, msg) {
      if (localStorage.getItem('count') === '0') {
        count = 0
        localStorage.removeItem('count')
      }
      countTime()
    }
    //监听鼠标
    document.onmousemove = function (event) {
      const x1 = event.clientX;
      const y1 = event.clientY;
      if (x != x1 || y != y1) {
        count = 0;
        localStorage.setItem('count', '0')
      }
      x = x1;
      y = y1;
    };
    document.onkeyup = function () {
      count = 0;
      localStorage.setItem('count', '0')
    };
  }
  const h = _vm.$createElement
  /* eslint-disable */
  waitOperate(eval(process.env.VUE_APP_LOGOUT_FOR_PERMISSION) ? () => {
    var lang = zzSessionStorage.getItem('lang') ? zzSessionStorage.getItem('lang') : 'zh'
    if (WHITELIST.includes(_vm.$route.path)) {
      count = 0;
      localStorage.setItem('count', '0')
      return
    }
    _vm.$store.dispatch('user/logout').then(res => {
      // window.location.href = `/login`
      try {
        if (_vm.$msgbox && _vm.$msgbox.close) {
          _vm.$msgbox.close();
        }
      } catch (err) {
        console.log(err)
      }
      isOpen = false
      isLock = null
      zzSessionStorage.removeItem('isLock')
      router.push("/login")
    }).then(() => {
      _vm.$alert(lang === 'zh' ? '由于您长时间未操作，为保护您的数据安全已强制将您下线，如果需要继续操作请重新登陆！' : 'No operation for a long time non-operation, you have been forced logout to protect data security. If continue to operate, please login again!', {
        type: 'warning',
      })
    })


  } : () => { }, process.env.VUE_APP_LOGOUT_FOR_TIME,
    eval(process.env.VUE_APP_LOCK_FOR_PERMISSION) ? () => {
      var lang = zzSessionStorage.getItem('lang') ? zzSessionStorage.getItem('lang') : 'zh'
      if (WHITELIST.includes(_vm.$route.path)) {
        count = 0;
        localStorage.setItem('count', '0')
        if (_vm.$route.path === '/login') {
          zzSessionStorage.removeItem('lastWorkbench')
          zzSessionStorage.removeItem('isLock')
          isLock = null
        }
        return
      }
      if (isOpen) {
        return
      }
      isOpen = true
      zzSessionStorage.setItem('isLock', 'true')
      _vm.$msgbox({
        title: lang === 'zh' ? '已锁定' : 'Locked',
        confirmButtonText: lang === 'zh' ? '解锁' : 'Unlock',
        showClose: false,
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            if (!_vm.unlock.my_username) {
              _vm.$message.warning(lang === 'zh' ? '请输入您的用户名解锁' : 'Please enter your user name to unlock.')
              return
            }
            if (!_vm.unlock.my_password) {
              _vm.$message.warning(lang === 'zh' ? '请输入您的密码解锁' : 'Please enter the correct password to unlock.')
              return
            }
            var my_username = zzSessionStorage.getItem('my_username')
            var my_password = zzSessionStorage.getItem('my_password')
            if (md5(_vm.unlock.my_password) === my_password && my_username === _vm.unlock.my_username) {
              _vm.$message.success(lang === 'zh' ? '解锁成功，请继续操作' : 'Unlocked successfully. Please continue operation.')
              _vm.unlock = {
                my_username: null,
                my_password: null
              }
              isOpen = false
              count = 0;
              isLock = null
              zzSessionStorage.removeItem('isLock')
              localStorage.setItem('count', '0')
              document.querySelector('#my_username').value = null
              document.querySelector('#my_password').value = null
              setTimeout(() => {
                done()
              }, 500)
            } else {
              _vm.$message.error(lang === 'zh' ? '请输入正确用户名密码' : 'Please enter the correct password.')
            }
          }
        },
        message: h('div', {}, [
          h('el-form', {
            props: { labelWidth: "80px" }
          }, [
            h('el-form-item', {
              props: { label: lang === 'zh' ? '用户名' : 'User ID' },
            }, [
              h('input', {
                props: {
                  value: _vm.unlock.my_username
                },
                attrs: {
                  id: 'my_username',
                  class: 'el-input__inner',
                  autocomplete: 'new-password'
                },
                on: {
                  change: (event) => {
                    _vm.unlock.my_username = event.target.value
                  },
                  input: (event) => {
                    _vm.unlock.my_username = event.target.value
                  }
                }
              })
            ]),
            h('el-form-item', {
              props: { label: lang === 'zh' ? '密码' : 'Password' },
            }, [
              h('input', {
                props: {
                  value: _vm.unlock.my_password
                },
                attrs: {
                  id: 'my_password',
                  class: 'el-input__inner',
                  type: 'password',
                  autocomplete: 'new-password'
                },
                on: {
                  change: (event) => {
                    _vm.unlock.my_password = event.target.value
                  },
                  input: (event) => {
                    _vm.unlock.my_password = event.target.value
                  }
                }
              })
            ])
          ])
        ])
      })
    } : () => { }, process.env.VUE_APP_LOCK_FOR_TIME)
}
VueInit()


