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

namespace app\admin\controller\bbfxshop;

use app\common\controller\Backend;
use think\Db;
use think\Cache;
use app\common\model\Upgrade;
use app\common\model\Config as ConfigModel;

class Site extends Backend
{
    public function getInfo(){
        $type = $this->param("type/d");
        $result = [];
        
        if($type == 1){
            // 激活授权
            $res = Upgrade::getVersion();
            if(!empty($res)){
                $expirestime = $res['expirestime'];
            }
            else{
                $expirestime = "";
            }
            // echo "<pre>";
            // print_r($res);die;
            $version_name = Db::name("bbfx")->value("version_name");

            $site = [
                'status'=>'未授权',
                'commercial_version_name'=>'免费版',
                'empower_time'=>'',
                'activate_status'=>'否',
                'empower_status'=>'否',
                'domain_name'=>$_SERVER['HTTP_HOST'],
                'version_name'=>$version_name,
                'expirestime'=>$expirestime,
                'expire_status'=>1
            ];

            if(!empty($res)){
                $site['expire_status'] = $res['site']['expire_status'];
                $site['status'] = $res['site']['status_text'];
                $site['domain_name'] = $res['site']['domain_name'];
                $site['is_activate'] = $res['site']['is_activate'];
                $site['commercial_version_name'] = $res['site']['commercial_version_name'];
                $site['empower_time'] = $res['site']['empower_time'];
                $site['activate_status'] = $res['site']['activate_status'];
                $site['empower_status'] = $res['site']['empower_status'];
            }
            
            $result['new_version_name'] = $res['version_name'];
            $result['is_upgrade'] = $res['is_upgrade'];
            $result['site'] = $site;
                    
            $buy_qrcode = "";
            $buy_qrcode_ty = "";
            $res = ihttp_get("https://www.baibianfenxiao.com/api/buy/qrcodev1");
            $res = toJsonde($res['content']);
            if($res['code'] == 1){
                $buy_qrcode = $res['data']['buy_wxapp_qrcode'];
                $buy_qrcode_ty = $res['data']['buy_wxapp_qrcode_ty'];
            } 

            $result['buy_qrcode'] = $buy_qrcode;
            $result['buy_qrcode_ty'] = $buy_qrcode_ty;

        }
        else if($type == 2){
            // 后台登录页
            $list = Db::name("config")->where(['name'=>['in',['logo','login_bg','beian']]])->field("name,value")->select();
            $result = ['username'=>$this->auth->username];
            foreach($list as $key => $val){
                if($val['name'] == 'login_bg' || $val['name'] == 'logo'){
                    $val['value'] = cdnurl($val['value']);
                }
                $result[$val['name']] = $val['value'];
            }

            $base = Db::name("bbfx_base")->where(["uniacid"=>UNIACID])->field("id,backend_notice,backend_notice_image,backend_notice_image_link")->find();
            if(!empty($base['backend_notice'])){
                $base['backend_notice'] = iunserializer($base['backend_notice']);
            }
            if(empty($base['backend_notice'])){
                $base['backend_notice'] = [];
            }
            $result['backend_notice'] = $base['backend_notice'];
            $result['backend_notice_image'] = cdnurl($base['backend_notice_image']);
            $result['backend_notice_image_link'] = $base['backend_notice_image_link'];
        }
        else if($type == 3){
            // 微信公众号
            $result = Db::name("platform")->where(['id'=>UNIACID])->field("AppId,AppSecret")->find();
            if(empty($result)){
                __error("站点信息错误");
            }
        }
        else if($type == 10){
            // 微信公众号支付
            $result = Db::name("platform")->where(['id'=>UNIACID])->field("mch_id,paykey,cert,certkey,publickeyId,publickey")->find();
            if(empty($result)){
                __error("站点信息错误");
            }
            $result['pay_catalogue'] = $_SERVER['HTTP_HOST']."/mobile/#/pages/public/";
            $result['pay_catalogue1'] = $_SERVER['HTTP_HOST']."/";
            $result['pay_notify'] = $_SERVER['HTTP_HOST']."/api/pay/notify/i/".UNIACID;
        }
        else if($type == 4){
            // 微信小程序
            $result = Db::name("platform")->where(['id'=>UNIACID])->field("wxapp_AppId,wxapp_AppSecret,wxapp_upload_privateKey,wxapp_native_tabbar,wxapp_native_tabbar_shenhe,wxapp_merchant_AppId,wxapp_merchant_AppSecret,wxapp_merchant_upload_privateKey")->find();
            if(empty($result)){
                __error("站点信息错误");
            }
        }
        else if($type == 11){
            // 微信支付
            // 小程序
            $field = "wxapp_mch_id,wxapp_paykey,wxapp_cert,wxapp_certkey,wxapp_publickeyId,wxapp_publickey";
            // 公众号
            $field .= ",mch_id,paykey,cert,certkey,publickeyId,publickey";
            // H5
            $field .= ",wap_AppId,wap_mch_id,wap_paykey,wap_cert,wap_certkey";
            // 服务商
            $field .= ",service_provider_status,service_provider_appid,service_provider_mchid,service_provider_paykey,service_provider_cert,service_provider_certkey";

            $result = Db::name("platform")->where(['id'=>UNIACID])->field($field)->find();
            if(empty($result)){
                __error("站点信息错误");
            }

            $result['pay_catalogue'] = $_SERVER['HTTP_HOST']."/mobile/#/pages/public/";
            $result['pay_catalogue1'] = $_SERVER['HTTP_HOST']."/";
            $result['pay_notify'] = $_SERVER['HTTP_HOST']."/api/pay/notify/i/".UNIACID;
        }
        else if($type == 5){
            // 微信服务商支付
            $result = Db::name("platform")->where(['id'=>UNIACID])->field("service_provider_status,service_provider_appid,service_provider_mchid,mch_id,wxapp_mch_id,service_provider_paykey,service_provider_cert,service_provider_certkey")->find();
            if(empty($result)){
                __error("站点信息错误");
            }
        }
        else if($type == 6){
            // 支付宝支付
            $result = Db::name("platform")->where(['id'=>UNIACID])->field("zfb_appid,zfb_privateKey,zfb_publickey_cert")->find();
            if(empty($result)){
                __error("站点信息错误");
            }
        }
        else if($type == 7){
            // 微信H5支付
            $result = Db::name("platform")->where(['id'=>UNIACID])->field("wap_AppId,wap_mch_id,wap_paykey,wap_cert,wap_certkey")->find();
            if(empty($result)){
                __error("站点信息错误");
            }
        }
        else if($type == 8){
            // 系统信息
            $result['os'] = php_uname(); // 服务器操作系统
            $result['server_software'] = $_SERVER['SERVER_SOFTWARE'];// 服务器环境
            $result['php_vesion'] = PHP_VERSION;// php版本
            $result['upload_max_filesize'] = @ini_get('file_uploads') ? ini_get('upload_max_filesize') : 'unknow';// 上传限制
            $result['gd_version'] = gd_info()[ 'GD Version' ];// GD（图形处理）版本
            $result['post_max_size'] = ini_get('post_max_size');// POST数据限制
            $result['max_file_uploads'] = ini_get('max_file_uploads');// 上传数量限制
            $result['max_execution_time'] = ini_get('max_execution_time'). "秒";// 最大执行时间
            $result['port'] = $_SERVER[ 'SERVER_PORT' ];// 端口
            $result['dns'] = $_SERVER[ 'HTTP_HOST' ]; // 服务器域名
            $result['memory_limit'] = ini_get('memory_limit');// 内存限制
            $result['ip'] = $_SERVER['SERVER_ADDR'];// 服务器IP
            $result['sockets'] = extension_loaded('sockets'); //是否支持sockets
            $result['openssl'] = extension_loaded('openssl'); //是否支持openssl
            $result['curl'] = function_exists('curl_init'); // 是否支持curl功能
            $result['fileinfo'] = extension_loaded('fileinfo'); //是否支持fileinfo
            $bbfx = Db::name("bbfx")->find();
            $result['name'] = "百变分销";
            $result['version_name'] = $bbfx['version_name'];
            $result['version'] = $bbfx['version'];
        }
        else if($type == 9){
            // 鸣谢
            $content = "";
            $result = ihttp_get("https://www.baibianfenxiao.com/api/article/mingxie");
            $result = toJsonde($result['content']);
            if($result['code'] == 1){
                $content = htmlspecialchars_decode($result['data']);
            }
            $result['content'] = $content;
        }
        else if($type == 13){
            // 斗拱支付
            $result = Db::name("platform")->where(['id'=>UNIACID])->field("dg_status,dg_sys_id,dg_product_id,dg_fenzhang,dg_fenzhang_rate,dg_huifu_id,dg_wxapp_huifu_id,dg_gzh_huifu_id,dg_zfb_huifu_id,dg_rsaPrivateKey,dg_rsaPublicKey")->find();
            if(empty($result)){
                __error("站点信息错误");
            }
        }
        else if($type == 14){
            // 汇付八方支付
            $huifubafang = Db::name("platform")->where(['id'=>UNIACID])->field("huifubafang")->value("huifubafang");
            
            $result = iunserializer($huifubafang);
            if(empty($result)){
                $result = ['status'=>0,'comKey'=>'','comSecret'=>'','merchant_id'=>'','appid'=>''];
            }
        }
        else if($type == 15){
            // 首信易支付
            $thirdparty_pay = Db::name("platform")->where(['id'=>UNIACID])->value("thirdparty_pay");
            
            $result = iunserializer($thirdparty_pay)['shouxin'];
            if(empty($result)){
                $result = ['status'=>0,'merchantId'=>'','partnerId'=>'','privatekey'=>'','privatekeyPass'=>'','pay_method'=>[]];
            }
            if(is_null($result['pay_method'])){
                $result['pay_method'] = [];
            }
        }
        else{
            __error("类型错误");
        }


        __success("操作成功",$result);
    }

    
    public function getRenewlog(){
        $renewlog = Upgrade::renewlog();

        if(empty($renewlog)){
            $renewlog = [];
        }

        __success("操作成功",['list'=>$renewlog]);
    }

