<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\Upgrade;
use think\Db;
use think\Session;
use think\Cache;
/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Platform extends Backend
{

    /**
     * Platform模型对象
     * @var \app\common\model\Platform
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Platform;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
        
        $admin = Db::name("admin")->where(['id'=>$this->auth->id])->find();
        $this->assign("admin",$admin);
        $this->assignconfig('admin', $admin);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        $id = $this->param('id/d');
        
        
        $url = "/dashboard";
        if($id <= 0){
            $id = Db::name("platform")->order("id  asc")->value("id");
        }

        $uid = $this->auth->id;
        $account = Db::name("admin")->where(['id'=>$uid])->find();
        if($account['uniacid'] > 0){
            $id = $account['uniacid'];
            $role = Db::name("bbfx_role")->where(['id'=>$account['role_id']])->find();
            if(!empty($role)){
                $auth_content = iunserializer($role['auth_content']);
                
                $user_auths = Db::name("bbfx_auth")->where(['id'=>['in',$auth_content]])->field(['id','name','rule','pid'])->order("id asc")->select();
                
                foreach ($user_auths as $key => $val){
                    if($val['type'] == 0){
                        $url = $val['rule'];
                    }
                    else{
                        $url = Db::name("bbfx_auth")->where(['id'=>$val['pid']])->value("rule");
                    }
                    break;
                }
            }
        }
        Session::set("uniacid",$id);
        $this->redirect(request()->domain()."/admin/#{$url}?i=".$id);
        
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','name','type','status','createtime']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        
        $res = Upgrade::getVersion();
        $is_upgrade = 0;
        if(!empty($res)){
            $is_upgrade = $res['is_upgrade'];
            Db::name("platform")->where("id",1)->update(['createtime'=>$res['site']['createtime']]);
            $this->assign("expirestime",$res['expirestime']);
        }
        $version = Db::name("bbfx")->find();
        $this->assign("is_upgrade",$is_upgrade);
        $this->assign("version",$version);
        
        exit();
        
        return $this->view->fetch();
    }

    public function updateSuccessful(){
        Upgrade::updateSuccessful();
        $this->success("操作成功");
    }

    public function xufei(){
        
        
        if ($this->request->isAjax()) {
            $code = $this->param("code/s");
            if(empty($code)){
                $this->error("请输入授权码");
            }
            
            $res = Upgrade::xufei($code);
            
            if($res['code'] != 1){
                $this->error($res['message']);
            }
            $this->success("操作成功");
        }
        
         
        $res = Upgrade::getVersion();
        
        if(!empty($res)){
            $this->assign("expirestime",$res['expirestime']);
        }
        else{
            $this->assign("expirestime","");
        }
        $version_name = Db::name("bbfx")->value("version_name");
        
        $buy_qrcode = "";
        $result = ihttp_get("https://www.baibianfenxiao.com/api/buy/qrcode");
        $result = toJsonde($result['content']);
        if($result['code'] == 1){
            $buy_qrcode = $result['data'];
        } 
        $this->assign("status_text",$res['site']['status_text']);
        $this->assign("buy_qrcode",$buy_qrcode);
        $this->assign("version_name",$version_name);
        return $this->view->fetch();
    }
    
    public function mingxie(){
        $content = "";
        $result = ihttp_get("https://www.baibianfenxiao.com/api/article/mingxie");
        $result = toJsonde($result['content']);
        if($result['code'] == 1){
            $content = htmlspecialchars_decode($result['data']);
        }
        
        $this->assign("content",$content);
        
        return $this->view->fetch();
    }
    
    public function renewlog(){
        $list = Upgrade::renewlog();
        // print_r($list);die;
        
        $this->assign("list",$list);
        
        return $this->view->fetch();
    }
    
    public function update(){
        Cache::set("is_download",false);
        $res = Upgrade::execute();
        if($res){
            __success("更新成功");
        }
        else{
            __error("更新失败");
        }
    }
    
    public function updateProgress(){
        $res = Upgrade::updateProgress();
        if($res['code'] == 1){
            __success("操作成功",$res['data']);
        }
        else{
            __error("操作失败");
        }
    }
    
    public function updatesql(){
        Upgrade::updateSql();
        __success("更新成功");
    }

    public function initupload(){
        unlink(ROOT_PATH."download/miniprogram-ci.zip");
        $filepath = download_file('https://baibian1.oss-cn-beijing.aliyuncs.com/miniprogram-ci.zip', ROOT_PATH."download/",'miniprogram-ci.zip');
        if(empty($filepath)){
            __error("加载失败");
        }

        $zip = new \ZipArchive();
        if(empty($zip->open($filepath))){
            unlink($filepath);
            __error("解压组件失败");
        }

        del_Dir(ROOT_PATH."extend/miniprogram-ci");
        
        $zip->extractTo(ROOT_PATH."extend/");
        $zip->close();
        
        unlink($filepath);

        __success("加载成功，请重新点击上传代码！");
    }

    public function uploadWxapp()
    {
        // 

        if (!file_exists('../extend/miniprogram-ci/node_modules/miniprogram-ci')) {
            __error(-2,"您还未加载上传小程序代码组件，是否加载？");
        }

        $result = $this->initWxappVersion();

        $platform = $result['platform'];
        $version_name = $result['version_name'];
         
        try {
            //校验是否已安装miniprogram-ci工具
            

            if (!function_exists('exec')) { 
                throw new \Exception('exec函数已被禁用，请先解除禁用。');
            }

            if(!file_exists(ROOT_PATH.'public'.$platform['wxapp_upload_privateKey'])){
                throw new \Exception('请先配置小程序代码上传密钥。');
            }

            exec('node -v', $output, $return_var);
            if ($return_var === 0) {
                // echo "Node.js is installed. Version: " . $output[0];
                
            } else {
                // echo "Node.js is not installed.";
                throw new \Exception("Node.js尚未安装。");
            }

            $privateKeyPath = "../public".$platform['wxapp_upload_privateKey'];
             
            //上传小程序代码
            $data = [
                'appid' => $platform['wxapp_AppId'],
                'privateKeyPath'=>$privateKeyPath,
                'version' => $version_name,
                'desc' => '',
            ];
            $json_data = json_encode($data);
            $command = 'node ../extend/miniprogram-ci/upload.js '.escapeshellarg($json_data).' 2>&1';
            $output=null;
            $retval = null;
            exec($command, $output, $retval);
            if ($retval) {
                $result = __json(0,$output);
            } else {
                $result = __json(1,"上传成功");
            }
 
        } catch (\Exception $e) {
            $result = __json(0,$e->getMessage());
        }
        
        __result($result);
    }
    
    public function downloadWxapp(){
        
        $result = $this->initWxappVersion();
        
        $platform = $result['platform'];
        $version_name = $result['version_name'];
        
        $filepath = ROOT_PATH."public/wxapp/{$version_name}.zip";
        $zip_path = ROOT_PATH."public/wxapp/{$version_name}";
        
        $res = zipDirectory($zip_path,$filepath,$version_name);
        
        if($res['code'] != 1){
            $this->error($res['message']);
        }
        if(file_exists($filepath) && $file=fopen($filepath,"r")){
            Header("content-type:application/octet-stream");
            //声明文件类型，这里是为了让客户端下载它，而不是打开它，所以声明为未知二进制文件。否则客户端会根据其文件类型在线打开它。
            Header("content-Length:".filesize($filepath)); //声明文件的大小，告诉客户端这个文件的大小，否则客户端下载的时候看不到进度。
            Header("content-disposition:attachment;filename={$version_name}.zip");
            //声明文件名，这里就是告诉客户端它要下载的文件的名字，否则名字就会是你php文件的名字。
            echo fread($file,filesize($filepath)); 
            //这里就是将加载的文件echo出来，因此这个php文件不能出现其他任何的文字，就是说这里若是出现了任何其他的输出的话都会输出到客户端下载的文件里。
            fclose($file);
        }
        else{
            $this->error("操作失败");
        }
    }

    protected function initWxappVersion(){
        $version_name = Db::name("bbfx")->value("version_name");
        $admin = Db::name("admin")->where(['id'=>$this->auth->id])->find();
        if($admin['uniacid']){
            $platform = Db::name("platform")->where(['id'=>$admin['uniacid']])->find();
        }
        else{
            $platform = Db::name("platform")->where(['id'=>['>',0]])->order("id asc")->find();
        }
        $uniacid = $platform['id'];
        $domain = $_SERVER['HTTP_HOST'];
        
        $siteinfo = 'var siteinfo = {
	"uniacid": "'.$uniacid.'",
	"version": "'.$version_name.'",
	"siteroot": "https://'.$domain.'"
};
module.exports = siteinfo;   
        ';
        
        $res = file_put_contents(ROOT_PATH."public/wxapp/{$version_name}/siteinfo.js",$siteinfo);
        if(empty($res)){
            $this->error("操作失败");
        }

        $config = '{
  "description": "项目配置文件。",
  "packOptions": {
    "ignore": [],
    "include": []
  },
  "setting": {
    "urlCheck": false,
    "es6": false,
    "postcss": true,
    "minified": true,
    "newFeature": true,
    "bigPackageSizeSupport": true,
    "babelSetting": {
      "ignore": [],
      "disablePlugins": [],
      "outputPath": ""
    }
  },
  "compileType": "miniprogram",
  "libVersion": "3.2.5",
  "appid": "'.$platform['wxapp_AppId'].'",
  "projectname": "'.$platform['name'].'",
  "condition": {},
  "editorSetting": {
    "tabIndent": "insertSpaces",
    "tabSize": 2
  }
}';
        file_put_contents(ROOT_PATH."public/wxapp/{$version_name}/project.config.json",$config);

        // if(is_dir(ROOT_PATH."extend/miniprogram-ci/mp-weixin")){
        //     deleteDir(ROOT_PATH."extend/miniprogram-ci/mp-weixin");
        // }
        // copyDirectory(ROOT_PATH."public/wxapp/{$version_name}", ROOT_PATH."extend/miniprogram-ci/mp-weixin");

        return ['version_name'=>$version_name,'platform'=>$platform];
    }
}
