<?php
namespace app\admin\controller;

use app\model\Teams;
use support\Request;

class TeamController extends base
{
    public function index(Request $request) {
        $list = (new Teams())->teams();
        
        return $this->success($list);
    }

    public function save(Request $request) {
        $id = $request->post('id', 0);
        $name = $request->post('name','');
        $pid = $request->post('pid', 0);
        $rules = $request->post('rules', []);
        $admin_ids = $request->post('admins', []);
        $status = $request->post('status',1);

        if($id) {
            $item = Teams::where('id', $id)->find();
        }else{
            $item = new Teams();
        }
        if($pid) {
            $p =  Teams::where('id', $pid)->find();
            if(empty($p)) {
                return $this->error(2004, '上级分类不存在');
            }
        }

        $item->name = $name;
        $item->pid = $pid;
        $item->rules = $rules;
        $item->admin_ids = $admin_ids;
        $item->status = $status;
        $item->save();
        return $this->success(null);
    }

    public function move(Request $request) {
        $id = $request->post('id');
        $pid = $request->post('pid');
        $type = $request->post('type'); //inner  after  before

        $item = Teams::where('id', $id)->find();
        if($type == 'inner') {
            $item->pid = $pid;
            $item->sort = Teams::where('pid', $pid)->max('sort') + 1;
            $item->save();
        }else {
            $p = Teams::where('id', $pid)->find();
            $ps = Teams::where('pid', $p->pid)->where('id','<>', $id)->select();
            $aks = [];
            $newpid = $p->pid;
            foreach($ps as $_p) {
                if($type == 'before') {
                    if($_p->id == $pid) {
                        $aks[] = $id;
                    }
                }
                $aks[] = $_p->id;
                if($type == 'after') {
                    if($_p->id == $pid) {
                        $aks[] = $id;
                    }
                }
            }
            foreach($aks as $k=>$id) {
                Teams::where('id', $id)->update(['pid'=> $newpid, 'sort' => $k]);
            }
        }

        return $this->success(null);
    }

    public function del(Request $request) {
        $id = $request->post('id');

        Teams::where('id', $id)->update(['status'=>0]);
        return $this->success(null);
    }
}