    public function submit(){
        $type = $this->param("type/d");
        if($type == 2){
            $params = $this->param(['logo/s','login_bg/s','beian/s','backend_notice_image_link/s','backend_notice_image/s','backend_notice/a']);

            foreach($params as $key => $val){
                if($key == 'logo' || $key == 'login_bg'){
                    $val = replaceSiteroot($val);
                }
                Db::name("config")->where(['name'=>$key])->update(['value'=>$val]);
            }

            ConfigModel::refreshFile();

            $data = [
                'backend_notice_image_link'=>$params['backend_notice_image_link'],
                'backend_notice_image'=>replaceSiteroot($params['backend_notice_image']),
                'backend_notice'=>iserializer($params['backend_notice']),
            ];

            Db::name("bbfx_base")->where(['uniacid'=>UNIACID])->update($data);
        }
        else if($type == 13){
            $params = $this->param(['dg_status/d','dg_sys_id/s','dg_product_id/s','dg_fenzhang_rate/d','dg_fenzhang/d','dg_huifu_id/s','dg_wxapp_huifu_id/s','dg_gzh_huifu_id/s','dg_zfb_huifu_id/s','dg_rsaPrivateKey/s','dg_rsaPublicKey/s']);
            if($params['dg_fenzhang'] == 1 && $params['dg_fenzhang_rate'] <= 0){
                __error("请输入最大分账比例");
            }
            Db::name("platform")->where(['id'=>UNIACID])->update($params);
        }
        else if($type == 14){
            $huifubafang = $this->param(['status/d','comKey/s','comSecret/s','merchant_id/s','appid/s']);
            Db::name("platform")->where(['id'=>UNIACID])->update(['huifubafang'=>iserializer($huifubafang)]);
        }
        else if($type == 12){
            $password = $this->param("password/s");
            if(!empty($password)){
                if(!empty($password) && mb_strlen($password, 'UTF-8') < 6){
                    __error("密码长度不足，最低6位字符");
                }

                $salt = \fast\Random::alnum();
                $password = $this->auth->getEncryptPassword($password, $salt);

                Db::name("admin")->where(['id'=>$this->auth->id])->update(['salt'=>$salt,'password'=>$password]);
            }
        }
        else if($type == 3){
            $params = $this->param(['AppId/s','AppSecret/s']);
            Db::name("platform")->where(['id'=>UNIACID])->update($params);
        }
        else if($type == 10){
            $params = $this->param(['mch_id/s','paykey/s','cert/s','certkey/s','publickeyId/s','publickey/s']);
            $params['cert'] = stripUrlDomain($params['cert']);
            $params['certkey'] = stripUrlDomain($params['certkey']);
            $params['publickey'] = stripUrlDomain($params['publickey']);
            Db::name("platform")->where(['id'=>UNIACID])->update($params);
        }
        else if($type == 4){
            $params = $this->param(['wxapp_AppId/s','wxapp_AppSecret/s','wxapp_upload_privateKey/s','wxapp_native_tabbar/d','wxapp_native_tabbar_shenhe/d','wxapp_merchant_AppId/s','wxapp_merchant_AppSecret/s','wxapp_merchant_upload_privateKey/s']);
            $params['wxapp_upload_privateKey'] = stripUrlDomain($params['wxapp_upload_privateKey']);
            $params['wxapp_merchant_upload_privateKey'] = stripUrlDomain($params['wxapp_merchant_upload_privateKey']);

            Db::name("platform")->where(['id'=>UNIACID])->update($params);
        }
        else if($type == 11){
            $params = $this->param(['wxapp_mch_id/s','wxapp_paykey/s','wxapp_cert/s','wxapp_certkey/s','wxapp_publickeyId/s','wxapp_publickey/s','mch_id/s','paykey/s','cert/s','certkey/s','publickeyId/s','publickey/s','wap_AppId/s','wap_mch_id/s','wap_paykey/s','wap_cert/s','wap_certkey/s','service_provider_status/d','service_provider_appid/s','service_provider_mchid/s','service_provider_paykey/s','service_provider_cert/s','service_provider_certkey/s']);
            // 小程序
            $params['wxapp_cert'] = stripUrlDomain($params['wxapp_cert']);
            $params['wxapp_certkey'] = stripUrlDomain($params['wxapp_certkey']);
            $params['wxapp_publickey'] = stripUrlDomain($params['wxapp_publickey']);
            // 公众号
            $params['cert'] = stripUrlDomain($params['cert']);
            $params['certkey'] = stripUrlDomain($params['certkey']);
            $params['publickey'] = stripUrlDomain($params['publickey']);
            // H5
            $params['wap_cert'] = stripUrlDomain($params['wap_cert']);
            $params['wap_certkey'] = stripUrlDomain($params['wap_certkey']);
            // 服务商
            $params['service_provider_cert'] = stripUrlDomain($params['service_provider_cert']);
            $params['service_provider_certkey'] = stripUrlDomain($params['service_provider_certkey']);

            Db::name("platform")->where(['id'=>UNIACID])->update($params);
        }
        else if($type == 5){
            $params = $this->param(['service_provider_status/d','service_provider_appid/s','service_provider_mchid/s','mch_id/s','wxapp_mch_id/s','service_provider_paykey/s','service_provider_cert/s','service_provider_certkey/s']);
            $params['service_provider_cert'] = stripUrlDomain($params['service_provider_cert']);
            $params['service_provider_certkey'] = stripUrlDomain($params['service_provider_certkey']);
            Db::name("platform")->where(['id'=>UNIACID])->update($params);
        }
        else if($type == 6){
            $params = $this->param(['zfb_appid/d','zfb_privateKey/s','zfb_publickey_cert/s']);
            $params['zfb_publickey_cert'] = stripUrlDomain($params['zfb_publickey_cert']);
            Db::name("platform")->where(['id'=>UNIACID])->update($params);
        }
        else if($type == 7){
            $params = $this->param(['wap_AppId/s','wap_mch_id/s','wap_paykey/s','wap_cert/s','wap_certkey/s']);
            $params['wap_cert'] = stripUrlDomain($params['wap_cert']);
            $params['wap_certkey'] = stripUrlDomain($params['wap_certkey']);
            Db::name("platform")->where(['id'=>UNIACID])->update($params);
        }
        else if($type == 15){
            $params = $this->param(['status/d','merchantId/s','partnerId/s','privatekey/s','privatekeyPass/s','pay_method/a']);
            $params['privatekey'] = stripUrlDomain($params['privatekey']);

            
            $thirdparty_pay = Db::name("platform")->where(['id'=>UNIACID])->value("thirdparty_pay");
            
            $thirdparty_pay = iunserializer($thirdparty_pay);
            $thirdparty_pay['shouxin'] = $params;

            Db::name("platform")->where(['id'=>UNIACID])->update(['thirdparty_pay'=>iserializer($thirdparty_pay)]);
        }
        else{
            __error("操作失败");
        }

        __success("操作成功");
    }

