<?php

namespace app\adminapi\controller;

use app\adminapi\BaseController;
use support\Request;
use think\facade\Db;

class AdminUserController extends BaseController
{
    public function getAdminUserList(Request $request)
    {
        $param = $request->post();
        $page       = isset($param['page']) ? $param['page'] : 1;
        $pageSize   = isset($param['pageSize']) ? $param['pageSize'] : 10;
        $search     = isset($param['search']) ? $param['search'] : [];

        $where = [
        ];

        $list = Db::name('admin')
            ->where($where)
            ->order('id', 'asc')
            ->page($page, $pageSize)
            ->select()
            ->toArray();

        $total = Db::name('admin')
            ->where($where)
            ->count();

        foreach($list as $key => $val){
            unset($list[$key]['password']);
            if($val['login_time']>0){

            }
            $list[$key]['login_time'] = $val['login_time']?date('Y-m-d H:i:s',$val['login_time']):'';
        }

        $result = [
            'list' => $list,
            'total' => $total
        ];

        return $this->Success($result);
    }

    public function addAdminUser(Request $request){
        $params = $request->post();
        
        // 檢查帳號是否重複
        $is_exist = Db::name('admin')
        ->where('username',$params['username'])
        ->find();

        if($is_exist){
            return $this->Error('帳號已存在');
        }

        $data = [
            'username' => $params['username'],
            'password' => password_hash($params['password'], PASSWORD_DEFAULT),
            'is_main' => 0,
            'status' => 1,
            'create_time' => date('Y-m-d H:i:s',time())
        ];
        
        try{
            Db::name('admin')->insert($data);

            AdminLog( $this->uid , '新增管理員 ' . $data['username']);

            return $this->Success('操作成功');
        }catch(\Exception $e){
            AdminLog( $this->uid , '新增管理員 ' . $data['username'] . ' 失敗');
            
            return $this->Error('操作失敗:'. $e->getMessage());                
        }
    }

    public function deleteAdminUser(Request $request){
        $id = $request->get('id');

        try{
            $admin_name = getNameById('admin','username',$id);

            $result = Db::name('admin')
            ->where('id',$id)
            ->delete();
    
            AdminLog($this->uid, '刪除管理員 '. $admin_name);
            return $this->Success('操作成功');    
        }catch(\Exception $e){
            AdminLog($this->uid, '刪除管理員'.$admin_name.'失敗');
            return $this->Error('操作失敗');                
        }
    }

    public function getAdminUser(Request $request){
        $id = $request->get('id');

        $user = Db::name('admin')
        ->where('id',$id)
        ->find();

        if(!$user){
            return $this->Error('用戶不存在');
        }

        unset($user['password']);

        $result = $user;

        return $this->Success($result);
    }

    public function updateAdminUser(Request $request){
        $params = $request->post();
        $username = $params['username'];
        unset($params['username']);
        
        $data = [
            'is_main' => 0,
            'status' => 1,
            'update_time' => date('Y-m-d H:i:s',time())
        ];

        if($params['password']){
            $data['password'] = password_hash($params['password'], PASSWORD_DEFAULT);
        }

        try{
            $result = Db::name('admin')
            ->where('id',$params['id'])
            ->update($data);

            AdminLog($this->uid, '修改管理員 ' . $username);
    
            return $this->Success('操作成功');
        }catch(\Exception $e){

            AdminLog($this->uid, '修改管理員 ' . $username . '失敗');
            
            return $this->Error('操作失敗:'. $e->getMessage());                
        }
    }

    public function getAdminLog(Request $request){
        $param = $request->post();

        $page       = isset($param['page']) ? $param['page'] : 1;
        $pageSize   = isset($param['pageSize']) ? $param['pageSize'] : 10;
        $search     = isset($param['search']) ? $param['search'] : [];

        $where = [
        ];

        if(isset($search['keyword']) && $search['keyword']){
            $where[] = ['content', 'like', '%'.$search['keyword'].'%'];
        }

        $list = Db::name('admin_log')
            ->where($where)
            ->order('id', 'desc')
            ->page($page, $pageSize)
            ->select()
            ->toArray();

        $total = Db::name('admin_log')
            ->where($where)
            ->count();

        // foreach($list as $key => $val){
        // }

        $result = [
            'list' => $list,
            'total' => $total
        ];

        return $this->Success($result);
    }


    public function getCurrentAdminUser(Request $request){

        $user = Db::name('agent_user')
        ->where('agent_id',$this->agent_id)
        ->where('id',$this->uid)
        ->find();

        if(!$user){
            return $this->Error('用戶不存在');
        }

        $result = $user;
        
        return $this->Success($result);
    }

}
