import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
import axios from 'axios'
import IndexRoot from './js/IndexRoot.js'
import writeLog from './js/writeLog.js'
import ViewUIPlus from 'view-ui-plus'
import 'leaflet/dist/leaflet.css'
import 'view-ui-plus/dist/styles/viewuiplus.css'
import './assets/main.css'

window.state = null

/**
 * usage:
 * let x = new Date()
 * x.format('yyyy-MM-dd hh:mm:ss')
 *
 * @method format
 *
 * @param  {[type]} format [description]
 *
 * @return {[type]}        [description]
 */
Date.prototype.format = function (format) { // eslint-disable-line
    let o = {
      'M+': this.getMonth() + 1, // month
      'd+': this.getDate(), // day
      'h+': this.getHours(), // hour
      'm+': this.getMinutes(), // minute
      's+': this.getSeconds(), // second
      'q+': Math.floor((this.getMonth() + 3) / 3), // quarter
      'S': this.getMilliseconds() // millisecond
    }
    if (/(y+)/.test(format)) {
      format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    for (let k in o) {
      if (new RegExp('(' + k + ')').test(format)) {
        format = format.replace(RegExp.$1,
          RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
      }
    }
    return format
}

const pinia = createPinia()
const app = createApp(App)

let $indexRoot =  new IndexRoot()
app.config.globalProperties.$indexRoot = $indexRoot

window.onerror=(message, source, lineno, colno, error)=>{
  var data = {
    message: message,
    source: source,
    lineno: lineno,
    colno: colno,
    error: error
  };
  writeLog('ERROR', JSON.stringify(data))
}

app.use(router)
    .use(ViewUIPlus)
    .use(pinia)

const config_url = process.env.NODE_ENV === 'development' ? '../config.json' : '/config.json'
function getSysConfig() {
    return new Promise((resolve, reject) => {
    axios.get(config_url).then((result) => {
        let config = result.data
        resolve(config)
    }).catch((error) => {
        console.log(error)
        reject()
    })
    })
}

async function init() {
    const {SERVICE_IP, MAP_CENTER,LOG_SERVE_IP} = await getSysConfig()
    document.location.serviceIP = SERVICE_IP
    document.location.mapCenter = MAP_CENTER
    document.location.logServe = LOG_SERVE_IP
}

init().then(() => app.mount('#app'))