    public function getWxappTabbar(){
        $wxapp_tabbar = Db::name("platform")->where(['id'=>UNIACID])->value("wxapp_tabbar");
        $wxapp_tabbar = iunserializer($wxapp_tabbar);
        if(empty($wxapp_tabbar)){
            $wxapp_tabbar = [
                "color"=>"#5b5b5b",
                "selectedColor"=>"#000000",
                "bgColor"=>"#ffffff",
                "list"=>[]
            ];
        }

        __success("操作成功",$wxapp_tabbar);
    }

    public function submitWxappTabbar(){
        $wxapp_tabbar = $this->param(['color/s','selectedColor/s','bgColor/s','list/a']);
        Db::name("platform")->where(['id'=>UNIACID])->update(['wxapp_tabbar'=>iserializer($wxapp_tabbar)]);
        __success("操作成功");
    }


    public function xufei(){
        $code = $this->param("code/s");
        if(empty($code)){
            __error("请输入授权码");
        }
        
        $result = Upgrade::xufei($code);

        __result($result);
    }

    public function update(){
        Cache::set("is_download",false);
        $del_files = ["public/admin","public/mobile/static","public/datascreen/assets","public/merchant"];
        $res = Upgrade::execute($del_files);
        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 updateSuccessful(){
        $result = \app\common\model\UpdateSql::updateSuccessful();
        __result($result);
    }

    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) {
                addFileLog("wxappupload",json_encode($output));
                $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){
            __error($res['message']);
        }

