<?php

namespace app\mainapp\controller;

use app\mainapp\BaseController;
use app\common\model\Train as TrainModel;
use app\common\model\TrainJoin as TrainJoinModel;

class Train extends BaseController
{
    /**
     * 培训列表
     */
    public function list()
    {
        $ppage = input('ppage/d', 1);
        $psize = input('psize/d', 20);
        $plist = TrainModel::where('status', 1)->order(['priority' => 'asc', 'id' => 'desc'])->page($ppage)->limit($psize)->select();
        page_result(0, "", [
            'plist'   => $plist,
            'pstatus' => $psize > count($plist) ? 'noMore' : 'more',
        ]);
    }

    /**
     * 参加列表
     */
    public function joinlist()
    {
        $ppage  = input('ppage/d', 1);
        $psize  = input('psize/d', 20);
        $userid = input('userid/d', 0);
        $map    = [
            ['status', '=', 1],
            ['user_id', '=', $userid],
        ];
        $plist  = TrainJoinModel::with(['train'])->where($map)->order(['id' => 'desc'])->page($ppage)->limit($psize)->select();
        page_result(0, "", [
            'plist'   => $plist,
            'pstatus' => $psize > count($plist) ? 'noMore' : 'more',
        ]);
    }

    /**
     * 参加培训
     */
    public function join()
    {
        $userid   = input('userid/d', 0);
        $train_id = input('train_id/d', 0);
        if (empty($userid) || empty($train_id)) {
            page_result(1, "信息不存在");
        }

        $check = TrainJoinModel::where('train_id',$train_id)->where('user_id',$userid)->find();
        if (!empty($check)) {
            page_result(1, "请勿重复报名");
        }

        TrainJoinModel::create([
            'train_id'    => $train_id,
            'user_id'     => $userid,
            'create_time' => time(),
        ]);

        page_result(0, "操作完成");
    }

    /**
     * 取消培训
     */
    public function deljoin()
    {
        $userid   = input('userid/d', 0);
        $id = input('id/d', 0);
        $info = TrainJoinModel::where('id',$id)->where('user_id',$userid)->find();
        if (empty($info)) {
            page_result(1, "信息不存在");
        }

        $info->delete();
        page_result(0, "操作完成");
    }
}