<?php

namespace app\api\controller;

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

    //我的关注列表
    public function my_follow_list(){
        $list = Db::name('user_follow')
            ->alias('follow')
            ->join('user','follow.follow_uid = user.id','LEFT')
            ->field('user.id,user.nickname,user.avatar,user.bio,user.birthday,user.gender')
            ->where('follow.uid',$this->auth->id)->order('follow.id desc')->autopage()->select();

        $list = list_domain_image($list,['avatar']);
        $list = list_birthday_age($list);

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

    //我的粉丝列表
    public function my_fans_list(){
        $list = Db::name('user_follow')
            ->alias('follow')
            ->join('user','follow.uid = user.id','LEFT')
            ->field('user.id,user.nickname,user.avatar,user.bio,user.birthday,user.gender')
            ->where('follow.follow_uid',$this->auth->id)->order('follow.id desc')->autopage()->select();

        $list = list_domain_image($list,['avatar']);
        $list = list_birthday_age($list);

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

    //关注某人
    public function follow_one(){
        $follow_uid = input('follow_uid',0);
        if(!$follow_uid){
            $this->error(__('Invalid parameters'));
        }

        $checkuser = Db::name('user')->find($follow_uid);
        if(empty($checkuser)){
            $this->error('此用户不存在');
        }

        if($follow_uid == $this->auth->id){
            $this->error('不能关注自己');
        }

        $map = [
            'uid' => $this->auth->id,
            'follow_uid' => $follow_uid,
        ];

        $check = Db::name('user_follow')->where($map)->find();
        if($check){
            $this->error('已经关注此人');
        }

        Db::startTrans();
        $id = Db::name('user_follow')->insertGetId($map);
        if(!$id){
            Db::rollback();
            $this->error('关注失败');
        }

        //tag任务赠送金币
        //关注3人加3金币
        $task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,2);
        if($task_rs === false){
            Db::rollback();
            $this->error('完成任务赠送奖励失败');
        }

        Db::commit();
        $this->success('操作成功',$id);
    }

    //取关某人
    public function un_follow_one(){
        $follow_uid = input('follow_uid',0);
        if(!$follow_uid){
            $this->error(__('Invalid parameters'));
        }

        $checkuser = Db::name('user')->find($follow_uid);
        if(empty($checkuser)){
            $this->error('此用户不存在');
        }

        $map = [
            'uid' => $this->auth->id,
            'follow_uid' => $follow_uid,
        ];

        //不检查，全删

        $rs = Db::name('user_follow')->where($map)->delete();
        $this->success('操作成功');
    }
}
