<template>
  <el-container class="container-width rounded">
    <el-header class="header">
      <div class="d-flex">
        <div class="" v-show="iconShow">
          <span class="header-return webkit-drag">
            <a @click="goURL">
            <i class="fas fa-angle-left" style="vertical-align: text-top;cursor: pointer"></i>
            </a>
          </span>
        </div>
        <div v-if="iconShow" class="p-2"><img src="../assets/img/logo.png" width="30" height="30"></div>
        <div class="pt-2 pb-2 pr-2" v-else ><img src="../assets/img/logo.png" width="30" height="30"></div>
        <div class="p-2"><h5 class="mt-1">纵横Z+ 造价工作平台 <span class="version-name">版本：V{{ version }}</span></h5></div>
        <div class="ml-auto p-2 pt-3 webkit-drag">
          <div class="d-flex flex-wrap">
            <div class="">
              <update-header ref="update" v-on:softwareDownload="relationDownload"></update-header>
            </div>
            <div class="">
              <download-header ref="download"></download-header>
            </div>
            <div class="mr-5">
              <usb-header ref="usb" v-on:softwareDownload="relationDownload"></usb-header>
            </div>
            <div class="">
              <div class="mr-3"><i class="fas fa-minus" @click="minimizeWindow"></i></div>
            </div>
            <div class="">
              <div class=""><i class="fas fa-times" @click="closeWindow"></i></div>
            </div>
          </div>
        </div>
      </div>
    </el-header>
    <el-main>
      <router-view v-on:softwareDownload="relationDownload" v-on:softwareUpdate="relationUpdate"></router-view>
    </el-main>
    <software-update></software-update>
  </el-container>
</template>

<script>
  import pkg from '../../../package.json'
  import mixin from './mixin'
  import SoftwareUpdate from './StartUpPage/SoftwareUpdate'
  import UsbHeader from './StartUpPage/UsbHeader'
  import DownloadHeader from './StartUpPage/DownloadHeader'
  import UpdateHeader from './StartUpPage/UpdateHeader'
  const electron = require('electron').remote
  const BrowserWindow = electron.BrowserWindow
  const fs = require('fs-extra')
  const path = require('path')

  export default {
    name: 'element-page',
    mixins: [mixin],
    components: { SoftwareUpdate, UsbHeader, DownloadHeader, UpdateHeader },
    data: () => ({
      version: pkg.version,
      iconShow: false
    }),
    watch: {
      // 如果路由有变化，会再次执行该方法
      '$route': 'iconshow'
    },
    created () {
      // 更改为启动前获取最新官网产品数据
      let softwarejson = path.join('data/sc_software.json')
      if (this.checkOnline()) {
        let version = fs.readJsonSync(softwarejson).startup_version
        let self = this
        this.$http({
          url: 'https://smartcost.com.cn/startup/sc_version.json?' + this.RndNum(),
          method: 'get',
          timeout: 5000
        }).then(function (response) {
          if (version !== response.data.startup_version) {
            // 加入随机数防止缓存
            console.log(response.data)
            console.log(version)
            self.$http.get('https://smartcost.com.cn/startup/sc_software.json?' + self.RndNum())
              .then(function (response2) {
                fs.writeJsonSync(softwarejson, response2.data)
                // 还要更新本地数据
                let scproductlist = response2.data.sc_product
                let productlist = self.$db.read().get('sc_productData').value()
                for (let i in productlist) {
                  let scproductinfo = scproductlist.find(function (item) {
                    return item.product_id === productlist[i].product_id
                  })
                  self.$db.read().get('sc_productData').updateById(productlist[i].id, scproductinfo).write()

                  let scdownlist = response2.data.sc_down
                  let downlist = self.$db.read().get('sc_exeData').value()
                  for (let j in downlist) {
                    let scdowninfo = scdownlist.find(function (item) {
                      return item.dwon_id === downlist[j].down_id
                    })
                    if (scdowninfo !== undefined) {
                      let setinfo = {
                        keyNumber: scdowninfo.key_number,
                        keytype: scdowninfo.keytype,
                        simpleName: scdowninfo.product_title,
                        versionName: scdowninfo.title
                      }
                      self.$db.read().get('sc_exeData').updateById(downlist[j].id, setinfo).write()
                    }
                  }
                }
              })
              .catch(function (error2) {
                throw error2
              })
          }
        }).catch(function () {
        })

        // 启动前检测数据库一些异常情况，恢复到上一个状态，暂时包含下载列，安装列, 删除标记delete的字段
        this.$db.read().get('sc_download').removeWhere({ delete: true }).write()
        let downinfo = this.$db.read().get('sc_download').find({ status: 5 }).value()
        if (downinfo !== undefined) {
          this.$db.read().get('sc_download').updateById(downinfo.id, { show: true, start: true, pause: false, resume: false }).write()
        } else {
          let downinfo2 = this.$db.read().get('sc_download').find({ status: 1 }).value()
          if (downinfo2 !== undefined) {
            this.$db.read().get('sc_download').updateById(downinfo2.id, { status: 5, show: true, start: true, pause: false, resume: false }).write()
          }
        }
        this.$db.read().get('sc_download').updateWhere({ status: 3 }, { status: 2 }).write()
      }
    },
    methods: {
      minimizeWindow () {
        const window = BrowserWindow.getFocusedWindow()
        window.minimize()
      },
      closeWindow () {
        const window = BrowserWindow.getFocusedWindow()
        window.close()
      },
      goURL () {
        if (this.$route.path === '/softwarelist') {
          let first = this.$db.read().get('sc_hadInstall.first').value()
          let url = first ? { path: '/firstopen' } : { path: this.$db.read().get('sc_hadInstall.url').value() }
          this.$router.push(url)
        } else {
          this.$router.push({ path: '/softwarelist' })
        }
      },
      iconshow () {
        let path = this.$route.path
        if (path === '/softwarelist' || path.indexOf('/softwaredetail') !== -1) {
          this.iconShow = true
        } else {
          this.iconShow = false
        }
      },
      relationDownload (downID) {
        console.log(downID)
        this.$refs.download.adddownload(downID)
      },
      relationUpdate () {
        this.$refs.update.fetchData()
      },
      checkOnline () {
        if (!navigator.onLine) {
          return false
        } else {
          return true
        }
      },
      // 产生随机数函数
      RndNum (n = 6) {
        let rnd = ''
        for (let i = 0; i < n; i++) {
          rnd += Math.floor(Math.random() * 10)
        }
        return rnd
      }
    }
  }
</script>