
import Vue from 'vue'
import DicomEvent from '@/views/trials/trials-panel/reading/dicoms/components/DicomEvent'
import 'normalize.css/normalize.css' // A modern alternative to CSS resets
// import { createVersionPolling } from "@/utils/version-polling.esm.js";
import ElementUI, { MessageBox } from 'element-ui'
import { getBasicDataAllSelect, getFrontInternationalizationList, getCurrentPublishInfo } from '@/api/dictionary/dictionary'
import { resetReadingRestTime } from '@/api/trials/reading'
// import 'element-ui/lib/theme-chalk/index.css'
import './assets/css/theme-blue/index.css' // 浅绿色主题
import './assets/css/iconfont/index.css' // 阿里巴巴图标库
// import locale from 'element-ui/lib/locale/lang/en' // lang i18n
import i18n from './lang'
import '@/styles/index.scss' // global css
import { getWebConfigInfo } from '@/api/admin'
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 htmlToPdf from './utils/htmlToPdf'
// Vue.use(htmlToPdf)
import permission from './utils/permission'
Vue.use(permission)

import { formatSize, guidToColor } from "./utils"
Vue.prototype.$FormatSize = formatSize
Vue.prototype.$GuidToColor = guidToColor

import Viewer from 'v-viewer'
import './assets/css/viewer.css'
Viewer.setDefaults({
  // navbar: true, //底部缩略图
  toolbar: {
    zoomIn: true,
    zoomOut: true,
    reset: true,
    prev: true,
    next: true,
    rotateLeft: true,
    rotateRight: true,
    flipHorizontal: true,
    flipVertical: true,
  }
})
Vue.use(Viewer)


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

