<?php
/**
 * @copyright Copyright (c) 2021 勾股工作室
 * @license https://opensource.org/licenses/GPL-3.0
 * @link https://www.gougucms.com
 */

declare (strict_types = 1);

namespace app\api\controller;

use app\api\ApiController;
use app\api\middleware\Auth;
use app\user\validate\PositionCheck;
use think\exception\ValidateException;
use think\facade\Db;

class UserPosition extends ApiController
{

    protected $middleware = [
    	Auth::class => ['except' => []]
    ];

    public function index()
    {
        $this->checkAuth();
        $list = Db::name('Position')->where('status', 1)->where('id', '>', 1)->order('create_time asc')->select()->toArray();
        foreach ($list as &$val) {
            $groupId = Db::name('PositionGroup')->where(['pid' => $val['id']])->column('group_id');
            $groupName = Db::name('AdminGroup')->where('id', 'in', $groupId)->column('title');
            $val['group_id'] = $groupId;
            $val['group_name'] = implode(',', $groupName);
        }
        $this->apiSuccess('获取成功', $list);  
    }

    public function group()
    {
        $group = Db::name('AdminGroup')->where('status', 1)->where('id', '>', 1)->order('create_time asc')->field(['id', 'title'])->select()->toArray();
        $this->apiSuccess('获取成功', $group);  
    }

    //添加&编辑
    public function add()
    {
        $this->checkAuth();
        $param = get_params();
        if (!empty($param['id']) && $param['id'] > 0) {
            try {
                validate(PositionCheck::class)->scene('edit')->check($param);
            } catch (ValidateException $e) {
                $this->apiError($e->getError());
            }
            // 启动事务
            Db::startTrans();
            try {
                Db::name('Position')->where(['id' => $param['id']])->strict(false)->field(true)->update($param);
                Db::name('PositionGroup')->where(['pid' => $param['id']])->delete();
                foreach ($param['group_id'] as $k => $v) {
                    $data[$k] = [
                        'pid' => $param['id'],
                        'group_id' => $v,
                        'create_time' => time(),
                    ];
                }
                Db::name('PositionGroup')->strict(false)->field(true)->insertAll($data);
                add_log('edit', $param['id'], $param);
                //清除菜单\权限缓存
                clear_cache('adminMenu');
                clear_cache('adminRules');
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->apiError($e->getError());
            }
        } else {
            try {
                validate(PositionCheck::class)->scene('add')->check($param);
            } catch (ValidateException $e) {
                $this->apiError($e->getError());
            }
            // 启动事务
            Db::startTrans();
            try {
                $uid = Db::name('Position')->strict(false)->field(true)->insertGetId($param);
                foreach ($param['group_id'] as $k => $v) {
                    $data[$k] = [
                        'pid' => $uid,
                        'group_id' => $v,
                        'create_time' => time(),
                    ];
                }
                Db::name('PositionGroup')->strict(false)->field(true)->insertAll($data);
                add_log('add', $uid, $param);
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->apiError($e->getError());
            }
        }
        $this->apiSuccess('操作成功');
    }

    //删除
    public function delete()
    {
        $this->checkAuth();
        $id = get_params("id");
        if (empty($id)) {
            $this->apiError("请选择岗位");
        }
        if ($id == 1) {
            $this->apiError("超级岗位不能删除");
        }
        $data['status'] = '-1';
        $data['id'] = $id;
        $data['update_time'] = time();
        if (Db::name('Position')->update($data) !== false) {
            add_log('delete', $id);
            return to_assign(0, "删除成功");
        } else {
            $this->apiError("删除失败");
        }
    }
}
