<?php
namespace app\common\controller;
use think\facade\View;
use think\facade\Cache;
use think\facade\Session;
use think\facade\Db;
use app\common\variable\MsgCode;
use app\common\model\ScoreTask as ScoreTaskModel;
use app\common\model\UserInfo as UserInfoModel;
use app\common\model\UserScore as UserScoreModel;
use app\common\model\ScoreTaskComplete as ScoreTaskCompleteModel;
use app\common\event\ScoreTask as ScoreTaskEvent;
/**
 * 
 */
class Score extends Base
{
    public static function statistics($D)
    {
        $sign_in_status=0;
        $Task=ScoreTaskModel::where(['event'=>'sign_in'])->field('id,title,tips,event,score,url,repeat,repeat_sum')->find()->toArray();
        if ($Task) {
            if (ScoreTaskEvent::isComplete($D['uid'],$Task)==ScoreTaskEvent::COMPLETE_STATUS_2)
                $sign_in_status=1;
        }
        $Data=ScoreTaskModel::where(['status'=>1])
            ->whereRaw('is_company is null OR is_company ='.$D['role_type'])
            ->field('id,event,score,repeat,repeat_sum')
            ->order('sort asc,id desc')->paginate(1000)->each(function($v)use($D){
                $v->is_complete=ScoreTaskEvent::isComplete($D['uid'],$v);
            });
        $score_task=0;
        foreach ($Data->items() as $k => $v) {
            if ($v['is_complete']===ScoreTaskEvent::COMPLETE_STATUS_0
                ||$v['is_complete']===ScoreTaskEvent::COMPLETE_STATUS_1)
                $score_task=$score_task+$v['score'];
        }
        $Data=[
            'sign_in_status'=>$sign_in_status,
            'score'         =>  UserInfoModel::where(['uid'=>$D['uid']])->value('score'),
            'score_today'   =>  UserScoreModel::where(['uid'=>$D['uid']])->whereTime('create_time','today')->where('score','>',0)->sum('score'),
            'score_task'    =>  $score_task,
        ];
        return parent::ajaxReturn('',MsgCode::$success,$Data);
    }
    public static function getScoreTaskList($uid,$is_company)
    {
        $Data=ScoreTaskModel::where(['status'=>1])
            ->whereRaw('is_company is null OR is_company ='.$is_company)
            ->field('id,title,tips,event,score,url,repeat,repeat_sum')
            ->order('sort asc,id desc')->paginate(1000)->each(function($v)use($uid){
                $v->is_complete=ScoreTaskEvent::isComplete($uid,$v);
            });
        if ($Data->items()) {
            return parent::ajaxReturn('',MsgCode::$success,$Data);
        }else{
            return parent::ajaxReturn('暂无数据~',MsgCode::$error);
        }
    }
    public static function receiveScore($D)
    {
        $Task=ScoreTaskModel::where(['id'=>$D['id'],'status'=>1])->field('id,title,tips,event,score,url,repeat,repeat_sum')->find()->toArray();
        if ($Task) {
            $is_complete=ScoreTaskEvent::isComplete($D['uid'],$Task);
            switch (true) {
                case $is_complete==ScoreTaskEvent::COMPLETE_STATUS_1:
                    $UserInfoModel=UserInfoModel::where(['uid'=>$D['uid']])->find();
                    $UserInfoModel->score =Db::raw('score+'.$Task['score']);
                    $UserScoreModel=new UserScoreModel;
                    $UserScoreModel->uid    =   $D['uid'];
                    $UserScoreModel->tid    =   $Task['id'];
                    $UserScoreModel->score  =   $Task['score'];
                    $UserScoreModel->desc   =   '完成'.$Task['title'].'任务，奖励'.$Task['score'].'积分。';
                    $ScoreTaskCompleteModel=new ScoreTaskCompleteModel;
                    $ScoreTaskCompleteModel->uid    =   $D['uid'];
                    $ScoreTaskCompleteModel->tid    =   $Task['id'];
                    // 启动事务
                    Db::startTrans();
                    try {
                        $UserInfoModel->save();
                        $UserScoreModel->save();
                        $ScoreTaskCompleteModel->save();
                        // 提交事务
                        Db::commit();
                        return parent::ajaxReturn('领取成功');
                    } catch (\Exception $e) {
                        // 回滚事务
                        Db::rollback();
                        return parent::ajaxReturn('领取失败，请重试',MsgCode::$error);
                    }
                    break;
                case $is_complete==ScoreTaskEvent::COMPLETE_STATUS_2:
                    return parent::ajaxReturn('您已领取过奖励了，请刷新查看',MsgCode::$error);
                    break;
                default:
                    return parent::ajaxReturn('您还未完成该任务~',MsgCode::$error);
                    break;
            }
        }else{
            return parent::ajaxReturn('任务不存在或已下架~',MsgCode::$error);
        }
    }
    public static function signInToday($uid)
    {
        if (!$uid)
            return parent::ajaxReturn('请先登录',MsgCode::$error);
        $Task=ScoreTaskModel::where(['event'=>'sign_in'])->field('id,title,tips,event,score,url,repeat,repeat_sum')->find()->toArray();
        if ($Task) {
            if (ScoreTaskEvent::isComplete($uid,$Task)==ScoreTaskEvent::COMPLETE_STATUS_0) {
                $UserInfoModel=UserInfoModel::where(['uid'=>$uid])->find();
                $UserInfoModel->score =Db::raw('score+'.$Task['score']);
                $UserScoreModel=new UserScoreModel;
                $UserScoreModel->uid    =   $uid;
                $UserScoreModel->tid    =   $Task['id'];
                $UserScoreModel->score  =   $Task['score'];
                $UserScoreModel->desc   =   '完成'.$Task['title'].'任务，奖励'.$Task['score'].'积分。';
                $ScoreTaskCompleteModel=new ScoreTaskCompleteModel;
                $ScoreTaskCompleteModel->uid    =   $uid;
                $ScoreTaskCompleteModel->tid    =   $Task['id'];
                // 启动事务
                Db::startTrans();
                try {
                    $UserInfoModel->save();
                    $UserScoreModel->save();
                    $ScoreTaskCompleteModel->save();
                    // 提交事务
                    Db::commit();
                    Cache::set('updateUser:'.$uid,true);
                    return parent::ajaxReturn('签到成功',MsgCode::$success,['score'=>$Task['score']]);
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return parent::ajaxReturn('签到失败，请重试',MsgCode::$error);
                }
            }else{
                return parent::ajaxReturn('您已签到',MsgCode::$success);
            }
        }else{
            return parent::ajaxReturn('任务不存在',MsgCode::$error);
        }
    }
}