<?php

namespace app\admin\controller;

use app\admin\BaseController;
use app\common\model\Coach as CoachModel;
use app\common\model\Agent as AgentModel;

class Coach extends BaseController
{

    // 删除
    public function delCoach()
    {
        $idarr = input('idarr/a');
        CoachModel::whereIn('id', $idarr)->where('status', 1)->delete();
        exit(json_encode([
            'code' => 0,
            'msg'  => "",
        ]));
    }

    // 编辑&添加
    public function editCoach()
    {
        $id = input('id/d');
        if (empty($id)) {
            exit(json_encode([
                'code' => 1,
                'msg'  => '数据异常',
            ]));
        } else {
            $coach = CoachModel::find($id);
            if (empty($coach)) {
                exit(json_encode([
                    'code' => 1,
                    'msg'  => '数据异常',
                ]));
            }
            CoachModel::update([
                'id'        => $id,
                'title'     => input('title/s'),
                'content'   => input('content/s'),
                'num'       => input('num/d'),
                'status'    => input('status/d'),
                'coachtime' => input('coachtime/s'),
            ]);
        }
        exit(json_encode([
            'code' => 0,
        ]));
    }

    // 列表
    public function index()
    {
        $statuslist = CoachModel::$status;
        $agentlist  = AgentModel::order(['id' => 'desc'])->where('status',1)->select();
        return view('coach/coachlist', [
            'statuslist' => $statuslist,
            'agentlist' => $agentlist,
        ]);
    }

    public function coachForm()
    {
        $id         = input('id/d, 0');
        $coach      = CoachModel::findOrEmpty($id);
        $statuslist = CoachModel::$status;

        return view('coach/coachform', [
            'coach'      => $coach,
            'statuslist' => $statuslist,
        ]);
    }

    public function listCoach()
    {
        $limit    = input('limit');
        $page     = input('page');
        $map      = [];
        $keywords = input('keywords/s');
        if (!empty($keywords)) {
            $map[] = ['title', 'like', '%' . $keywords . '%'];
        }
        $status = input('status/d');
        if (!empty($status)) {
            $map[] = ['status', '=', $status];
        }
        $agentid = input('agentid/d');
        if (!empty($agentid)) {
            $map[] = ['agentid', '=', $agentid];
        }
        $list  = CoachModel::with('agent')->where($map)->order(['id' => 'desc'])->limit($limit)->page($page)->append(['status_text'])->select();
        $count = CoachModel::where($map)->count();
        if ($count == 0) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "未查询到数据",
            ]));
        }
        exit(json_encode([
            'code'  => 0,
            'msg'   => "",
            'count' => $count,
            'data'  => $list,
        ]));
    }
}