<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
/**
 * 培训活动
 *
 * @icon fa fa-circle-o
 */
class Trainactive extends Backend
{

    /**
     * Trainactive模型对象
     * @var \app\admin\model\Trainactive
     */
    protected $model = null;
    protected $noNeedLogin = ['qrcode','showinfo','nograde','transfer','selectuser'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Trainactive;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("userauthStatusList", $this->model->getUserauthStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['cate','level','type'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('cate')->visible(['name']);
				$row->getRelation('level')->visible(['name']);
				$row->getRelation('type')->visible(['name']);

                $row['usercount'] = count(explode(',',$row['user_ids']));
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 二维码
     */
    public function qrcode(){
        $id = input('id');
        $info = Db::name('train_active')->where('id',$id)->find();

        //二维码
        $sign_data = [
            'type' => 'sign',
            'name' => $info['name'],
            'id'   => $info['id'],
        ];
        $pingjia_data = [
            'type' => 'pingjia',
            'name' => $info['name'],
            'id'   => $info['id'],
        ];
        $info['sign_qrcode'] = $this->introimage(json_encode($sign_data));
        $info['pingjia_qrcode'] = $this->introimage(json_encode($pingjia_data));

        $this->assign('row',$info);

        //评价人
        $pingjiaren = Db::name('user')->where('id',$info['pingjia_uid'])->value('nickname');
        $this->assign('pingjiaren',$pingjiaren);

        $this->view->engine->layout(false);
        return $this->view->fetch();
    }

    //生成邀请码二维码图片
    private function introimage($data) {
        $params['text'] = $data;
        $qrcode_service = \addons\qrcode\library\Service::qrcode($params);

        $qrcodePath = ROOT_PATH . 'public/uploads/trainqrcode/'.date('Ymd');
        if (!is_dir($qrcodePath)) {
            @mkdir($qrcodePath);
        }
        $filename = md5($data) . '.png';
        if (is_really_writable($qrcodePath)) {
            $filePath = $qrcodePath .'/'. $filename;
            $qrcode_service->writeFile($filePath);
        }

        return request()->domain().'/uploads/trainqrcode/'.date('Ymd') .'/'. $filename;
    }

    /**
     * 打印
     */
    public function showinfo(){
        $id = input('id');
        $info = Db::name('train_active')->alias('ta')->field('ta.*,cate.name as cate_name,level.name as level_name,type.name as type_name,user.nickname as pingjia_nickname')
            ->join('train_cate cate',  'ta.cate_id  = cate.id' ,'LEFT')
            ->join('train_level level','ta.level_id = level.id','LEFT')
            ->join('train_type type',  'ta.type_id  = type.id' ,'LEFT')
            ->join('user',         'ta.pingjia_uid  = user.id' ,'LEFT')
            ->where('ta.id',$id)->find();
        $info = info_domain_image($info,['logo_image','files','pingjia_image']);

        //重新定义附件
        $files_json = json_decode($info['files_json'],true);
        if(!empty($files_json)){
            foreach($files_json as $key => $file){
                $files_json[$key]['url'] = localpath_to_netpath($file['url']);
                $url = explode('.',$file['url']);
                $files_json[$key]['suffix'] = $url[count($url)-1];
            }
            $info['files_json'] = $files_json;
        }else{
            $info['files_json'] = [];
        }

        //时间
        $info['pingjia_time'] = $info['pingjia_time'] == 0 ? '' : date('Y-m-d H:i:s',$info['pingjia_time']);
        $info['starttime'] = $info['starttime'] == 0 ? '' : date('Y-m-d H:i:s',$info['starttime']);
        $info['endtime'] = $info['endtime'] == 0 ? '' : date('Y-m-d H:i:s',$info['endtime']);

        $this->assign('row',$info);

        //全部应到用户，左外链接，没签到的则为NULL
        if(empty($info['user_ids'])){ $info['user_ids'] = 0;}

        $user_yingdao = Db::name('user')->field('user_train.*,user.nickname,user.id as user_pkid')
            ->join('user_train','user_train.user_id = user.id and user_train.train_id = '.$info['id'],'LEFT')
            ->where('user.id','IN',$info['user_ids'])
            ->orderRaw('field(user.id,'.$info['user_ids'].')')
            ->select();
//        dump($user_yingdao);
        $status_arr = [
            1 => '正常',
            2 => '迟到',
        ];
        $status_color = [
            1 => 'green',
            2 => 'blue',
        ];
        if(!empty($user_yingdao)){
        foreach($user_yingdao as $key => $val){
            $user_yingdao[$key]['sign_time'] = empty($val['sign_time']) ? '' : date('Y-m-d H:i:s',$val['sign_time']);
            $user_yingdao[$key]['sign_image'] = localpath_to_netpath($val['sign_image']);
            $user_yingdao[$key]['status_text'] = isset($status_arr[$val['status']]) ? $status_arr[$val['status']] : '未到';
            $user_yingdao[$key]['status_color'] = isset($status_color[$val['status']]) ? $status_color[$val['status']] : 'red';
        }
        }

        //其他用户 签到记录
        $user_train = Db::name('user_train')->field('user_train.*,user.nickname,user.id as user_pkid')
            ->join('user','user_train.user_id = user.id','LEFT')
            ->where('user_train.train_id',$id)
            ->where('user_train.user_id','NOTIN',$info['user_ids'])
            ->order('user_train.id desc')->select();
//        dump($user_train);
        foreach($user_train as $key => $val){
            $user_train[$key]['sign_time'] = empty($val['sign_time']) ? '' : date('Y-m-d H:i:s',$val['sign_time']);
            $user_train[$key]['sign_image'] = localpath_to_netpath($val['sign_image']);
//            $user_train[$key]['status_text'] = isset($status_arr[$val['status']]) ? $status_arr[$val['status']] : '';
//            $user_train[$key]['status_color'] = isset($status_color[$val['status']]) ? $status_color[$val['status']] : 'red';
            $user_train[$key]['status_text'] = '';
            $user_train[$key]['status_color'] = '';
        }

        //本活动给的所有评分
        $user_train_evaluate = Db::name('user_train_evaluate')->where('train_id',$id)->column('user_id,score');

        //合并
        $all_user_train = array_merge($user_yingdao,$user_train);
        foreach($all_user_train as $key => $usertrain){
            $all_user_train[$key]['score'] = isset($user_train_evaluate[$usertrain['user_pkid']]) ? $user_train_evaluate[$usertrain['user_pkid']] : '';
        }
        $this->assign('user_train',$all_user_train);

        //查看评分的权限
        $score_auth = 0; //无权限
        if($this->auth->check('trainactive/showinfo/score')){
            $score_auth = 1; //有权限
        }
        $this->assign('score_auth',$score_auth);

        //学习记录，过滤掉没签到的
        $all_user_train_signed = $all_user_train;
        foreach($all_user_train_signed as $key => $val){
            if(empty($val['sign_image'])){
                unset($all_user_train_signed[$key]);
            }
        }
        $this->assign('user_train_chunk',array_chunk($all_user_train_signed,8));

        //应到，但实到的
        $shidao = Db::name('user_train')->where('train_id',$id)->where('user_id','IN',$info['user_ids'])->count('id');

        //应到的
        $yingdao = $info['user_ids'] == 0 ? 0 :count(explode(',',$info['user_ids']));
        $result = [
            'yingdao' => $yingdao,
            'shidao' => $shidao,
            'weidao' => $yingdao - $shidao,
            'qita' => Db::name('user_train')->where('train_id',$id)->where('user_id','NOTIN',$info['user_ids'])->count('id'),
        ];
        $this->assign('result',$result);
        //
        $this->view->engine->layout(false);
        return $this->view->fetch();
    }

    /**
     * 未到用户
     */
    public function nograde(){
        $id = input('id');
        $info = Db::name('train_active')->where('id',$id)->find();
        $user_ids = $info['user_ids'];

        $grade_uids = Db::name('user_train')->where('train_id',$id)->column('user_id');

        $lists = Db::name('user')->where('id','IN',$user_ids)->where('id','NOTIN',$grade_uids)->select();
        $this->assign('lists',$lists);
        return $this->view->fetch();
    }

    /**
     * 穿梭
     */
    public function transfer(){
        //
        $this->view->engine->layout(false);
        return $this->view->fetch();
    }

    /**
     * 选人
     */
    public function selectuser(){

        $id = input('id');

        if($this->request->isPost()){
            $params = $this->request->post('row/a');
            $user_rule = explode(',',$params['user_rule']);

            $user_ids = [];
            foreach($user_rule as $key => $val){
                if(strpos($val,'u_') !== false){
                    $user_ids[] = substr($val,2);
                }
            }
            $user_ids = implode(',',$user_ids);

            $update = [
                'user_ids' => $user_ids,
                'user_rule' => $params['user_rule'],
                'userauth_status' => $params['userauth_status'],
            ];
            Db::name('train_active')->where('id',$id)->update($update);
            $this->success('设置成功');
        }

        $id = input('id');
        $row = Db::name('train_active')->where('id',$id)->find();
        
        $user_rule = explode(',', $row['user_rule']);
        $nodeList = \app\admin\model\User::getTreeList($user_rule);
        $this->assign("nodeList", $nodeList);

        $this->assign('row',$row);
        return $this->view->fetch();
    }
}
