<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Exception;
use think\exception\PDOException;

/**
 * 绑定资质
 * @ApiWeigh (96)
 */
class Bind extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];


    /**
     * @ApiTitle (输入手环ID绑定信息)
     * @ApiMethod (POST)
     * @ApiParams   (name="unique", type="string", required=true, description="手环id")
     * @ApiReturn   ({
    "code":"状态码",
    "msg": "提示消息",
    "data": {}
    })
     */
    public function inUnique()
    {
        $unique = $this->request->param('unique');
        $user = $this->auth->getUserinfo();
        if (empty($unique)) {
            $this->error('参数错误', ['status' => 2]);
        }
//        $res = \db('study')->where('unique',$unique)->value('user_id');
//        if (!empty($res)){
//            $this->error('当前学生已经被绑定了');
//        }
        $is_bind = db('user')->where('id', $user['id'])->value('bind_study');
//        if ($is_bind == 1) {
//            $this->error('您当前已经绑定过学生了,请勿重复操作', $is_bind);
//        }
        Db::startTrans();
        try {
            db('study')
                ->where('unique', $unique)
                ->update([
                    'user_id' => $user['id'],
                    'updatetime' => time()
                ]);
            \db('user')
                ->where('id', $user['id'])
                ->update([
                    'bind_study' => 1,
                    'updatetime' => time()
                ]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error('参数错误', $e->getMessage());
        }
        $data = db('study')->where('unique', $unique)->field('id,grade,name')->find();
        $this->success('绑定成功',$data);
    }

    /**
     * @ApiTitle (扫码绑定信息)
     * @ApiMethod (POST)
     * @ApiParams   (name="unique", type="string", required=true, description="手环id[条形码编号]")
     * @ApiReturn   ({
    "code":"状态码",
    "msg": "提示消息",
    "data": {}
    })
     */
    public function scanCode()
    {
        $unique = $this->request->param('unique');
        $user = $this->auth->getUserinfo();
        if (empty($unique)) {
            $this->error('参数错误', ['status' => 2]);
        }
//        $res = \db('study')->where('unique',$unique)->value('user_id');
//        if (!empty($res)){
//            $this->error('当前学生已经被绑定了');
//        }
        $is_bind = db('user')->where('id', $user['id'])->value('bind_study');
//        if ($is_bind == 1) {
//            $this->error('您当前已经绑定过学生了,请勿重复操作', $is_bind);
//        }
        Db::startTrans();
        try {
            db('study')
                ->where('unique', $unique)
                ->update([
                    'user_id' => $user['id'],
                    'updatetime' => time()
                ]);
            \db('user')
                ->where('id', $user['id'])
                ->update([
                    'bind_study' => 1,
                    'updatetime' => time()
                ]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error('参数错误', $e->getMessage());
        }
        $data = db('study')->where('unique', $unique)->field('id,grade,name')->find();
        $this->success('绑定成功', $data);
    }

    /**
     * @ApiTitle (项目管理[老师])
     * @ApiMethod (POST)
     * @ApiReturn   ({
    "code":"状态码",
    "msg": "提示消息",
    "data": {
    "id": 项目id,
    "title": "项目名称",
    }
    })
     */
    public function teachItem()
    {
        $user = $this->auth->getUserinfo();
        $data = db('item')
            ->where('user_id', $user['id'])
            ->field('id,title')
            ->select();
        if (empty($data)) {
            $this->error('当前还未关联项目', ['status' => 2]);
        }
        $this->success('获取项目成功', $data);
    }

    /**
     * @ApiTitle (学生校区)
     * @ApiMethod (POST)
     * @ApiReturn ({
    "code": "状态码",
    "msg": "获取校区成功",
    "time": "时间",
    "data": [
    {
    "campus_id": "校区id",
    "campus_title": "校区名称"
    }
    ]
    })
     */
    public function studyCampus(){
        $user = $this->auth->getUserinfo();
        $sid = db('study')
            ->where('user_id', $user['id'])
            ->value('id');
        $data = \db('study_score_log l')
            ->distinct('campus_id')
            ->join('campus c','c.id = l.campus_id')
            ->where('study_id',$sid)
            ->field('campus_id,c.title as campus_title')
            ->select();
        if (empty($data)){
            $this->error('当前学生还未有项目关联校区',['status'=>2]);
        }
        $this->success('获取校区成功', $data);

    }

    /**
     * @ApiTitle (活动现场[扫码])
     * @ApiMethod (POST)
     * @ApiParams   (name="id", type="string", required=true, description="项目id")
     * @ApiParams   (name="unique", type="string", required=true, description="条形码唯一标识")
     * @ApiReturn   ({
    "code":"状态码",
    "msg": "提示消息",
    "data": {
    "name": "姓名",
    "gender": "性别",
    }
    })
     */
    public function scanBarCode()
    {
        $id = $this->request->param('id');
        $unique = $this->request->param('unique');
        if (empty($unique) && empty($id)) {
            $this->error('参数错误', ['status' => 2]);
        }
        $study = db('study')->where('unique', $unique)->field('id,grade,name,team,earn_score')->find();
        $item = db('item')->where('id', $id)->field('score,title,campus_id')->find();
        $team = \db('team')->where('title', $study['team'])->field('title,score')->find();
        $sum1 = $team['score'] + $item['score'];    //合计战队总分
        $sum2 = $study['earn_score'] + $item['score'];  //合计个人总分
        Db::startTrans();
        try {
            db('study_score_log')->insert([
                'item_id' => $id,
                'campus_id' => $item['campus_id'],
                'study_id' => $study['id'],
                'team' => $study['team'],
                'score' => $item['score'],
                'memo' => $study['name'] . '参加' . $item['title'] . '加分',
                'createtime' => time()
            ]);
            db('study')
                ->where('id', $study['id'])
                ->update([
                    'earn_score' => $sum2,
                ]);
            \db('team')
                ->where('title', $study['team'])
                ->update([
                    'score' => $sum1,
                    'updatetime' => time()
                ]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error('连接错误', ['status' => 3]);
        }
        $data = db('study')->where('unique', $unique)->field('name,gender')->find();
        if ($data['gender'] == 1){
            $data['gender'] = '男';
        }else{
            $data['gender'] = '女';
        }
        $this->success('扫码成功', $data);
    }

    /**
     * @ApiTitle (绑定后获取头像昵称)
     */
    public function study(){
        $user = $this->auth->getUserinfo();
        $sid = \db('study')->where('user_id', $user['id'])->value('id');
        //获取学生的信息
        $data = \db('study')->where('id', $sid)->field('avatar,name,earn_score')->find();
        $data['avatar'] = cdnurl( $data['avatar'], true);
        $this->success('',$data);
    }

    /**
     * @ApiTitle (获取学生信息)
     * @ApiMethod (POST)
     * @ApiParams   (name="cid", type="string", required=true, description="校区id")
     * @ApiReturn   ({
    "code":"状态码",
    "msg": "提示消息",
    "data": {
    "avatar": "学生头像",
    "name": "学生名称",
    "earn_score": "学生获得分数"
    "item": 雷达图项目{
    "total": 1,
    "per_page": 3,
    "current_page": 1,
    "last_page": 1,
    "data": [
    {
    "item_id": 项目id,
    "sum_score": "项目分数",
    "title": "维度名称"
    },
    ]
    },}
    })
     */
    public function getScore()
    {
        $user = $this->auth->getUserinfo();
        $cid = $this->request->param('cid');
        $sid = \db('study')->where('user_id', $user['id'])->value('id');
        //获取学生的信息
        $data = \db('study')->where('id', $sid)->field('avatar,name,earn_score')->find();
        $data['avatar'] = cdnurl( $data['avatar'], true);
        //获取雷达维度
        $data['item'] = \db('study_score_log')
            ->distinct('item_id')
            ->field('item_id,SUM(score) as sum_score')
            ->order('sum_score','desc')
            ->group('item_id')
            ->where(['campus_id' => $cid, 'study_id' => $sid])
            ->paginate(3)
            ->each(function ($item, $key) {
                $item['title'] = \db('item i')
                    ->join('radar r', 'i.radar_id = r.id')
                    ->where('i.id', $item['item_id'])
                    ->value('r.title');
                return $item;
            });
        $this->success('获取成功', $data);
    }

}