// set ElementUI lang to EN
// Vue.use(ElementUI, { locale, size: 'medium' })
import upload from '@/components/element-ui/upload'
Vue.use(upload)
import Preview from '@/components/Preview/index'
Vue.use(Preview)
import Onlyoffice from '@/components/Preview_onlyoffice/index'
Vue.use(Onlyoffice)
import Video from '@/components/Preview_video/index'
Vue.use(Video)
import AGR from '@/components/AGR/index'
Vue.use(AGR)
import MFA from '@/components/MFA/index'
Vue.use(MFA)
import FB from '@/components/feedBack/index'
Vue.use(FB)
import FBT from '@/components/feedBackTable/index'
Vue.use(FBT)
import resize from '@/directive/resize/index'
// 表格自适应指令
Vue.use(resize)
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'
import { getTrialBodyPartList } from "@/api/trials/setting";
import global_ from './components/Global'
var _vm
getWebConfigInfo().then(res => {
  if (res.IsSuccess) {
    window.webConfig = JSON.parse(res.Result)
  }

  // 全局方法挂载
  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.$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}`
  }
  Vue.prototype.$validatePassword = (rule, value, callback) => {
    var lang = zzSessionStorage.getItem('lang') ? zzSessionStorage.getItem('lang') : 'zh'
    /* eslint-disable */
    var reg1 = eval(window.webConfig.VUE_APP_PASSWORD_FOR_PERMISSION) ? new RegExp(`${window.webConfig.VUE_APP_PASSWORD_FOR_REGULAR}`) : /.*/g; //密码必须是8位以上、必须含有字母、数字、特殊符号
    if (!reg1.test(value)) {
      callback(
        new Error(_vm.$t('env:regExp:formatPassword')))
    } else {
      callback();
    }
  }

  DictData.install()


  Vue.prototype.GLOBAL = global_
  Vue.config.productionTip = false
  Vue.prototype.$upload = () => {
    _vm.$forceUpdate()
  }
  Vue.prototype.$guid = () => {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  }
  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)
    })
  }


  async function VueInit() {
    var params
    var res
    if (~window.location.href.indexOf('/readingDicoms') || ~window.location.href.indexOf('/noneDicomReading') || ~window.location.href.indexOf('/criterionquestions') || ~window.location.href.indexOf('/petct') || ~window.location.href.indexOf('/fusion')) {
      params = $q('TrialReadingCriterionId')
      res = await getBasicDataAllSelect(params)
    } else if (~window.location.href.indexOf('/ecrfPreview')) {
      params = $q('SystemReadingCriterionId')
      res = await getBasicDataAllSelect(params, true)
    } else {
      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;
    Vue.prototype.$companyInfo = PublishInfo.OtherInfo;
    // 获取检查部位
    Vue.prototype.$getBodyPart = (id) => {
      return new Promise(async (resolve, reject) => {
        try {
          let params = {
            TrialId: id
          }
          let BodyPart = await getTrialBodyPartList(params)
          if (BodyPart.IsSuccess) {
            resolve(BodyPart.Result);
          } else {
            reject(BodyPart);
          }
        } catch (err) {
          reject(err)
        }
      })
    }
    i18n.mergeLocaleMessage('zh', zhMessages)
    i18n.mergeLocaleMessage('en', enMessages)
    Vue.use(ElementUI, {
      i18n: (key, value) => i18n.t(key, value),
      size: 'medium'
    })
    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, arr, key = 'label') {
      try {
        let data = arr || d;
        type = type || 'value';
        // code === 'YesOrNo' ? console.log(d) : ''
        return data[code].find(i => {
          return i[type] === v
        }) ? data[code].find(i => {
          return i[type] === v
        })[key] : ''
      } catch (e) {
      }
    }
    Vue.prototype.$company = (isShort = true) => {
      let companyName = null
      if (localStorage.getItem('CompanyInfo')) {
        let CompanyInfo = JSON.parse(localStorage.getItem('CompanyInfo'))
        let isZh = zzSessionStorage.getItem('lang') === 'zh' || _vm.$i18n.locale == 'zh'
        if (isZh) {
          companyName = isShort ? CompanyInfo.CompanyShortNameCN : CompanyInfo.CompanyNameCN
        } else {
          companyName = isShort ? CompanyInfo.CompanyShortName : CompanyInfo.CompanyName
        }
      }
      return companyName;
    }
    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.$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.$EventBus = new Vue()
    Vue.prototype.$path = []
    var t = function (key) {
      if (!~Vue.prototype.$path.indexOf(key)) {
        Vue.prototype.$path.push(key)
      }
      let text = i18n.t(key)
      if (Array.isArray(store.state.trials.config.TrialObjectNameList) && store.state.trials.config.TrialObjectNameList.length > 0) {
        let arr = JSON.parse(JSON.stringify(store.state.trials.config.TrialObjectNameList))
        arr.sort((a, b) => b.Name.length - a.Name.length)
        arr.forEach(item => {
          let test = new RegExp(item.Name, 'ig')
          text = text.replace(test, item.TrialName)
        })
      }
      let CompanyInfo = JSON.parse(localStorage.getItem('CompanyInfo'))
      if (CompanyInfo && CompanyInfo.SystemShortName && (text.toUpperCase() !== "CIRCLE")) {
        // 精准匹配独立单词 IRC
        // let test = new RegExp('IRC', 'ig')
        let test = new RegExp('\\bIRC\\b', 'ig')
        text = text.replace(test, CompanyInfo.SystemShortName)
      }
      // return i18n.t(key)
      return text;
    }
    Vue.prototype.$t = t
    _vm = new Vue({
      el: '#app',
      router,
      store,
      i18n,
      data: {
        unlock: {
          my_username: null,
          my_password: null,
          view: false
        }
      },
      render: h => h(App)
    })
    var isLock = zzSessionStorage.getItem('isLock')
    var isOpen = false
    let count = 0;
    console.log(window.webConfig.VUE_APP_LOGIN_FOR_PERMISSION, 'window.webConfig.VUE_APP_LOGIN_FOR_PERMISSION')
    if (eval(window.webConfig.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(_vm.$t("env:sso:tip"), {
            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')
        }
      }
      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 */
    // eval(window.webConfig.VUE_APP_LOGOUT_FOR_PERMISSION)
    // window.webConfig.VUE_APP_LOGOUT_FOR_TIME
    // eval(window.webConfig.VUE_APP_LOCK_FOR_PERMISSION)
    // window.webConfig.VUE_APP_LOCK_FOR_TIME
    // window.VUE_APP_COMPANY_NAME = window.webConfig.VUE_APP_COMPANY_NAME;
    waitOperate(eval(window.webConfig.VUE_APP_LOGOUT_FOR_PERMISSION) ? () => {
      var lang = zzSessionStorage.getItem('lang') ? zzSessionStorage.getItem('lang') : 'zh'
      if (_vm.$store.state.trials.unlock || 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)
        }
        _vm.$FB.close();
        _vm.$FBT.close();
        _vm.$MFA.close();
        isOpen = false
        isLock = null
        zzSessionStorage.removeItem('isLock')
        DicomEvent.$emit('isLock', false)
        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',
        // })
        _vm.$alert(_vm.$t("env:loginOut"), {
          type: 'warning',
        })
      })

    } : () => { }, window.webConfig.VUE_APP_LOGOUT_FOR_TIME,
      eval(window.webConfig.VUE_APP_LOCK_FOR_PERMISSION)
        ? () => {
          var lang = zzSessionStorage.getItem('lang') ? zzSessionStorage.getItem('lang') : 'zh'
          if (_vm.$store.state.trials.unlock || WHITELIST.includes(_vm.$route.path)) {
            count = 0;
            localStorage.setItem('count', '0')
            if (_vm.$route.path === '/login') {
              zzSessionStorage.removeItem('lastWorkbench')
              zzSessionStorage.removeItem('isLock')
              DicomEvent.$emit('isLock', false)
              isLock = null
            }
            return
          }
          if (isOpen) {
            return
          }
          isOpen = true
          zzSessionStorage.setItem('isLock', 'true')
          DicomEvent.$emit('isLock', true)
          _vm.$msgbox({
            title: _vm.$t("env:lock:msgBox:title"),
            confirmButtonText: _vm.$t("env:lock:msgBox:confirmButtonText"),
            showClose: false,
            beforeClose: (action, instance, done) => {
              if (action === 'confirm') {
                if (!_vm.unlock.my_username) {
                  _vm.$message.warning(_vm.$t("env:lock:msgBox:iupUser"))
                  return
                }
                if (!_vm.unlock.my_password) {
                  _vm.$message.warning(_vm.$t("env:lock:msgBox:inpPassword"))
                  return
                }
                var my_username = zzSessionStorage.getItem('my_username')
                var my_password = zzSessionStorage.getItem('my_password')
                let my_userid = zzSessionStorage.getItem('userId')
                let my_EMail = zzSessionStorage.getItem('my_EMail') || ''
                if (md5(_vm.unlock.my_password) === my_password && (my_username === _vm.unlock.my_username || my_EMail.toUpperCase() === _vm.unlock.my_username.toUpperCase())) {
                  resetReadingRestTime().then(() => {
                  })
                  const closeLock = (_vm) => {
                    _vm.$message.success(_vm.$t("env:lock:msgBox:lockSuccess"))
                    _vm.unlock = {
                      my_username: null,
                      my_password: null,
                      view: false
                    }
                    isOpen = false
                    count = 0;
                    isLock = null
                    zzSessionStorage.removeItem('isLock')
                    DicomEvent.$emit('isLock', false)
                    localStorage.setItem('count', '0')
                    document.querySelector('#my_username').value = null
                    document.querySelector('#my_password').value = null
                    setTimeout(() => {
                      done()
                    }, 500)
                  }
                  // if (eval(window.webConfig.VUE_APP_LOCK_FOR_PERMISSION_MFA)) {
                  //   sendMFAEmail({ UserId: my_userid, MfaType: 1 }).then((res) => {
                  //     done();
                  //     Vue.prototype.$MFA({
                  //       status: "lock",
                  //       UserId: my_userid,
                  //       EMail: res.Result,
                  //       username: my_username,
                  //       callBack: () => {
                  //         closeLock(_vm)
                  //       },
                  //     })
                  //   })
                  // } else {
                  closeLock(_vm)
                  // }

                } else {
                  // console.log(111)
                  _vm.$message.error(_vm.$t('env:lock:msgBox:userFail'))
                }
              }
            },
            message: h('div', {}, [
              h('el-form', {
                props: { labelWidth: "80px" }
              }, [
                h('el-form-item', {
                  props: { label: _vm.$t("env:lock:msgBox:form:username") },
                }, [
                  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: _vm.$t("env:lock:msgBox:form:Password") },
                  attrs: {
                    style: "position: relative;"
                  }
                }, [
                  h('input', {
                    props: {
                      value: _vm.unlock.my_password
                    },
                    ref: "unlock_my_password_input",
                    attrs: {
                      id: 'my_password',
                      class: 'el-input__inner',
                      type: _vm.unlock.view ? 'text' : 'password',
                      autocomplete: 'new-password',
                      style: "padding-right:25px"
                    },
                    on: {
                      change: (event) => {
                        _vm.unlock.my_password = event.target.value
                      },
                      input: (event) => {
                        _vm.unlock.my_password = event.target.value
                      }
                    }
                  }),
                  h('i', {
                    attrs: {
                      id: 'my_password_view',
                      class: "el-icon-view",
                      style: "cursor: pointer;position: absolute;top:35%;right:10px"
                    },
                    on: {
                      click: (event) => {
                        _vm.unlock.view = !_vm.unlock.view
                        if (_vm.unlock.view) {
                          _vm.$refs['unlock_my_password_input'].type = "text"
                        } else {
                          _vm.$refs['unlock_my_password_input'].type = "password"
                        }
                      },
                    }
                  }),
                ])
              ])
            ])
          })
        } : () => { },
      window.webConfig.VUE_APP_LOCK_FOR_TIME
    )
  }
  VueInit()
})

// createVersionPolling({
//   appETagKey: "__APP_ETAG__",
//   pollingInterval: 5 * 60 * 1000, // 单位为毫秒
//   silent: window.webConfig.NODE_ENV === false, // 开发环境下不检测
//   onUpdate: (self) => {
//     // 当检测到有新版本时，执行的回调函数，可以在这里提示用户刷新页面
//     const result = confirm(_vm.$t("versionPolling:tip"));
//     if (result) {
//       self.onRefresh();
//     } else {
//       self.onCancel();
//     }
//     // 强制更新可以用alert
//     // alert('有新版本，请刷新页面');
//   },
// });


export default _vm