<?php

namespace app\common\logic;

use app\common\api\Upgrade as apiUpgrade;
use app\common\model\Config as mConfig;
use app\common\model\Upgrade as mUpgrade;

class Upgrade extends Base
{

    public function check()
    {
        $result = ['code' => 200, 'msg' => '', 'data' => []];
        $apiUpgrade = new apiUpgrade();
        $data = $apiUpgrade -> check();
        if ($data !== false) {
            $config = new mConfig();
            $version_code = $config -> where('name', '=', 'version_code') -> value('value');
            if ($version_code == $data['version_code']) {
                $result['code'] = 8002;
                $result['msg'] = $this -> errorCode(8002);
                return $result;
            }
            if ($version_code < $data['version_min_code']) {
                $result['code'] = 8003;
                $result['msg'] = $this -> errorCode(8003);
                return $result;
            }
            //插入版本更新记录
            $mUpgrade = new mUpgrade();
            $where[] = ['version_code', '=', $data['version_code']];
            $isExist = $mUpgrade -> where($where) -> count();
            if (empty($isExist)) {
                $versionData['version_name'] = $data['version_name'];
                $versionData['version_code'] = $data['version_code'];
                $versionData['content'] = json_encode($data['content'], JSON_UNESCAPED_UNICODE);
                $mUpgrade -> isUpdate(false) -> allowField(true) -> save($versionData);
            }
            $result['data']['version_name'] = $data['version_name'];
            $result['data']['version_code'] = $data['version_code'];
            $result['data']['down_url'] = $data['down_url'];
            $result['data']['content'] = $data['content'];
            return $result;
        }
        $result['code'] = 8001;
        $result['msg'] = $this -> errorCode(8001);
        return $result;
    }


    /**
     * @系统更新记录
     *
     * @author: zsl
     * @since: 2019/6/20 17:52
     */
    public function lists()
    {
        $result = ['code' => 200, 'msg' => '请求成功', 'data' => []];
        $mUpgrade = new mUpgrade();
        $field = 'id,version_name,version_code,content,update_time,status';
        $lists = $mUpgrade -> field($field) -> order('create_time desc') -> select();
        if (!empty($lists)) {
            foreach ($lists as &$v) {
                $v['content'] = json_decode($v['content']) ? json_decode($v['content']) : [];
            }
            unset($v);
            $result['data'] = $lists;
        }
        return $result;
    }


    public function currentVersion()
    {
        $result = ['code' => 200, 'msg' => '请求成功', 'data' => []];
        $mConfig = new mConfig();
        $where[] = ['name', '=', 'version_name'];
        $versionName = $mConfig -> where('name', '=', 'version_name') -> value('value');
        $versionCode = $mConfig -> where('name', '=', 'version_code') -> value('value');
        $result['data']['version_name'] = $versionName;
        $result['data']['version_code'] = $versionCode;
        return $result;
    }


    public function begin()
    {
        $result = ['code' => '200', 'msg' => '开始下载更新包...', 'data' => []];
        $data = $this -> check();
        if ($data['code'] != 200) {
            return $data;
        }
        $result['data']['down_url'] = $data['data']['down_url'];
        $result['data']['version_code'] = $data['data']['version_code'];
        $result['url'] = url('admin/upgrade/setp01');
        return $result;
    }


    /**
     * @步骤一 : 下载更新包
     *
     * @author: zsl
     * @since: 2021/3/25 16:25
     */
    public function setp01($param)
    {
        $result = ['code' => '200', 'msg' => '更新包下载完成...<br/>开始解压更新包...', 'data' => []];
        if (empty($param['down_url'])) {
            $result['code'] = 8004;
            $result['msg'] = $this -> errorCode(8004);
            return $result;
        }
        if (empty($param['version_code'])) {
            $result['code'] = 8005;
            $result['msg'] = $this -> errorCode(8005);
            return $result;
        }
        try {
            $content = file_get_contents($param['down_url']);
            $file_name = $param['version_code'] . '.zip';
            $root_path = substr($_SERVER['DOCUMENT_ROOT'], 0, strrpos(rtrim($_SERVER['DOCUMENT_ROOT'], '/'), '/'));
            $save_path = '/data/upgrade/';
            if (!file_exists($root_path . $save_path)) {
                mkdir($root_path . $save_path, 0777, true);
            }
            if (!file_put_contents($root_path . $save_path . $file_name, $content)) {
                $result['code'] = 8006;
                $result['msg'] = $this -> errorCode(8006);
                return $result;
            }
        } catch (\Exception $e) {
            $result['code'] = 8006;
            $result['msg'] = $this -> errorCode(8006);
            return $result;
        }
        $result['data']['file_name'] = $file_name;
        $result['url'] = url('admin/upgrade/setp02');
        return $result;
    }


    /**
     * @解压更新包
     *
     * @author: zsl
     * @since: 2021/3/25 16:26
     */
    public function setp02($param)
    {
        $result = ['code' => '200', 'msg' => '更新包解压完成...<br/>开始执行安装程序...', 'data' => []];
        if (empty($param['file_name'])) {
            $result['code'] = 8007;
            $result['msg'] = $this -> errorCode(8007);
            return $result;
        }
        try {
            $zip = new \ZipArchive();
            $root_path = substr($_SERVER['DOCUMENT_ROOT'], 0, strrpos(rtrim($_SERVER['DOCUMENT_ROOT'], '/'), '/'));
            $save_path = '/data/upgrade/';
            if ($zip -> open($root_path . $save_path . $param['file_name']) === true) {
                $unzip_path = '/application/upgrade/';
                $status = $zip -> extractTo($root_path . $unzip_path);
                $zip -> close();
                if (!$status) {
                    $result['code'] = 8008;
                    $result['msg'] = $this -> errorCode(8008);
                    return $result;
                }
            }
            $result['url'] = url('upgrade/index/step01');
        } catch (\Exception $e) {
            $result['code'] = 8008;
            $result['msg'] = $this -> errorCode(8008);
        }
        return $result;
    }


    private function errorCode($code)
    {
        $errorCode = [
                8001 => '',
                8002 => '当前版本为最新版本',
                8003 => '当前版本不支持自动更新，请手动更新或联系售后人员',
                8004 => '下载地址错误',
                8005 => '版本号错误',
                8006 => '更新包下载失败',
                8007 => '更新包名错误',
                8008 => '解压更新包失败',
        ];
        return empty($errorCode[$code]) ? '系统繁忙,请稍候再试' : $errorCode[$code];
    }

}