<?php
namespace App\Admin\Controllers;

use Dcat\Admin\Http\Controllers\UserController as BaseUserController;
use Dcat\Admin\Grid;
use Dcat\Admin\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use App\Models\adminUser;

class UserController extends BaseUserController
{
    // 添加同步方法
    public function sync(Request $request)
    {
        set_time_limit(300);

        $db1 = DB::connection('mysql');
        $db2 = DB::connection('sqlsrv');
        $num = 500;

        $roleId = $db1->table('admin_roles')
        ->where('name', 'DHH')
        ->value('id');
 
        if (empty($roleId)) {
            return response()->json([
                'status'  => false,
                'message' => '订货会权限未设置-DHH'
            ]);
        }

        // 获取MySQL用户表数据(排除admin用户)
        $excludedUsers = $db1->table('admin_users')
        ->select('username', 'name')
        ->where('username', '<>', 'admin')
        ->get()
        ->map(function($item) {
            return (array)$item; // 确保转换为关联数组
        })->toArray();

        // 拼接 VALUES 字符串
        $values = collect($excludedUsers)
        ->map(fn($user) => "'{$user['username']}'")
        ->implode(',');
        if ($values=='') {
            $values="'1'";
        }
        // SQL Server客户表查询(排除已存在用户)
        $data = $db2->table('KEHU')
            ->select('KHDM', 'KHMC')
            ->whereRaw("ISNULL(KHXZ,0)<>0")
            ->whereRaw("KHDM NOT IN({$values})")
            ->limit($num)
            ->get()
            ->toArray();
        try {
            $users=array();
            foreach ($data as $key => $value) {
                $user = adminUser::create([
                    'username' => $value->KHDM,
                    'name' => $value->KHMC,
                    'password' => bcrypt($value->KHDM),
                ]);
                // 分配默认角色
                if (!$user->roles()->where('name', 'DHH')->exists()) {
                    $user->roles()->attach($roleId); // 2为默认角色ID
                }
                $users[] = $user;
            }
            $msg='继续同步';
            if (count($users)<$num) {
                $msg='同步完成';
            }
            return response()->json([
                'status' => true,
                'message' => $msg.'，共处理'.count($users).'条记录'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status'  => false,
                'message' => '同步失败: '.$e->getMessage()
            ]);
        }
    }

    // 重写grid方法添加按钮
    protected function grid()
    {
        $grid = parent::grid();
        
        // 在表格右上角添加工具栏按钮
        $grid->tools(function ($tools) {
            if (Admin::user()->can('users.sync')) {
                $url = admin_url('auth/users/sync');
                $tools->append(<<<HTML
                <style>
                    #body{
                        position:fixed;
                        top:0%;
                        z-index:1199;
                        width:100%;
                        height:100%;
                        margin:auto auto;
                    }
                    #loading{
                        position:fixed;
                        top:50%;
                        z-index:1200;
                        background:url(/load.gif) top center no-repeat;
                        width:100%;
                        height:140px;
                        margin:auto auto;
                    }
                </style>
                <button class="btn btn-primary btn-outline sync-btn" 
                        data-url="{$url}"
                        style="margin-right:10px">
                    <i class="feather icon-refresh-cw"></i> 同步用户
                </button>
                <script src="/js/admin.js"></script>
                HTML);
            }
        });

        return $grid;
    }
}