<?php

namespace app\admin\controller;

use app\admin\BaseController;
use app\common\model\TrainJoin as TrainJoinModel;

class Trainjoin extends BaseController
{
    public function index()
    {
        return view('trainjoin/index');
    }

    public function list()
    {
        $limit = input('limit');
        $page  = input('page');

        $where    = [];
        $keywords = input('keywords', '');
        if (!empty($keywords)) {
            $where[] = ['t.title|u.nickname|u.mobile', 'like', "%{$keywords}%"];
        }
        $status = input('status', 0);
        if (!empty($status)) {
            $where[] = ['tj.status', '=', $status];
        }

        $list  = TrainJoinModel::alias('tj')
            ->field(['tj.*', 't.title', 'u.nickname', 'u.mobile'])
            ->leftJoin('user u', 'u.id = tj.user_id')
            ->leftJoin('train t', 't.id = tj.train_id')
            ->where($where)
            ->limit($limit)->page($page)->select()->append(['status_text']);
        $count = TrainJoinModel::alias('tj')
            ->field(['tj.*', 't.title', 'u.nickname', 'u.mobile'])
            ->leftJoin('user u', 'u.id = tj.user_id')
            ->leftJoin('train t', 't.id = tj.train_id')
            ->where($where)->count();
        if ($count == 0) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "未查询到数据",
            ]));
        }
        exit(json_encode([
            'code'  => 0,
            'msg'   => "",
            'count' => $count,
            'data'  => $list,
        ]));
    }

    public function field()
    {
        $id   = input('id/d');
        $info = TrainJoinModel::find($id);
        if ($info == null) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "数据不存在",
            ]));
        } else {
            $info->save([
                input('field/s') => input('value/s'),
            ]);
        }
        exit(json_encode([
            'code' => 0,
        ]));
    }

    public function del()
    {
        $id     = input('id/d');
        $info   = TrainJoinModel::where('id', $id)->select();
        $result = $info->delete();
        if ($result) {
            exit(json_encode([
                'code' => 0,
                'msg'  => "",
            ]));
        }
        exit(json_encode([
            'code' => 1,
            'msg'  => "删除失败，请稍后重试",
        ]));
    }

    public function status()
    {
        $idarr  = input('idarr/a');
        $status = input('status/d');
        TrainJoinModel::whereIn('id', $idarr)->update(['status' => $status]);

        exit(json_encode([
            'code' => 0,
            'msg'  => "",
        ]));
    }
}
