import Vue from 'vue'
import axios from 'axios'
import NP from 'number-precision'

import ElementUI from 'element-ui'
import '@/assets/css/index.css'
import '@/styles/element-ui.scss'
/*
import '@/styles/index.scss'
*/
import '@/styles/theme.scss'

import elementUIVerify from '@/utils/elementUIVerify'

import ECharts from 'vue-echarts/components/ECharts.vue'
import 'echarts/lib/chart/bar'
import 'echarts/lib/chart/pie'
import 'echarts/lib/chart/line'
import 'echarts/lib/component/tooltip'
import 'echarts/lib/component/toolbox'
import 'echarts/lib/component/polar'
import 'echarts/lib/component/geo'
import 'echarts/lib/component/legend'
import 'echarts/lib/component/title'
import 'echarts/lib/component/visualMap'
import 'echarts/lib/component/dataset'
import 'echarts/lib/component/axis'

import VueQriously from 'vue-qriously'
import Print from '@/utils/print'
import Clipboard from 'v-clipboard'
import '@/icons' // icon
import App from './App'
import router from './router'
import store from './store'
import { localStore } from '@/utils'
import * as filters from './filters' // global filters
import '@/permission' // permission control

import printPage from '@/utils/printPage'
import VueScrollTo from 'vue-scrollto'
import GlobalComponents from '@/components/GlobalComponents'
// string 原型方法修改
import '@/utils/posUtils/string'
import VueKonva from 'vue-konva'
import agencyName from '@/utils/agencyName'

// 红色雷锋侧边栏
if (process.env.VUE_APP_PROJECT === 'leifengjinianguan') {
  import('@/styles/project/leifeng/index.scss')
} else {
  import('@/styles/index.scss')
}

Vue.use(VueKonva)

// import * as faceapi from 'face-api.js'

faceapi.env.monkeyPatch({
  Canvas: HTMLCanvasElement,
  Image: HTMLImageElement,
  ImageData: ImageData,
  Video: HTMLVideoElement,
  createCanvasElement: () => document.createElement('canvas'),
  createImageElement: () => document.createElement('img')
})

Vue.use(GlobalComponents)

Vue.use(VueScrollTo)

Vue.http = Vue.prototype.$http = axios
Vue.NP = Vue.prototype.$NP = NP
Vue.config.productionTip = false

Vue.use(ElementUI, { size: 'small' })
Vue.use(elementUIVerify)
Vue.use(Clipboard)
Vue.component('v-chart', ECharts)

const log = require('electron-log')
log.transports.console.level = 'silly'
log.transports.file.maxSize = 15 * 1024 * 1024

// 避免在配置页无法打开配置文件
localStore.set('init', true)

console.log(localStore.get('appName'), process.env.VUE_APP_PROJECT_NAME)

document.title = localStore.get('appName') || process.env.VUE_APP_PROJECT_NAME

// 本地存储
Vue.localStore = Vue.prototype.$localStore = localStore
// 日志收集
Vue.log = Vue.prototype.$log = log

// 与旧版本本地存储做兼容，防止数据丢失
setLocalStoreFromlocalStorage()

// 打印
Vue.use(Print)
// 二维码
Vue.use(VueQriously)

// Vue.component('v-chart', ECharts)

// register global utility filters.
Object.keys(filters).forEach(key => {
  Vue.filter(key, filters[key])
})

// 是否存在定制logo
const fs = require('fs')
const userDataFolder = require('electron').remote.app.getPath('userData')
const logoPath = require('path').join(userDataFolder, 'logo.png')

fs.stat(logoPath, (err, stats) => {
  if (err) {
    console.log(err)
    return
  }
  store.commit('SET_CUSTOM_LOGO', 'file://' + logoPath)
})

Vue.mixin({
  data () {
    return {
      colorPalette: [
        '#74a275', '#3b5069', '#b39a57', '#2987db', '#f49e43',
        '#785012', '#805ebe', '#204e55', '#c0c21f', '#9f3d3f', '#cf7d39', '#d7c0c3', '#06315b', '#97b3a1', '#f8e71c', '#d4578a', '#72ce84', '#e93d35'
      ]
    }
  },
  computed: {
    // 售票电脑ip、mac信息
    sellerDevice () {
      return this.$store.state.app.sellerDevice
    },
    pagePermission () {
      return this.$route.meta.permissionList
    },
    printType () {
      return this.$store.state.app.localConfig && this.$store.state.app.localConfig.printType
    },
    transformUrl () {
      const configs = this.$store.state.app.systemConfig || []
      const item = configs.find(i => i.configKey === 'reportfile_url_serverip_replace') || {}
      const value = item?.configValue
      console.log('reportfile_url_serverip_replace', value, typeof value)
      return value === '1'
    }
  },
  methods: {
    agencyName,
    checkPermission (type) {
      return this.pagePermission.indexOf(type) !== -1 || this.pagePermission.indexOf('all') !== -1
    },
    goToDownload () {
      this.$confirm('报表已导出，是否跳转到报表下载页？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$router.push('/queryReport/reportList')
      }).catch(() => {
      })
    },
    // 下载excel
    downloadFile (url) {
      return axios.get(url, {
        responseType: 'arraybuffer'
      }).then(res => {
        const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
        const link = document.createElement('a')
        link.href = window.URL.createObjectURL(blob)
        link.download = url.split('/').pop()
        link.click()
      }).catch(e => {
        this.$message.error(`${url}下载失败：${e}`)
      })
    },
    downloadExport (data) {
      if (!data.downloadUrl) {
        this.$message.error('暂无下载地址')
        return
      }

      let url = ''

      if (this.transformUrl) {
        const urlObj = new URL(data.downloadUrl)
        const localObj = new URL(this.$localStore.get('serverUrl'))
        // 主机地址一样，则不进行替换
        if (urlObj.hostname === localObj.hostname) {
          url = data.downloadUrl
        } else {
          urlObj.hostname = localObj.hostname
          urlObj.protocol = localObj.protocol
          urlObj.port = localObj.port || '80'

          url = urlObj.href
        }
      } else {
        url = data.downloadUrl
      }

      console.log('下载地址', url)
      this.downloadFile(url)
    },
    printPage
  }
})

const { ipcRenderer } = require('electron')
ipcRenderer.removeAllListeners('message')
ipcRenderer.on('message', (event, { message, data }) => {
  switch (message) {
    case 'downloadProgress':
      // console.log('下载进度', data)
      store.dispatch('updateApp', {
        status: 0,
        process: Math.floor(data.percent)
      })
      break
    case 'update-available':
      console.log('有可用更新')
      break
    case 'update-not-available':
      console.log('无可用更新')
      store.dispatch('updateApp', {
        status: 1,
        process: 0
      })
      break
    case 'isUpdateNow':
      store.dispatch('updateApp', {
        status: 2,
        process: 0
      })
      break
    default:
      // console.log(message, data)
      break
  }
})

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

// 兼容处理
function setLocalStoreFromlocalStorage () {
  let { serverUrl, updateUrl, defaultPrinter, defaultTemplate, autoPrint } = localStorage
  serverUrl && localStore.set('serverUrl', serverUrl)
  updateUrl && localStore.set('updateUrl', updateUrl)
  defaultPrinter && localStore.set('defaultPrinter', defaultPrinter)
  defaultTemplate && localStore.set('defaultTemplate', defaultTemplate - 0)
  autoPrint && localStore.set('autoPrint', !!(autoPrint - 0))

  // 清除原纪录，切换到config.json来保存数据
  localStorage.clear()
}
