<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\validate\Admin as AdminValidate;
use app\common\controller\Backend;
use think\App;
use think\db\exception\PDOException;use think\facade\Config;
use think\facade\Db;use think\Request;
use think\exception\ValidateException;

class Wechat extends Backend
{

	protected $noNeedLogin=["wxlogin"];
	protected $noNeedPermission=["wxinfo","wxedit"];
	public function __construct(App $app) {parent::__construct($app);}
	public function initialize(){
		parent::initialize(); // TODO: Change the autogenerated stub
	}
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function wxlogin()
    {
    	$openMemberCenter = Config::get('buildadmin.open_member_center');
        if (!$openMemberCenter) {
            $this->error(__('Member center disabled'));
        }

        // 检查登录态
        if ($this->auth->isLogin()) {
            $this->success(__('You have already logged in. There is no need to log in again~'), [
                'routePath' => '/user'
            ], 302);
        }
         if ($this->request->isPost()) {
            $params = $this->request->post(['openid','unionid',"nickname"=>"","avatar"=>"","mobile"=>"", "keep",
            'registerType'=>"wx"]);
            $validate = new AdminValidate();
            try {
                $validate->scene("wechat")->check($params);
            } catch (ValidateException $e){
                $this->error($e->getMessage());
            }
		    $res = $this->auth->isWxUser($params['openid'], $params['unionid'], (bool)$params['keep']);
            if (!$res) {
                $res = $this->auth->WxRegister( $params['openid'], $params['unionid'], $params['nickname'], $params['mobile'], $params['avatar']);
            }

            if (isset($res) && $res === true) {
                $this->success(__('Login succeeded!'), [
                    'userInfo'  =>$this->auth->getInfo(),
                    'routePath' => '/user'
                ]);
            } else {
                $msg = $this->auth->getError();
                $msg = $msg ?: __('Check in failed, please try again or contact the website administrator~');
                $this->error($msg);
            }
        }

        $this->success('', [
            'accountVerificationType' => get_account_verification_type()
        ]);
    }
	//微信端用户信息
   public  function wxinfo(){
        $this->success('', $this->auth->getInfo());
	}
	//微信端用户信息补充
   public  function wxedit(){
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }
            // 数据验证
            if ($this->modelValidate) {
                try {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->auth->getAdmin()));
                    $validate = new $validate;
                    $validate->scene('wxedit')->check($data);
                } catch (ValidateException $e) {
                    $this->error($e->getMessage());
                }
            }
            $data   = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                $result = $this->auth->getAdmin()->save($data);
                Db::commit();
            } catch (PDOException|\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }
}
