<?php
// +----------------------------------------------------------------------
// | [RhaPHP System] Copyright (c) 2017-2020 http://www.rhaphp.com/
// +----------------------------------------------------------------------
// | [RhaPHP] 并不是自由软件,你可免费使用,未经许可不能去掉RhaPHP相关版权
// +----------------------------------------------------------------------
// | Author: Geeson <qimengkeji@vip.qq.com>
// +----------------------------------------------------------------------

namespace app\miniapp\controller;

use app\common\model\MiniappAddon;
use think\Db;
use think\facade\Session;

class Base extends \app\admin\controller\Base
{
    public $_mid;//小程序标识 ID
    public $miniappInfo;//小程序信息
    public function initialize()
    {

        parent::initialize(); // TODO: Change the autogenerated stub
        if ($this->_mid =input('_mid')) {
            session('_mid', $this->_mid);
            $this->miniappInfo = getMimiappInfo($this->_mid);
            session('miniappInfo',$this->miniappInfo);
            $miniappInfo = Db::name('miniapp')->where('user_id','=', $this->admin_id)
                ->where('is_use','=','1')
                ->find();
            if ($miniappInfo['id'] != $this->_mid) {
                Db::name('miniapp')->where('user_id','=',$this->admin_id)
                    ->where('id' ,'=', $this->_mid)
                    ->update(['is_use' => '1']);
                Db::name('miniapp')->where('user_id','=', $this->admin_id)
                    ->where('id','neq', $this->_mid)
                    ->update(['is_use' => '0']);
            }
        } else {
            $miniappInfo = Db::name('miniapp')->where('user_id','=', $this->admin_id)
                ->where('is_use','=', '1')
                ->find();
            if(!empty($miniappInfo)){
                $this->_mid = $miniappInfo['id'];
                session('_mid', $this->_mid);
                $this->miniappInfo = getMimiappInfo($this->_mid);
                session('miniappInfo',$this->miniappInfo);
            }else{
                $this->redirect('mp/index/miniapplists');
            }
        }
        $options = array(
            'appid' => $this->miniappInfo['appid'],
            'appsecret' => $this->miniappInfo['appsecret'],
            'token' => $this->miniappInfo['token'],
            'encodingaeskey' => $this->miniappInfo['encodingaeskey']
        );
        $addon=MiniappAddon::where('addon',$this->miniappInfo['addon'])->field('name')->find();
        if(empty($addon)){
            $this->miniappInfo['addon_name']='';
        }else{
            $this->miniappInfo['addon_name']=$addon['name'];
        }
        $this->assign('miniappInfo', $this->miniappInfo);
        $this->assign('_mid',$this->_mid);
        Session::delete('mp_options');
        Session::set('miniapp_options', $options);
    }

}