<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
/**
 * 关系
 */
class Relation extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    //关系列表
    public function lists(){
        $uid = input('uid',$this->auth->id);

        //所有
        $list = Db::name('relation')->where('is_show',1)->order('weigh desc')->select();

        //已有关系
        $user_relation = Db::name('user_relation')->alias('ur')
            ->field('ur.*,u.avatar,u.nickname,to.avatar as to_avatar,to.nickname as to_nickname')
            ->join('user u','ur.uid = u.id','LEFT')
            ->join('user to','ur.to_uid = to.id','LEFT')
            ->where('ur.uid|ur.to_uid',$uid)->where('ur.status',1)->select();
        $user_relation = list_domain_image($user_relation,['avatar','to_avatar']);
        $new_user_relation = array_column($user_relation,null,'relation_id');

        //处理,留对方的头像和昵称
        foreach($list as $key => &$val){
            $val['info'] = [];
            if(isset($new_user_relation[$val['id']])){
                $info = $new_user_relation[$val['id']];
                if($info['uid'] == $uid){
                    $info['avatar'] = $info['to_avatar'];
                    $info['nickname'] = $info['to_nickname'];
                    unset($info['to_avatar']);
                    unset($info['to_nickname']);
                }else{
                    unset($info['to_avatar']);
                    unset($info['to_nickname']);
                }

                //是否能取消
                $info['can_cancel'] = 0;
                if($info['uid'] == $this->auth->id || $info['to_uid'] == $this->auth->id){
                    $info['can_cancel'] = 1;
                }

                $val['info'] = $info;
            }
        }

        $this->success('success',$list);
    }

    //新增
    public function addone(){
        $to_uid = input('to_uid',0);
        if($to_uid == $this->auth->id){
            $this->error('不能跟自己建立关系');
        }

        if(!$this->user_auth_limit()){
            $this->error('请先完成实名认证');
        }

        //关系检测
        $relation_id    = input('relation_id','');
        $relation = Db::name('relation')->where('id',$relation_id)->find();
        if(empty($relation)){
            $this->error('不存在的关系');
        }
        $relation_name = $relation['name'];



        //检查这两个人的已有关系
        $where = '(uid = '.$this->auth->id.' and to_uid = '.$to_uid.') or (uid = '.$to_uid.' and to_uid = '.$this->auth->id.')';
        $check = Db::name('user_relation')->where($where)->find();

        if($check){
            $now_relation = Db::name('relation')->where('id',$check['relation_id'])->value('name');

            if($check['status'] == 1){
                if($check['uid'] == $this->auth->id){
                    $this->error('您已经与该用户建立'.$now_relation.'关系');
                }else{
                    $this->error('该用户已经与您建立'.$now_relation.'关系');
                }
            }elseif($check['status'] == 0){
                if($check['uid'] == $this->auth->id){
                    $this->error('您已经申请建立'.$now_relation.'关系,待对方同意');
                }else{
                    $this->error('对方已经申请建立'.$now_relation.'关系,待您同意');
                }
            }elseif($check['status'] == 2){
                $this->error($now_relation.'关系的申请已被拒绝,七日内不能再像TA申请');
            }else{
                //可以申请
            }
        }else{
            //可以申请
        }

        //检查我 关系的唯一性
        $check_map1 = 'relation_id = '.$relation_id.' and (uid = '.$this->auth->id.' or to_uid = '.$this->auth->id.')';
        $check_res1 = Db::name('user_relation')->where($check_map1)->find();
        if($check_res1){
            if($check_res1['status'] == 1){
                if($check_res1['uid'] == $this->auth->id){
                    $this->error('您已经与其他用户建立'.$relation_name.'关系');
                }else{
                    $this->error('其他用户已经与您建立'.$relation_name.'关系');
                }
            }elseif($check_res1['status'] == 0){
                if($check_res1['uid'] == $this->auth->id){
                    $this->error('您已经与其他用户申请建立'.$relation_name.'关系,待对方审核中');
                }else{
                    $this->error('其他用户已经与您申请建立'.$relation_name.'关系,待您审核中');
                }
            }
        }

        //检查对方 关系的唯一性
        $check_map2 = 'relation_id = '.$relation_id.' and (uid = '.$to_uid.' or to_uid = '.$to_uid.')';
        $check_res2 = Db::name('user_relation')->where($check_map2)->find();
        if($check_res2){
            if($check_res2['status'] == 1){
                if($check_res2['uid'] == $to_uid){
                    $this->error('TA已经与其他用户建立'.$relation_name.'关系');
                }else{
                    $this->error('其他用户已经与TA建立'.$relation_name.'关系');
                }
            }elseif($check_res2['status'] == 0){
                if($check_res2['uid'] == $to_uid){
                    $this->error('TA已经与其他用户申请建立'.$relation_name.'关系');
                }else{
                    $this->error('其他用户已经与TA申请建立'.$relation_name.'关系');
                }
            }
        }

        Db::startTrans();

        //检查关系卡数量
        $cardnum = Db::name('user_decorate_relation')->where('user_id',$this->auth->id)->where('is_using',0)->order('id desc')->lock(true)->find();
        if(empty($cardnum)){
            Db::rollback();
            $this->error('关系卡数量不足');
        }

        //扣掉一个关系卡
        $use_card = Db::name('user_decorate_relation')->where('id',$cardnum['id'])->update(['is_using'=>1,'updatetime'=>time()]);
        if(!$use_card){
            Db::rollback();
            $this->error('关系申请失败');
        }

        //新增
        $data = [
            'uid' => $this->auth->id,
            'relation_id' => $relation_id,
            'to_uid' => $to_uid,
            'status' => 0,
            'createtime' => time(),
            'updatetime' => time(),
        ];

        $id = Db::name('user_relation')->insertGetId($data);
        if(!$id){
            Db::rollback();
            $this->error('关系申请失败');
        }

        //给对方一条消息
        $message = [
            'content' => $this->auth->nickname . '申请与你成为'.$relation['name'],
        ];
        $msg_id = \app\common\model\Message::addMessage($to_uid,'关系审核',$message['content'],'newrelation',0);

        //发起人也要发消息
        //系统消息
        $to_nickname = Db::name('user')->where('id',$to_uid)->value('nickname');
        $msg_id = \app\common\model\Message::addMessage($this->auth->id,'申请关系','您正在申请与'.$to_nickname.'成为'.$relation_name.'关系,请等待对方同意','applyrelation');

        Db::commit();

        $this->success('申请成功,请等待对方同意',$id);
    }

    //待审核关系
    public function audit_lists(){
        $list = Db::name('user_relation')->alias('ur')
            ->field('ur.*,relation.name as relation_name,user.nickname,user.avatar,user.gender,user.birthday,uw.vip_endtime')
            ->join('relation','ur.relation_id = relation.id','LEFT')
            ->join('user','ur.uid = user.id','LEFT')
            ->join('user_wallet uw','ur.uid = uw.user_id','LEFT')
            ->where('ur.to_uid',$this->auth->id)
            ->where('ur.status',0)
            ->order('ur.id desc')->autopage()->select();
        $list = list_domain_image($list,['avatar']);

        if(!empty($list)){
            foreach($list as $key => &$val){

                //用户年龄
                $val['age'] = birthtime_to_age($val['birthday']);
                unset($val['birthday']);

                //用户vip
                $val['is_vip'] = $val['vip_endtime'] > time() ? 1 : 0;
                unset($val['vip_endtime']);

            }
        }

        $this->success('success',$list);
    }

    //审核
    public function audit(){
        $id = input('id',0);
        $status = input('status',1);

        //查询
        $info = Db::name('user_relation')->alias('ur')
            ->where('ur.id',$id)
            ->where('ur.to_uid',$this->auth->id)
            ->where('ur.status',0)
            ->find();
        if(!$info){
            $this->error('请刷新重试');
        }

        //更新
        $data = [
            'status' => $status,
            'updatetime' => time(),
        ];

        $rs = Db::name('user_relation')->where('id',$id)->update($data);
        if($rs === false){
            $this->error('操作失败');
        }

        if($status == 1){
            $remark = '您已同意建立关系';
            $remark2 = '已同意';
        }else{
            $remark = '已拒绝';
            $remark2 = '已拒绝';

            //退回关系卡
            $use_card = Db::name('user_decorate_relation')->where('user_id',$info['uid'])->where('is_using',1)->order('id desc')->find();
            if($use_card){
                $rs2 = Db::name('user_decorate_relation')->where('id',$use_card['id'])->update(['is_using'=>0,'updatetime'=>time()]);
                if($rs2 === false){
                    Db::rollback();
                    $this->error('操作失败');
                }
            }
        }

        //给发起方一条消息
        $relation_name = Db::name('relation')->where('id',$info['relation_id'])->value('name');
        $message = [
            'content' => '和'.$this->auth->nickname.'成为'.$relation_name.':'.$remark2,
        ];
        $msg_id = \app\common\model\Message::addMessage($info['uid'],'关系申请结果',$message['content']);

        //
        $this->success($remark);
    }

    //取消
    public function cancel(){
        $id = input('id',0);
        $relation_id = input('relation_id',0);

        $where = [
            'id' => $id,
            'relation_id' => $relation_id
        ];
        $where2 = 'uid = '.$this->auth->id.' or to_uid = '.$this->auth->id;
        $info = Db::name('user_relation')->where($where)->where($where2)->find();

        if(empty($info)){
            $this->error('不存在的关系');
        }

        Db::name('user_relation')->where($where)->delete();

        //给发起方一条消息
        $relation_name = Db::name('relation')->where('id',$relation_id)->value('name');
        $message = [
            'user_id' => ($info['uid'] == $this->auth->id) ? $info['to_uid'] : $info['uid'],
            'content' => $this->auth->nickname.'已取消和你的'.$relation_name.'关系',
        ];
        $msg_id = \app\common\model\Message::addMessage($message['user_id'],'关系取消',$message['content']);

        //
        $this->success('关系已取消');


    }


    ///////////////////////////关系卡///////////////////////

    //关系卡列表
    public function decorate_list(){
        $list = Db::name('decorate_relation')->autopage()->select();
        $list = list_domain_image($list,['base_image']);

        $relation = Db::name('relation')->where('is_show',1)->order('weigh desc')->column('name');
        $relation = implode(',',$relation);

        $result = [
            'list' => $list,
            'relation' => $relation
        ];

        $this->success(1,$result);
    }

    /**
     * 购买并加入我的背包
     */
    public function buy_one() {
        $number = input_post('number',1,'intval'); //数量
        if(!$number){
            $this->error();
        }

        $did = input_post('did',''); //装扮ID
        if (!$did) {
            $this->error();
        }
        // 判断用户金币余额是否充足
        $walletinfo = model('wallet')->getWallet($this->auth->id);

        // 获取购买装扮需要的价格
        $decorate = Db::name('decorate_relation')->where(['id'=>$did])->find();
        if(!$decorate) {
            $this->error("道具信息获取失败!");
        }
        $total_price = bcmul($decorate['price'],$number,0);
        if($walletinfo['gold'] < $total_price) {
            $this->error("您的金币不足,请先充值!");
        }
        // 进行购买逻辑
        Db::startTrans();

        // 添加到背包
        for($i=1;$i<=$number;$i++){
            $data[] = [
                'user_id' => $this->auth->id,
                'decorate_id' => $decorate['id'],
                'is_using' => 0,
                'createtime' => time(),
                'updatetime' => time(),
            ];
        }

        $log_id = Db::name('user_decorate_relation')->insertAll($data);
        if(!$log_id){
            Db::rollback();
            $this->error('购买失败');
        }

        //扣钱
        $rs = model('wallet')->lockChangeAccountRemain($this->auth->id,'gold',-$total_price,32,'购买关系卡','user_decorate_relation',0);
        if($rs['status'] === false){
            Db::rollback();
            $this->error($rs['msg']);
        }


        Db::commit();
        $this->success("购买成功!");
    }


    //获取用户装扮
    public function my_decorate_list()
    {
        $uid = $this->auth->id;

        $map = [
            'a.user_id' => $uid,
            'a.is_using'=> 0,
        ];

        $list = Db::name('user_decorate_relation')
            ->alias('a')
            ->field('a.id,a.decorate_id,b.name,b.base_image,count(a.decorate_id) as number')
            ->join('decorate_relation b', 'a.decorate_id = b.id','LEFT')
            ->where($map)->group('a.decorate_id')->order('a.id desc')->autopage()->select();

        $list = list_domain_image($list,['base_image']);

        $this->success('success',$list);
    }
}