<?php
namespace Base\Model;

use PhalApi\Exception;

class Authorization extends Base {
    protected function getTableName($id) {
        return 'authorization';
    }

    public static $authorization_type_name = [
        1=>'微信登录',
    ];

    //获取用户信息--连表--单条
    public function getUserInfo($where){
        if (empty($where)){
            return [];
        }
        return $this->getORM()
            ->alias('a')
            ->select('a.*,ad.nickname,ad.sex,ad.headimgurl,ad.province,ad.city,ad.country,ad.privilege,ad.authorization_id,m.username')
            ->leftJoin('authorization_details','ad','a.id = ad.authorization_id')
            ->leftJoin('member','m','a.member_id = m.id')
            ->where($where)
            ->fetchOne();

    }


    //获取用户信息--连表--多条
    public function getUserInfoS($where){
        if (empty($where)){
            return [];
        }
        return $this->getORM()
            ->alias('a')
            ->select('a.*,ad.nickname,ad.sex,ad.headimgurl,ad.province,ad.city,ad.country,ad.privilege,ad.authorization_id,m.username')
            ->leftJoin('authorization_details','ad','a.id = ad.authorization_id')
            ->leftJoin('member','m','a.member_id = m.id')
            ->where($where)
            ->fetchAll();

    }

    //微信回调添加第三方数据的
    public function addData($authorization, $authorization_details){
        try{
            // 开启事务
            $this->getORM()->beginTransaction();
            $inserResultObj = $this->getORM()->insert($authorization);  //注事务插入这个返回的不是id
            $authorization_details['authorization_id'] = $inserResultObj['id'];
            $authorizationDetailsModel =  new AuthorizationDetails;
            $authorizationDetailsModel->insert($authorization_details);
            // 提交事务
            $this->getORM()->commit();

            $authorization['id'] = $inserResultObj['id'];
            $result = [
                'authorization'=>$authorization,
                'authorization_details'=>$authorization_details
            ];

            return $result;
        }catch (Exception $exception){
            // 回滚事务
            $this->getORM()->rollBack();
            throw new Exception\BadRequestException('服务器内部异常，请检查参数');
        }
    }
}