        // 无法压缩成功一半是因为文件权限问题
        // 查看归属：ls -l，查看每一行第三、四列（属主：属组）
        // 异常文件：root root ， 正常文件：www-data www-data / nginx nginx
        // 先确认你的 PHP 运行用户：ps aux | grep php-fpm | grep -v root
        // 然后执行其中一个命令（一般都是第一个）：chown -R www:www /www/wwwroot/域名/public/wxapp/
        // chown -R www-data:www-data /www/wwwroot/域名/public/wxapp/
        // chown -R nginx:nginx /www/wwwroot/域名/public/wxapp/

        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{
            __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'];
        if(empty($platform['wxapp_AppId'])){
            __error("未配置小程序APPID");
        }

        // 设置原生导航
        $app_json = file_get_contents(ROOT_PATH."public/wxapp/{$version_name}/app.json");
        $app_json = json_decode($app_json,true);
        if(!empty($app_json)){
            if($platform['wxapp_native_tabbar'] == 1){
                
                $wxapp_tabbar = iunserializer($platform['wxapp_tabbar']);
                
                if(empty($wxapp_tabbar) || empty($wxapp_tabbar['list'])){
                    __error("未配置小程序原生导航");
                }

                $tabbar_filepath = ROOT_PATH."public/wxapp/{$version_name}/static/tabbar";
                del_Dir($tabbar_filepath);
                if(!is_dir($tabbar_filepath)) {
                    mkdir($tabbar_filepath, 0777, true);
                }

                
                $tabBar_item = [];
                foreach($wxapp_tabbar['list'] as $key => $item){
                    
                    $links = explode("/",$item['path']);
                    $pagePath = [];
                    foreach($links as $v){
                        if(!empty($v)){
                            $pagePath[] = $v;
                        }
                    }
                    $pagePath = implode("/",$pagePath);
                    
                    if(!strstr($pagePath, 'pages/')){
                        __error("【".$item['pathName']."】页面不可作为原生tabbar页面");
                    }
                    if(strstr($pagePath, 'diypage/')){
                        $pagePath = explode("?",$pagePath)[0];
                    }

                    $iconPath_filename = "iconPath_".$key.".png";
                    $selectedIconPath_filename = "selectedIconPath_".$key.".png";
                    $iconPath = download_file(cdnurl($item['defaultIcon']), $tabbar_filepath."/",$iconPath_filename);
                    $selectedIconPath = download_file(cdnurl($item['activeIcon']), $tabbar_filepath."/",$selectedIconPath_filename);
                    if(!empty($iconPath)){
                        $iconPath = "static/tabbar/".$iconPath_filename;
                    }
                    else{
                        $iconPath = "";
                    }
                    if(!empty($selectedIconPath)){
                        $selectedIconPath = "static/tabbar/".$selectedIconPath_filename;
                    }
                    else{
                        $selectedIconPath = "";
                    }
                    $tabBar_item[] = [
                        "pagePath"=> $pagePath,
                        "iconPath"=> $iconPath,
                        "selectedIconPath"=> $selectedIconPath,
                        "text"=> $item['pathName']
                    ];
                }
                
                $tabBar = [
                    "color"=>rgbToHex($wxapp_tabbar['color']),
                    "selectedColor"=>rgbToHex($wxapp_tabbar['selectedColor']),
                    "borderStyle"=> "black",
                    "backgroundColor"=> rgbToHex($wxapp_tabbar['bgColor']),
                    "list"=>$tabBar_item
                ];
                $app_json['tabBar'] = $tabBar;


                $app_json = json_encode($app_json,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE);
                $app_json = str_replace("\/","/",$app_json);
                $app_json = str_replace('"usingComponents": []','"usingComponents": {}',$app_json);
                file_put_contents(ROOT_PATH."public/wxapp/{$version_name}/app.json", $app_json);
            }
            else{
                unset($app_json['tabBar']);
                $app_json = json_encode($app_json,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE);
                $app_json = str_replace("\/","/",$app_json);
                $app_json = str_replace('"usingComponents": []','"usingComponents": {}',$app_json);
                file_put_contents(ROOT_PATH."public/wxapp/{$version_name}/app.json", $app_json);
            }
        }


        $site_name = Db::name("bbfx_base")->where(['uniacid'=>UNIACID])->value("title");
        
        $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)){
            __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": "'.$site_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];
    }

    // 上传商户端小程序代码
    public function uploadMerchantWxapp()
    {
        // 

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

        if (!file_exists('../extend/miniprogram-ci/merchantupload.js')) {
            $merchantupload = "
                const ci = require('miniprogram-ci')
                let data = process.argv[2];
                data = JSON.parse(data);
                if(data.length ==  0) {
                    console.log('参数缺失');
                    process.exit(-1);
                }
                let appid = data.appid;
                let privateKeyPath = data.privateKeyPath;
                let desc = data.desc;
                let version = data.version;
                
                const project = new ci.Project({
                    appid: appid,
                    type: 'miniProgram',
                    projectPath: `../public/merchant/wxapp`,
                    privateKeyPath: privateKeyPath,
                    ignores: ['node_modules/**/*'],
                })
                
                ci.upload({
                    project,
                    version,
                    desc,
                    setting: {
                        es6: true,
                        es7: true,
                        minify: true,
                    },
                    onProgressUpdate: console.log,
                })
            ";
            file_put_contents('../extend/miniprogram-ci/merchantupload.js',$merchantupload);
        }
        
        $result = $this->initMerchantWxappVersion();

        $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_merchant_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_merchant_upload_privateKey'];
            
            //上传小程序代码
            $data = [
                'appid' => $platform['wxapp_merchant_AppId'],
                'privateKeyPath'=>$privateKeyPath,
                'version' => $version_name,
                'desc' => '',
            ];
            $json_data = json_encode($data);
            $command = 'node ../extend/miniprogram-ci/merchantupload.js '.escapeshellarg($json_data).' 2>&1';
            $output=null;
            $retval = null;
            exec($command, $output, $retval);
            if ($retval) {
                addFileLog("merchantupload",json_encode($output));
                $result = __json(0,$output);
            } else {
                $result = __json(1,"上传成功");
            }
 
        } catch (\Exception $e) {
            $result = __json(0,$e->getMessage());
        }
        
        __result($result);
    }

    // 下载商户端小程序代码
    public function downloadMerchantWxapp(){
        
        $result = $this->initMerchantWxappVersion();
        
        $platform = $result['platform'];
        $version_name = $result['version_name'];
        
        $filepath = ROOT_PATH."public/merchant/wxapp.zip";
        $zip_path = ROOT_PATH."public/merchant/wxapp";
        
        $res = zipDirectory($zip_path,$filepath,'wxapp');
        
        if($res['code'] != 1){
            __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=wxapp.zip");
            //声明文件名，这里就是告诉客户端它要下载的文件的名字，否则名字就会是你php文件的名字。
            echo fread($file,filesize($filepath)); 
            //这里就是将加载的文件echo出来，因此这个php文件不能出现其他任何的文字，就是说这里若是出现了任何其他的输出的话都会输出到客户端下载的文件里。
            fclose($file);
        }
        else{
            __error("操作失败");
        }
    }

    protected function initMerchantWxappVersion(){
        $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'];

        $platform['wxapp_merchant_AppId'] = $platform['wxapp_AppId'];
        $platform['wxapp_merchant_AppSecret'] = $platform['wxapp_AppSecret'];
        $platform['wxapp_merchant_upload_privateKey'] = $platform['wxapp_upload_privateKey'];

        if(empty($platform['wxapp_merchant_AppId'])){
            __error("未配置商户小程序APPID");
        }


        $site_name = Db::name("bbfx_base")->where(['uniacid'=>UNIACID])->value("title");
        
        $siteinfo = 'var siteinfo = {
	"uniacid": "'.$uniacid.'",
	"version": "'.$version_name.'",
	"siteroot": "https://'.$domain.'"
};
module.exports = siteinfo;   
        ';
        
        $res = file_put_contents(ROOT_PATH."public/merchant/wxapp/siteinfo.js",$siteinfo);
        if(empty($res)){
            __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_merchant_AppId'].'",
  "projectname": "'.$site_name.'商户端",
  "condition": {},
  "editorSetting": {
    "tabIndent": "insertSpaces",
    "tabSize": 2
  }
}';
        file_put_contents(ROOT_PATH."public/merchant/wxapp/project.config.json",$config);

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