<?php
// +----------------------------------------------------------------------
// | A3Mall
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzncit <158373108@qq.com>
// +----------------------------------------------------------------------

namespace app\adminapi\service;

use app\common\exception\BaseException;
use app\common\library\jwt\Token;
use app\adminapi\model\Admin as AdminModel;
use app\common\library\utils\Tool;
use app\common\model\AdminLog as AdminLogModel;
use app\common\library\utils\Hash;
use app\adminapi\service\Purview as PurviewService;
use app\common\model\AdminManage as AdminManageModel;
use app\common\service\Users as UsersService;

/**
 * @package app\adminapi\service
 * @class Admin
 * @author xzncit 2023-09-04
 */
class Admin {

    /**
     * @param $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getList($params){
        $array           = [];
        $array["list"]   = [];
        $fields          = ["title",["title"=>$params["keywords"]??'']];
        $array["total"]  = AdminModel::withSearch(...$fields)->withJoin("manage")->count();
        $result          = AdminModel::withSearch(...$fields)->withJoin("manage")->order("admin.id","desc")->page($params["current"]??1,$params["size"]??10)->select()->toArray();
        foreach($result as $key=>$value){
            $array["list"][$key] = $value;
        }

        return $array;
    }

    /**
     * 详情
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function detail($id){
        $array             = [];
        $array["purview"]  = AdminManageModel::where("status",1)->select()->toArray();
        $array["row"]      = AdminModel::where("id",$id??0)->find();
        if(!empty($array["row"])){
            $array["row"]["password"] = "";
            $array["row"]["confirm_password"] = "";
        }

        return $array;
    }

    /**
     * 添加/修改
     * @param $data
     * @return AdminModel|bool|\think\Model
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function save($data){
        if(empty($data["id"])){
            if(empty($data["password"])){
                throw new BaseException("请填写密码",0);
            }else if(empty($data["confirm_password"])){
                throw new BaseException("请填写确认密码",0);
            }else if($data["password"] != $data["confirm_password"]){
                throw new BaseException("您输入的两次密码不致。",0);
            }

            if(AdminModel::where("username",$data["username"])->count()){
                throw new BaseException("用户名已存在",0);
            }

            $data["salt"]        = Tool::getRands(5);
            $data["password"]    = Hash::md5($data["password"],$data["salt"]);
            $data["create_time"] = time();
            $data["update_time"] = time();
            $data["login_time"]  = time();
            return AdminModel::create($data);
        }

        $user = AdminModel::where("id",$data["id"])->find();
        if(empty($user)){
            throw new BaseException("您要修改的内容不存在",0);
        }

        $oldUser = AdminModel::where("username",$data["username"])->find();
        if(!empty($oldUser) && $user["id"] != $oldUser["id"]){
            throw new BaseException("用户名已存在",0);
        }

        if(!empty($data["password"]) || !empty($data["confirm_password"])){
            if($data["password"] != $data["confirm_password"]){
                throw new \Exception("您输入的两次密码不致。",0);
            }

            $data["salt"]        = Tool::getRands(5);
            $data["password"]    = Hash::md5($data["password"],$data["salt"]);
            return AdminModel::where("id",$data["id"])->save($data);
        }

        return AdminModel::where("id",$data["id"])->withoutField(["password","confirm_password"])->save($data);
    }

    /**
     * 修改密码
     * @param $data
     * @return bool
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function password($data){
        $user = AdminModel::where("id",UsersService::get("id",0))->find();
        if(empty($user)){
            throw new BaseException("您要修改的用户不存在",0);
        }

        if(empty($data["password"])){
            throw new BaseException("请输入密码",0);
        }else if(empty($data["confirm_password"])){
            throw new BaseException("请输入确认密码",0);
        }

        if($data["password"] != $data["confirm_password"]){
            throw new BaseException("您输入的两次密码不致。",0);
        }

        $data["salt"]        = Tool::getRands(5);
        $data["password"]    = Hash::md5($data["password"],$data["salt"]);
        return AdminModel::where("id",$user["id"])->save([
            "password"  => $data["password"],
            "salt"      => $data["salt"]
        ]);
    }

    /**
     * @param $id
     * @return bool
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function delete($id){
        $row = AdminModel::where("id",$id)->find();
        if(empty($row)){
            throw new BaseException("您要查找的内容不存在",0);
        }

        if($row["id"] == 1){
            throw new BaseException("该用户为系统用户,不允许删除",0);
        }

        return AdminModel::where("id",$id)->delete();
    }

    /**
     * 登录
     * @param array $params
     * @return array
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function login($params=[]){
        $admin = AdminModel::where("username",$params["username"])->find();
        if(empty($admin)){
            throw new BaseException("您输入的用户不存在",0);
        }

        if($admin["password"] != Hash::md5($params["password"],$admin["salt"])){
            throw new BaseException("您输入的密码错误！",0);
        }

        if($admin["status"] == 0){
            AdminLogModel::write($admin["id"],"登录操作","状态：用户 [ " . $admin['username'] . " ] 帐号禁止使用");
            throw new BaseException("您的帐号已被禁止使用！", 0);
        }

        return [
            "token"     => Token::set("id",$admin["id"]),
            "username"  => $admin["username"]
        ];
    }

}