<?php
/**
 * Copyright: Shanghai NuLang Network Technology Co., Ltd.
 * Faith: Some things do not need others to understand.
 * Project: CoverCMS <Your world, your ambition>
 * License: http://www.svipplus.cn/license/
 * Author: The Rain° <rain@svipplus.cn>
 * File: ManagerController.php
 * Time: 17:35
 */

namespace app\dash\controller;


use app\common\controller\BaseController;
use app\common\toolKit\CacheKit;
use app\common\toolKit\CommonKit;
use think\Db;

/**
 * Class ManagerController
 * @package app\dash\controller
 */
class ManagerController extends BaseController
{
    public function indexAction()
    {
		$isPeak = false;
        $user = $this->getUser();
        if (intval($user['id']) === 1){
            $isPeak = true;
        }
        if (request()->isPost()) {
            $user = $this->getUser();
            if (intval($user['id']) !== 1) {
                $total = 1;
                $items = [];
                $currentUser = Db::name('manager')->where('id', $user['id'])->find();
                if ($currentUser) {
                    $items[1] = $currentUser;
                }
            } else {
                $items = cache('managers');
                $total = count($items);
                foreach ($items as &$item) {
                    $editUrl = url('edit', ['id' => $item['id']]);
                    $deleteUrl = url('delete', ['id' => $item['id']]);
                    $item['actions'] = '';
                    $item['actions'] .= '<a class="cv-btn primary" href="javascript:openDialog(' . '\'编辑管理员\',' . '\'' . $editUrl . '\',' . '\'520px\',' . '\'330px\'' . ')">编辑</a>';
                    if (intval($item['id']) !== 1) {
                        $item['actions'] .= '&nbsp;&nbsp;' .
                            '<a class="cv-btn red" href="javascript:deleteManagerData(\'' . $deleteUrl . '\')">删除</a>';
                    }
                    $item['order'] = '<input style="width:35px;" type="text" name="cv[manager][' . $item['id'] . ']" value="' . $item['weight'] . '" />';
                }
            }
            return json(['total' => $total, 'rows' => array_values($items)]);
        }
		$this->assign([
            'is_peak'=>$isPeak
        ]);
        return $this->fetch();
    }

    public function loginAction()
    {
        if (request()->isPost()) {
            if (!input('?post.username') || !input('?post.plain_password')) {
                return json(['success' => false, 'message' => '账号、密码不能为空']);
            }
            $username = trim(input('post.username'));
            $item = Db::name('manager')->where('username', $username)->find();
            if (!$item || !password_verify(config('cloud.secret') . input('post.plain_password'), $item['password'])) {
                return json(['success' => false, 'message' => '账号或密码错误']);
            }
            $storage = serialize([
                'id' => $item['id'],
                'username' => $item['username'],
                'true_name' => $item['true_name'],
//                'last_login_at' => $item['last_login_at'],
//                'last_login_ip' => $item['last_login_ip']
            ]);
            session('manager', $storage);
            cache('manager', $storage);
            return json(['success' => true, 'message' => lang('Success')]);
        }
        $this->assign('success_url', request()->root() . '/dash');
        return $this->fetch();
    }

    public function logoutAction()
    {
        cache('manager',null);
        session('manager', null);
        return json(['success'=>true, 'meesgae'=>'成功退出','red'=>url('login')]);
    }

    public function newAction()
    {
        if (request()->isPost()) {
            $dataFromPost = request()->post('cv/a', null);
            if (is_null($dataFromPost) || !is_array($dataFromPost)) {
                return json(['success' => false, 'message' => lang('Failure')]);
            }
            if (CommonKit::isMissing(['username', 'plain_password'], $dataFromPost, true)) {
                return json(['success' => false, 'message' => lang('Failure')]);
            }
            $dataFromPost['username'] = trim($dataFromPost['username']);
            $dataFromPost['password'] = trim($dataFromPost['plain_password']);
            $uniqueUsername = Db::name('manager')->where('username', $dataFromPost['username'])->find();
            if (!$uniqueUsername) {
                return json(['success' => false, 'message' => '该账号已被使用，请换一个']);
            }
            if (strlen($dataFromPost['password']) < 5) {
                return json(['success' => false, 'message' => '请输入5位或以上长度密码']);
            }
            $dataFromPost['password'] = password_hash(config('cloud.secret') . $dataFromPost['password'], PASSWORD_BCRYPT);
            $lastInsertedItem = Db::name('manager')->insertGetId($dataFromPost);
            if (!$lastInsertedItem) {
                return json(['success' => false, 'message' => lang('Failure')]);
            }
            CacheKit::updateManagerCache();
            return json(['success' => true, 'message' => lang('Success')]);
        }
        return $this->fetch();
    }

    public function editAction()
    {
        $id = input('?get.id') ? input('get.id') : input('post.id', 0);
        if (intval($id) === 0) {
            return json(['success' => false, 'message' => lang('Failure')]);
        }
        if (request()->isPost()) {
            $dataFromPost = request()->post('cv/a', null);
            if (is_null($dataFromPost) || !is_array($dataFromPost)) {
                return json(['success' => false, 'message' => lang('Failure')]);
            }
            $plainPassword = trim(input('post.plain_password'));
            if (!empty($plainPassword)) {
                if (strlen($plainPassword) < 5) {
                    return json(['success' => false, 'message' => '请输入5位或以上长度密码']);
                } else {
                    $dataFromPost['password'] = password_hash(config('cloud.secret') . $plainPassword, PASSWORD_BCRYPT);
                }
            }
            Db::name('manager')->where('id', $id)->update($dataFromPost);
            CacheKit::updateManagerCache();
            return json(['success' => true, 'message' => lang('Success')]);
        }
        $item = Db::name('manager')->where('id', $id)->find();
        if (!$item) {
            return json(['success' => false, 'message' => lang('Failure')]);
        }
        $this->assign([
            'item' => $item
        ]);
        return $this->fetch();
    }

    public function deleteAction()
    {
        $id = intval(input('?get.id') ? input('get.id') : input('post.id', 0));
        if ($id === 0 || $id === 1) {
            return json(['success' => false, 'message' => lang('Failure')]);
        }
        $rst = Db::name('manager')->where('id', $id)->delete();
        if (!$rst) {
            return json(['success' => false, 'message' => lang('Failure')]);
        }
        return json(['success' => true, 'message' => lang('Success')]);
    }

    public function orderAction()
    {
        $dataFromPost = request()->post('cv/a', null);
        $needOrders = $dataFromPost['manager'];
        foreach ($needOrders as $key => $value) {
            Db::name('manager')->where('id', $key)->update(['weight' => abs(intval($value))]);
        }
        return json(['success' => true, 'message' => lang('Success')]);
    }
}