<?php

namespace App\Jobs\OpenWork\Contact;

use App\Servers\DB\DbService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\OpenWork\Contact\User as Usermodel;
use App\Models\OpenWork\Contact\UserDepart as UserDepartmodel;
use Illuminate\Support\Facades\DB;
use App\Facades\Servers\Logs\Log;
use App\Facades\Servers\Wechat\OpenWork;
use App\Models\OpenWork\Contact\UserActiveLog;
use App\Models\OpenWork\job\Records;
use App\Servers\OpenWork\External\ContactService;

/**
 * 部门成员队列
 * @author 唐远望
 * @date 2025-04-09
 * @version 1.0
 */


class UserJobs implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $userData;
    protected $Records;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(array $userData)
    {
        $this->userData = $userData;
    }


    public function getCorpId()
    {
        return $this->userData['authCorpId'] ?? null;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $corpId = $this->userData['authCorpId'];
        (new DbService())->getConnectionNameByCorpId($corpId);

        try {
            $userData = $this->userData;
            // 创建任务记录
            $this->Records = Records::create([
                'job_id' => $this->userData['authCorpId'] . '_UserJobs',
                'name' => static::class,
                'payload' => json_encode($this->userData),
                'status' => 'processing',
                'started_at' => now()
            ]);
            //处理明文用户ID
            $userData['userid'] = $this->handle_user_info($userData['authCorpId'], $userData['userid']);

            //查询用户是否存在
            $result = $this->get_one($userData['authCorpId'], $userData['userid']);
            if (!$result) {
                //执行添加用户
                $res = $this->add_user($userData);
                //更新用户授权状态
                // $this->update_wxwork_user_status($userData['authCorpId'], $userData['userid']);
            } else {
                //执行更新用户
                $wheres = [
                    'corpid' => $userData['authCorpId'],
                    'userid' => $userData['userid']
                ];
                //先初始开通信息，在通过激活记录更新
                $userData['is_open_interoperability'] ='0';
                $userData['is_open_foundation'] ='0';
                $userData['is_external_contact_permissions'] ='0';
                //更新用户信息
                $department = isset($userData['department']) ? $userData['department'] : [];
                $this->update_user($wheres, $userData, $department);
                //更新用户授权状态
                // $this->update_wxwork_user_status($userData['authCorpId'], $userData['userid']);
            }
            //更新激活历史记录
            $this->activate_information($userData['authCorpId'], $userData['userid']);
            //删除任务记录
            $this->Records->delete();
        } catch (\Exception $e) {
            // 更新任务状态为失败
            $this->Records->update([
                'status' => 'failed',
                'exception' => $e->getMessage(),
                'started_at' => now()
            ]);
            Log::info('job_error', '部门成员队列失败-异常原因', ['error' => $e->getMessage()]);
        }
    }

    /**
     * 查询用户
     */

    public function get_one($authCorpId, $userid)
    {
        // 获取实例

        $data = Usermodel::where([['corpid', '=', $authCorpId], ['userid', '=', $userid]])->first(['name', 'userid', 'corpid']);

        // 返回结果
        if ($data) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 查询成员授权状态
     * @author 唐远望
     * @date 2025-04-13
     * @version 1.0
     * @param string $authCorpId 授权企业ID
     * @param string $userid 用户ID
     * @return bool
     */
    public function update_wxwork_user_status($authCorpId, $userid)
    {
        // 获取实例
        $app            = OpenWork::getWork($authCorpId);
        //获取成员授权状态
        $result = $app->user->checkMemberAuth($userid);
        if (!$result)  return json_send(['code' => 'error', 'msg' => '获取失败']);
        // 错误提示
        if ($result['errcode']) {
            Log::info('job_error', '获取成员授权状态失败', ['error' => $result]);
            return false;
        }
        // 获取实例
        $user_info = Usermodel::where([['corpid', '=', $authCorpId], ['userid', '=', $userid]])->first();
        // 返回结果
        if ($user_info) {
            $user_info->is_member_auth = $result['is_member_auth'];
            $user_info->save();
        }
    }

    /**
     * 添加用户
     * @author 唐远望
     * @date 2025-04-09
     * @version 1.0
     * @param array $userData 用户信息
     * @return bool
     */

    public function add_user($userData)
    {

        $nowdate = time();
        // 获取实例
        $user_info = [
            'corpid' => $userData['authCorpId'],
            'userid' => $userData['userid'],
            'status' => $userData['status'], //激活状态: 1=已激活，2=已禁用，4=未激活，5=退出企业
            'avatar' => $userData['avatar'],
            'gender' => $userData['gender'],
            'main_department' => isset($userData['main_department']) ? $userData['main_department'] : 0,
            'insert_time' => $nowdate,
            'update_time' => $nowdate,
        ];

        DB::connection('company')->beginTransaction();
        try {
            //添加部门关系信息
            $department_list = isset($userData['department_list']) ? $userData['department_list'] : [];
            if (count($department_list) > 0) {
                foreach ($department_list as $key => $value) {
                    $user_depart_info = [
                        'corpid' => $userData['authCorpId'],
                        'userid' => $userData['userid'],
                        'department_id' => $value
                    ];

                    $user_depart_info_log = UserDepartmodel::where([['corpid', '=', $userData['authCorpId']], ['userid', '=', $userData['userid']], ['department_id', '=', $value]])->first();

                    if (!$user_depart_info_log) {
                        UserDepartmodel::insert($user_depart_info);
                    }
                }
            }
            //添加用户
            $user_id = Usermodel::insertGetId($user_info);
            DB::connection('company')->commit();
            // 成功处理...
            return true;
        } catch (\Exception $e) {
            DB::connection('company')->rollBack();
            // 错误处理...
            return false;
        }
    }


    /**
     * 处理明文用户信息
     * @author 唐远望
     * @date 2025-05-13
     * @version 1.0
     * @param array $userData 用户信息
     */
    public function handle_user_info($corpid, $user_id)
    {
        $user_config_list = (new ContactService())->get_external_contact_batchget_user_list_by_data($corpid, [$user_id]);
        if (!empty($user_config_list)) {
            return $user_config_list[0];
        } else {
            return $user_id;
        }
    }

    /**
     * 更新用户信息
     * @author 唐远望
     * @date 2025-04-09
     * @version 1.0
     * @param array $userData 用户信息
     * @return bool
     */

    public function update_user($wheres, $userData, $department_list)
    {
        $nowdate = time();
        // 获取实例
        $user_info = [
            'status' => $userData['status'], //激活状态: 1=已激活，2=已禁用，4=未激活，5=退出企业
            'update_time' => $nowdate,
            'avatar' => $userData['avatar'],
            'gender' => $userData['gender'],
            'main_department' => isset($userData['main_department']) ? $userData['main_department'] : 0,
            'is_open_interoperability'=>isset($userData['is_open_interoperability']) ? $userData['is_open_interoperability'] : 0,
            'is_open_foundation' =>isset($userData['is_open_foundation']) ? $userData['is_open_foundation'] : 0,
            'is_external_contact_permissions'=> isset($userData['is_external_contact_permissions']) ? $userData['is_external_contact_permissions'] : 0,
        ];

        DB::connection('company')->beginTransaction();

        try {
            //添加部门关系信息
            if (count($department_list) > 0) {
                foreach ($department_list as $key => $value) {
                    //聚合查询部门关系信息
                    $user_depart_info_all_log = UserDepartmodel::where([['corpid', '=', $userData['authCorpId']], ['userid', '=', $userData['userid']]])->pluck('department_id')
                        ->implode(',');
                    $user_depart_info_all_log_arr = explode(',', $user_depart_info_all_log);
                    //如果部门数据多余服务端
                    if ($user_depart_info_all_log && $user_depart_info_all_log_arr > $department_list) {
                        // 筛选出 $user_depart_info_all_log 中有但 $department_list 中没有的元素
                        $diff = array_diff($user_depart_info_all_log_arr, $department_list);
                        sort($diff); //重置下标
                        UserDepartmodel::whereIn('department_id', $diff)->where([['corpid', '=', $userData['authCorpId']], ['userid', '=', $userData['userid']]])->delete();
                    } else if ($user_depart_info_all_log && $user_depart_info_all_log_arr < $department_list) {
                        // 筛选出 $department_list 中有但 $user_depart_info_all_log 中没有的元素
                        $diff = array_diff($department_list, $user_depart_info_all_log_arr);
                        sort($diff); //重置下标
                        $user_depart_info_li = [];
                        foreach ($diff as $k => $v) {
                            $user_depart_info_li[$k] = [
                                'corpid' => $userData['authCorpId'],
                                'userid' => $userData['userid'],
                                'department_id' => $value
                            ];
                        }
                        UserDepartmodel::insert($user_depart_info_li);
                    } else if (!$user_depart_info_all_log) {
                        // 新增关系
                        $user_depart_info_li = [];
                        foreach ($department_list as $k => $v) {
                            $user_depart_info_li[$k] = [
                                'corpid' => $userData['authCorpId'],
                                'userid' => $userData['userid'],
                                'department_id' => $value
                            ];
                        }
                        UserDepartmodel::insert($user_depart_info_li);
                    }
                }
            }
            //添加用户
            Usermodel::where($wheres)->update($user_info);
            //DB::commit();
            DB::connection('company')->commit();
            // 成功处理...
            return true;
            // 成功处理...
        } catch (\Exception $e) {
            DB::connection('company')->rollBack();
            // 错误处理...
            Log::info('job_error', 'message', ['error' => $e->getMessage()]);
            return false;
        }
    }


    /**
     * 获取成员的激活详情
     * @author 唐远望
     * @version 1.0
     * @date 2025-04-22
     * @param string $authCorpId 授权企业ID
     * @param string $userid 用户ID
     * @return bool
     */
    public function activate_information($authCorpId, $userid)
    {
        // 获取实例
        $work            = OpenWork::getApp();
        //获取成员激活详情
        $result = $work->license_account->getActiveAccountInfo($authCorpId, $userid);
        if (!$result)  return json_send(['code' => 'error', 'msg' => '获取失败']);
        // 错误提示
        if ($result['errcode']) {
            Log::info('job_error', '获取成员激活详情失败', ['error' => $result]);
            return true;
        }
        //存在激活记录
        $active_info_list = $result['active_info_list'];
        if (count($active_info_list) < 1) {
            //如果本地存在激活记录则删除
            $active_info_log = UserActiveLog::where([['corpid', '=', $authCorpId], ['userid', '=', $userid]])->first();
            if ($active_info_log) UserActiveLog::where([['corpid', '=', $authCorpId], ['userid', '=', $userid]])->delete();
            return true;
        }
        DB::connection('company')->beginTransaction();
        try {
            $is_open_interoperability = 0;
            $is_open_foundation = 0;
            foreach ($active_info_list as $key => $value) {
                $active_info = [
                    'corpid' => $authCorpId,
                    'userid' => $userid,
                    'type' => $value['type'],
                    'active_code' => $value['active_code'],
                    'account_active_time' => $value['active_time'],
                    'account_expire_time' => $value['expire_time'],
                    'insert_time' => time(),
                ];

                $active_info_log = UserActiveLog::where([['corpid', '=', $authCorpId], ['userid', '=', $userid], ['active_code', '=', $value['active_code']]])->first();

                if (!$active_info_log) {
                    UserActiveLog::insert($active_info);
                } else {
                    UserActiveLog::where([['corpid', '=', $authCorpId], ['userid', '=', $userid], ['active_code', '=', $value['active_code']]])->update([
                        'account_active_time' => $value['active_time'],
                        'account_expire_time' => $value['expire_time']
                    ]);
                }
                //基础账户开通校验
                if ($value['type'] == '1' && $value['expire_time'] > time()) {
                    $is_open_foundation = 1;
                }
                //互通账户开通校验
                if ($value['type'] == '2' && $value['expire_time'] > time()) {
                    $is_open_interoperability = 1;
                }
            }
            $this->update_user_account_status($authCorpId, $userid, $is_open_interoperability, $is_open_foundation);
            DB::connection('company')->commit();
            // 成功处理...
        } catch (\Exception $e) {
            DB::connection('company')->rollBack();
            // 错误处理...
            Log::info('job_error', '获取成员激活详情失败', [$e->getMessage()]);
        }
        return true;
    }

    /**
     * 更新用户账号开通状态
     * @author 唐远望
     * @version 1.0
     * @date 2025-04-22
     * @param string $authCorpId 授权企业ID
     * @param string $userid 用户ID
     * @param int $is_open_interoperability 互通开通状态
     * @param int $is_open_foundation 基础开通状态
     * @return bool
     */
    public function update_user_account_status($authCorpId, $userid, $is_open_interoperability = 0, $is_open_foundation = 0)
    {
        DB::connection('company')->beginTransaction();
        try {

            $user_info = Usermodel::where([['corpid', '=', $authCorpId], ['userid', '=', $userid]])->first();
            if ($user_info) {
                $user_info->is_open_interoperability = $is_open_interoperability;
                $user_info->is_open_foundation = $is_open_foundation;
                $user_info->save();
            }
            DB::connection('company')->commit();
            // 成功处理...
        } catch (\Exception $e) {
            DB::connection('company')->rollBack();
            // 错误处理...
        }
        return true;
    }

    public function failed(\Throwable $exception)
    {
        Log::info('job_error', 'UserJobs彻底失败', ['data' => $this->userData, 'error' => $exception]);
        // 失败处理...
        if ($this->Records) {
            $this->Records->delete();
        }
    }
}
