<template>
    <div>
		<div :style="{background: '#fafafa', padding: '5px 20px', lineHeight: '34px'}" class="footer-between">
		    <div>
		        <a href="https://www.xingyousoft.com"><span class="footer-menu"><i class="iconfont iconx-wangzhi"></i>官网</span></a>
				<el-popover placement="bottom" width="200" trigger="click" popper-class="wei-dialog">
				    <a slot="reference"><span class="footer-menu"><i class="iconfont iconx-qiyeweixin"></i>客服</span></a>
					<div class="api">
						<img src="../assets/image/qrcode.png" style="width: 100%;"/>
					</div>
				</el-popover>
		    </div>
			
			<div>
				<span v-if="linkList.length > 0" class="footer-menu" style="padding: 0;cursor:default;"><i class="iconfont iconx-lianjie"></i>应用推荐：</span>
				<a v-for="(item, key) in linkList" :key="key" @click="openUrl(item.url)"><span class="footer-menu">{{item.title}}</span></a>
			</div>
			
		    <div style="cursor:pointer;position: relative;font-size: 13px;" @click="updateSoft()">
		        <span>
					<el-badge is-dot v-if="isUpdate">
						<i class="el-icon-refresh-right" style="font-size: 20px;"></i>
					</el-badge>
					版本：v{{softInfo.version}}
				</span>
		    </div>
		</div>
        <!-- 下载进度 -->
		<el-dialog title="软件更新" :visible.sync="isShow" width="400px" :show-close="false">
			<div style="text-align: center;">
				<div class="demo-Circle-custom">
					文件大小：<i>{{$utils.handleSize(Number(softInfo.totalSize))}}</i>
					<p>下载进度</p>
				</div>
				<el-progress type="circle" :stroke-width="10" :percentage="Number(softInfo.percent)" :width="220"></el-progress>
				<div>
					<el-button type="primary" style="margin-top: 30px;" @click="isShow = false">后台下载</el-button>
				</div>
			</div>
		</el-dialog>

        <!-- 下载完成 -->
		<el-dialog title="下载完成,是否退出并安装" :visible.sync="isFinished" width="400px" :close-on-click-modal="false">
			<p>文件下载位置{{softdownloadDir}}</p>
			<span slot="footer" class="dialog-footer">
				<el-button @click="isFinished = false">取 消</el-button>
				<el-button type="primary" @click="execSoft()">确 定</el-button>
			</span>
		</el-dialog>
    </div>
</template>

