<?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\model\Admin as AdminList;
use app\user\validate\AdminCheck;
use avatars\MDAvatars;
use Overtrue\Pinyin\Pinyin;
use think\exception\ValidateException;
use think\facade\Db;

class UserUser extends ApiController
{

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

    public function index()
    {
        $this->checkAuth();
        $param = get_params();
        $where = array();
        if (!empty($param['keyword'])) {
            $where[] = ['id|username|name|nickname|mobile|desc', 'like', '%' . $param['keyword'] . '%'];
        }
        $where[] = ['status', '<', 2];
        if (isset($param['status']) && $param['status']!='') {
            $where[] = ['status', '=', $param['status']];
        }
        if (!empty($param['type'])) {
            $where[] = ['type', '=', $param['type']];
        }
        if (!empty($param['did'])) {
            $department_array = get_department_son($param['did']);
            $where[] = ['did', 'in', $department_array];
        }
        $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
        $admin = AdminList::where($where)
            ->field(['id', 'username', 'name', 'email', 'mobile', 'sex', 'nickname', 'thumb', 'did', 'position_id', 'type', 'entry_time', 'last_login_time', 'last_login_ip', 'status'])
            ->order('id desc')
            ->paginate($rows, false, ['query' => $param])
            ->each(function ($item, $key) {
                $item->department = Db::name('Department')->where(['id' => $item->did])->value('title');
                $item->position = Db::name('Position')->where(['id' => $item->position_id])->value('title');
                $item->entry_time = empty($item->entry_time) ? '-' : date('Y-m-d', $item->entry_time);
                $item->last_login_time = empty($item->last_login_time) ? '-' : date('Y-m-d H:i', $item->last_login_time);
                $item->last_login_ip = empty($item->last_login_ip) ? '-' : $item->last_login_ip;
            });
        $this->apiSuccess('获取成功', $admin);
    }

    //添加
    public function add()
    {
        $this->checkAuth();
        $param = get_params();
        if (empty($param['name'])) {
            $this->apiError("请输入员工名称");
        }
        if (empty($param['sex'])) {
            $this->apiError("请选择性别");
        }
        if (empty($param['entry_time'])) {
            $this->apiError("请选择入职时间");
        }
        $param['entry_time'] = strtotime($param['entry_time']);
        $param['nickname'] = $param['name'];
        $pinyin = new Pinyin();
        $username = $pinyin->name($param['name'], PINYIN_UMLAUT_V);
        $param['username'] = implode('', $username);
        if (!empty($param['id']) && $param['id'] > 0) {
            $count = Db::name('Admin')->where([['username','=',$param['username']],['id','<>',$param['id']],['status','>=',0]])->count();
            if ($count > 0) {
                $count_e = Db::name('Admin')->where([['username', 'like', $param['username'].'%']])->count();
                $param['username'] = implode('', $username) . $count_e;
            }
            try {
                validate(AdminCheck::class)->scene('edit')->check($param);
            } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                $this->apiError($e->getError());
            }
            // 启动事务
            Db::startTrans();
            try {
                Db::name('Admin')->where(['id' => $param['id']])->strict(false)->field(true)->update($param);
                if (!isset($param['thumb']) || $param['thumb'] == '') {
                    $char = mb_substr($param['name'], 0, 1, 'utf-8');
                    Db::name('Admin')->where('id', $param['id'])->update(['thumb' => $this->to_avatars($char)]);
                }
                add_log('edit', $param['id'], $param);
                //清除菜单\权限缓存
                clear_cache('adminMenu');
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->apiError($e->getMessage());
            }
        } else {
            $count = Db::name('Admin')->where([['username', 'like', $param['username'].'%']])->count();
            if ($count > 0) {
                $param['username'] = implode('', $username) . $count;
            }
            try {
                validate(AdminCheck::class)->scene('add')->check($param);
            } catch (ValidateException $e) {
                $this->apiError($e->getError());
            }
            $param['salt'] = set_salt(20);
            $param['pwd'] = set_password($param['reg_pwd'], $param['salt']);
            // 启动事务
            Db::startTrans();
            try {
                $uid = Db::name('Admin')->strict(false)->field(true)->insertGetId($param);
                if (!isset($param['thumb']) || $param['thumb'] == '') {
                    $char = mb_substr($param['name'], 0, 1, 'utf-8');
                    Db::name('Admin')->where('id', $uid)->update(['thumb' => $this->to_avatars($char)]);
                }
                add_log('add', $uid, $param);
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->apiError($e->getMessage());
            }
        }
        $this->apiSuccess('操作成功');
    }

    //生成头像
    public function to_avatars($char)
    {
        $defaultData = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
            'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'S', 'Y', 'Z',
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖', '拾',
            '一', '二', '三', '四', '五', '六', '七', '八', '九', '十');
        if (isset($char)) {
            $Char = $char;
        } else {
            $Char = $defaultData[mt_rand(0, count($defaultData) - 1)];
        }
        $OutputSize = min(512, empty($_GET['size']) ? 36 : intval($_GET['size']));

        $Avatar = new MDAvatars($Char, 256, 1);
        $avatar_name = '/avatars/avatar_256_' . set_salt(10) . time() . '.png';
        $path = get_config('filesystem.disks.public.url') . $avatar_name;
        $res = $Avatar->Save('.' . $path, 256);
        $Avatar->Free();
        return $path;
    }

    //查看
    public function view()
    {
        $this->checkAuth();
        $id = get_params("id");
        if (empty($id)) {
            $this->apiError("请选择员工");
        }
        $detail = get_admin($id);
        if (empty($detail['id'])) {
            $this->apiError("员工不存在");
        }
        $detail['entry_time'] = date('Y-m-d', $detail['entry_time']);
        $detail['update_time'] = date('Y-m-d H:i:s', $detail['update_time']);
        unset($detail['pwd'], $detail['salt'], $detail['reg_pwd']);
        $this->apiSuccess('操作成功', $detail);
    }

    //禁用,恢复
    public function set()
    {
        $this->checkAuth();
        $type = get_params("type");
        $ids = get_params("ids");
        $idArray = explode(',', $ids);
        $list = [];
        foreach ($idArray as $key => $val) {
            if ($val == 1) {
                continue;
            }
            $list[] = [
                'status' => $type,
                'id' => $val,
                'update_time' => time(),
            ];
        }
        try {
            foreach ($list as $key => $v) {
                if (Db::name('Admin')->update($v) !== false) {
                    if ($type == 0) {
                        add_log('disable', $v['id']);
                    } else if ($type == 1) {
                        add_log('recovery', $v['id']);
                    }
                }
            }
        } catch (\Exception $e) {
            $this->apiError($e->getMessage());
        }
        $this->apiSuccess('操作成功');
    }

}