<script>
	import os from 'os'
	import fs from 'fs'
	import request from 'request'
	import { ipcRenderer } from 'electron'
	import pjson from '/package.json'
    export default {
        name: "updateRef",
		data(){
			return {
				softInfo: {
					version: pjson.version,
					name: pjson.softInfo.downloadName,
					percent: 0,
					downloadedSize: 0,
					totalSize: 0
				},
				softdownloadDir: os.userInfo().homedir+"\\Downloads", // 下载路径
				isShow: this.showDowload,
				isFinished: this.dowloadFinish,
				isUpdate: false,
				
				linkList: [], // 友情链接
				
				softdownloadPath: '',
			}
		},
        props: {
            showDowload: {
                type: Boolean,
                required: true,
                default: false
            },
			dowloadFinish: {
			    type: Boolean,
			    required: true,
			    default: false
			},
        },
		mounted() {
			
			// 友情连接
			this.$http.post(this.$api.target + '/api/api/m_position_list', { group_id: pjson.softInfo.linkId }).then((response) => {
				if (!response.data.error) {
				   this.linkList = response.data.result.list;
				}
			})
		},
		methods: {
			// 打开浏览器
			openUrl(url){
				const { shell } = require('electron');
				shell.openExternal(url);
			},
			// 检查更新
			updateSoft(flag){ // flag 软件打开时检测是否更新，true则静默不弹出最新版本提示
				if(Number(this.softInfo.percent) > 0){
					this.isShow = true;
				}else{
					this.$http.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
					this.$http.get(pjson.softInfo.downloadPrefix + '/' + pjson.name + "/version.json?"+Math.random()).then((response) => {
						let getResult = response.data || {};
						let currentVersion = this.softInfo.version.split('.');
						let updateVersion = getResult.v.split('.');
						currentVersion.map((item, index) => {
							currentVersion[index] = Number(item);
						})
						updateVersion.map((item, index) => {
							updateVersion[index] = Number(item);
						})
						let result1 = updateVersion[0] > currentVersion[0];
						let result2 = (updateVersion[0] == currentVersion[0]) && (updateVersion[1] > currentVersion[1]);
						let result3 = (updateVersion[0] == currentVersion[0]) && (updateVersion[1] == currentVersion[1]) && (updateVersion[2] > currentVersion[2]);
						let result4 = (updateVersion[0] == currentVersion[0]) && (updateVersion[1] == currentVersion[1]) && (updateVersion[2] == currentVersion[2]) && (updateVersion[3] > currentVersion[3]);
						if(result1 || result2 || result3 || result4){
							this.isUpdate = true;
							let updateContent = getResult.c || '';
							let html = '<div>检测到有新版本v'+getResult.v+'，是否更新最新版本？</div><div>'+updateContent+'</div>';
							this.$confirm(html, '应用更新', {
								dangerouslyUseHTMLString: true,
								confirmButtonText: '立即更新',
								type: 'warning'
							}).then(() => {
								this.softdownloadPath = this.softdownloadDir+'/'+ pjson.name + '_XY.exe';
								this.downloadFile(pjson.softInfo.downloadPrefix + '/' + pjson.name + '/' + pjson.name + "_XY.exe", this.softdownloadPath);
							}).catch(() => {
								       
							});
						}else{
							this.isUpdate = false;
							if(!flag){
								this.$message({message: '当前已经是最新版本',type: 'success', center: true});
							}
						}
					}).catch(function(error){
						console.log(error);
					});
				}
			},
			// 下载文件
			downloadFile(file_url, targetPath){
				let _this = this;
				let received_bytes = 0;
				let total_bytes = 0;
				let isError = false;
				
				let req = request({
				    method: 'GET', uri: file_url, strictSSL: false
				});
				let out = fs.createWriteStream(targetPath);
				req.pipe(out);
							
				req.on('response', function ( data ) {
					total_bytes = parseInt(data.headers['content-length']);
					const status = data.statusCode
					if (status < 200 || status >= 300) {
						_this.$message({showClose: true,message: '网络异常，请稍后重试！',type: 'warning'});
						isError = true;
					}else if(isNaN(total_bytes)){
						_this.$message({showClose: true,message: '网络异常，请稍后重试！',type: 'warning'});
						isError = true;
					}else{
						_this.isShow = true;
						isError = false;
					}
				});
							
				req.on('data', function(chunk) {
				    received_bytes += chunk.length;
					_this.showProgress(received_bytes, total_bytes);
				});
				
				
				req.on('end', function() {
					if(!isError){
						_this.softInfo.percent = 100;
						setTimeout(()=>{
							_this.isFinished = true;
							_this.isShow = false;
							_this.softInfo.percent = 0;
						}, 1000)
					}else{
						_this.isFinished = false;
						_this.softInfo.percent = 0;
						if(fs.existsSync(targetPath)){
							fs.unlinkSync(targetPath);
						}
					}
				});
			},
			// 显示进度
			showProgress(received, total){
				let percentage = (received * 100) / total;
				let temp = percentage - this.softInfo.percent;
				if(Number(temp) > 1.5){
					this.softInfo.percent = Number(percentage).toFixed(2);
				}
				this.softInfo.downloadedSize = Number(received);
				this.softInfo.totalSize = Number(total);
				// console.log(percentage + "% | " + received + " bytes out of " + total + " bytes.");
			},
			// 安装
		    execSoft(){
		    	const exec = require('child_process').exec;
				exec(this.softdownloadPath, (err, data) => {
					if (err) {
						throw err; 
					} else { // 完成
						this.isFinished = false;
					}
				});
		    }
		},
    }
</script>


<style>
.wei-dialog{
	padding: 0 !important;
}
</style>