<?php

namespace App\Jobs\Api\Promoter;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Servers\DB\DbService;
use App\Models\OpenWork\job\Records;
use App\Facades\Servers\Logs\Log;
use Illuminate\Support\Facades\DB;
use App\Models\Manager\CustomExternal as CustomExternalModel;
use App\Models\Manager\Promoter\RecruitCustomers as RecruitCustomersModel;
use App\Models\Manager\Promoter\Users as UsersModel;
use App\Models\Api\Promoter\Configuration as ConfigurationModel;
use App\Models\Manager\Promoter\EarningsRecord as EarningsRecordModel;
use App\Models\Manager\Promoter\Customers as CustomersModel;
use App\Models\Manager\Promoter\AuthCorp as AuthCorpModel;
use App\Models\Manager\Promoter\ExternalFollow as ExternalFollowModel;
use App\Models\Manager\Promoter\OpenworkGroupMember as OpenworkGroupMemberModel;

/**
 * 推广员拉新收益队列
 * @author 唐远望
 * @version 2.0
 * @date 2025-10-14
 */
class RecruitmentBySpreadJobs implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $message_data;
    protected $Records;

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

    /**
     * 推广员拉新注册赠送奖励
     * @author 唐远望
     * @version 1.0
     * @date 2025-10-14
     * @return void
     */
    public function handle()
    {
        try {
            $company_id = $this->message_data['company_id'];
            (new DbService())->getConnectionNameByCompanyId($company_id);
            DB::connection('company')->beginTransaction();
            // 创建任务记录
            $this->Records = Records::create([
                'job_id' => 'SASS_' . $company_id . '_RecruitmentBySpreadJobs',
                'name' => static::class,
                'payload' => json_encode($this->message_data),
                'status' => 'processing',
                'started_at' => now()
            ]);

            $uid = $this->message_data['uid'];
            $shareUid = $this->message_data['share_uid'];
            $company_id = $this->message_data['company_id'];
            $binding_scene = $this->message_data['binding_scene'];


            $before_revenue_amount = 0;
            $customers_atstus = 1;
            //查询推广员状态
            $UsersModel = new UsersModel();
            $CustomersModel = new CustomersModel();
            $CustomExternal = new CustomExternalModel();
            $AuthCorpModel = new AuthCorpModel();
            $ExternalFollowModel = new ExternalFollowModel();
            $OpenworkGroupMemberModel = new OpenworkGroupMemberModel();
            $EarningsRecordModel = new EarningsRecordModel();
            $RecruitCustomersModel = new RecruitCustomersModel();
            $promoter_info = $UsersModel->where('custom_uid', $shareUid)->first();
            if (!$promoter_info || $promoter_info['status'] == 0) {
                return true; //不存在推广员或不是推广员状态，不赠送奖励
                $this->Records->delete();
            }
            $before_revenue_amount = $promoter_info->total_commission_amount;
            //查询推广员配置信息
            $ConfigurationModel = new ConfigurationModel();
            //获取应用配置开关状态
            $application_switch_status_data = $ConfigurationModel->where(['code_name' => 'application_switch_status', 'company_id' => $company_id])->first();
            if (!$application_switch_status_data) {
                return true; //推广员开关信息未配置
                $this->Records->delete();
            }
            if ($application_switch_status_data->content == 0) {
                return true; //推广员功能未开启
                $this->Records->delete();
            }
            //国内用户定义配置
            $application_domestic_user_data = $ConfigurationModel->where(['code_name' => 'application_domestic_user', 'company_id' => $company_id])->first();
            if (!$application_domestic_user_data) {
                return true; //国内用户定义未配置
                $this->Records->delete();
            }
            
            //查询绑定SCRM关系
            $corpId   = $AuthCorpModel->where('company_id', $company_id)->value('corpid');
            $application_domestic_user_content = $application_domestic_user_data->content;
            $successful_type_array = $application_domestic_user_content['new_user_definition']['successful_type'] ? explode(',', $application_domestic_user_content['new_user_definition']['successful_type']) : [];
            $other_conditions_type_array = $application_domestic_user_content['new_user_definition']['other_conditions_type'] ? explode(',', $application_domestic_user_content['new_user_definition']['other_conditions_type']) : [];
            //当开启了添加企微客服或者企微客户状态为正常未流失或者客户已入企微群且未退群 验证时才去查询更新
            if (in_array('2', $successful_type_array) || in_array('1', $other_conditions_type_array) || in_array('2', $other_conditions_type_array)) {
                //执行企微客户查询更新操作
                $CustomExternal->customToExternal($company_id, $uid);

            }
            if (in_array('2', $successful_type_array)) { //拉新成功定义 1=注册登录小程序 2=添加企微客服
                if (!empty($corpId)) {
                    $externalUserId                      = $CustomExternal->where('custom_uid', $uid)->where('corpid', $corpId)->value('external_userid'); //Scrm平台外部联系人id
                    if (!$externalUserId) {
                        return true; //客户未绑定Scrm平台
                        $this->Records->delete();
                    }
                }
            }
            if (in_array('1', $other_conditions_type_array)) { //新用户定义其他条件 1=企微客户状态为正常未流失 2=客户已入企微群且未退群
                if (!empty($corpId)) {
                    $externalUserId                      = $CustomExternal->where('custom_uid', $uid)->where('corpid', $corpId)->value('external_userid'); //Scrm平台外部联系人id
                    if ($externalUserId) {
                        //查询客户状态
                        $external_follow_info = $ExternalFollowModel->where(['external_userid' => $externalUserId, 'corpid' => $corpId, 'status' => 1])->first(); //状态1=流失 0=正常
                        if ($external_follow_info) {
                            return true; //客户已流失
                            $this->Records->delete();
                        }
                    }
                }
            }
            if (in_array('2', $other_conditions_type_array)) { //新用户定义其他条件 1=企微客户状态为正常未流失 2=客户已入企微群且未退群
                if (!empty($corpId)) {
                    $externalUserId                      = $CustomExternal->where('custom_uid', $uid)->where('corpid', $corpId)->value('external_userid'); //Scrm平台外部联系人id
                    if ($externalUserId) {
                        //查询客户状态
                        $external_group_chat_info = $OpenworkGroupMemberModel->where(['external_userid' => $externalUserId, 'corpid' => $corpId, 'status' => 1])->first(); //状态，0在群，1离群
                        if ($external_group_chat_info) {
                            return true; //客户已入企微群,且已退群
                            $this->Records->delete();
                        }
                    }
                }
            }

            //获取客户关系配置规则
            $customer_relationship_rules_data = $ConfigurationModel->where(['code_name' => 'customer_relationship_rules', 'company_id' => $company_id])->first();
            //获取新客注册奖励规则
            $user_registration_reward_rules_data = $ConfigurationModel->where(['code_name' => 'user_registration_reward_rules', 'company_id' => $company_id])->first();
            $is_open_user_registration_reward = 0; //未开启
            $user_registration_reward_rules_content = '';
            if ($user_registration_reward_rules_data) {
                $user_registration_reward_rules_content = $user_registration_reward_rules_data->content;
                $is_open_user_registration_reward = $user_registration_reward_rules_content['status'];
            }
            $regist_binding_id = 0;
            if ($customer_relationship_rules_data) {  //customer_relationship_rules.customer_binding_model_type 客户关系绑定模型 1=简单模式 2=平衡模式 3=竞争模式 4=自定义
                //添加用户推广关系绑定
                $insert_data = [
                    'company_id' => $company_id,
                    'promoter_userid' => $shareUid,
                    'custom_uid' => $uid,
                    'binding_scene' => '注册绑定',
                    'status' => '1',
                    'insert_time' => time(),
                ];
                $regist_binding_id = $RecruitCustomersModel->insertGetId($insert_data);
                $CustomersModel->insert(['custom_uid' => $uid, 'promoter_userid' => $shareUid, 'insert_time' => time(), 'binding_scene' => '注册绑定', 'status' => $customers_atstus,'company_id' => $company_id]);
            }
            if ($is_open_user_registration_reward == 1) {
                $issuance_review_type = $user_registration_reward_rules_content['issuance_review_type']; //用户注册奖励规则发放审核类型 1=需要审核 2=不需要审核
                $reward_amount = $user_registration_reward_rules_content['reward_amount'];
                $after_revenue_amount = round($before_revenue_amount + $reward_amount, 2);
                $earnings_record_status = $issuance_review_type == 1 ? 2 : 4; //状态1=预计收益2=结算中3=审核中4=已转到余额
                //赠送新客注册奖励
                $insert_data = [
                    'company_id' => $company_id,
                    'custom_uid' => $uid,
                    'promoter_userid' => $shareUid,
                    'reward_amount' => $reward_amount,
                    'before_revenue_amount' => $before_revenue_amount,
                    'after_revenue_amount' => $after_revenue_amount,
                    'commission_rate' => '100', //固定奖励金额佣金比为100%
                    'regist_binding_id' => $regist_binding_id,
                    'revenue_type' => 2, //收益类型1=产品收益2=注册收益
                    'insert_time' => time(),
                    'status' => $earnings_record_status
                ];
                $EarningsRecordModel->insertGetId($insert_data);
                //无需审核时，直接发放奖励到余额
                if ($issuance_review_type  == 2) {
                    // 增加余额
                    $promoter_info->total_commission_amount += $reward_amount;
                    $promoter_info->save();
                }
            }
            DB::connection('company')->commit();
            //删除任务记录
            $this->Records->delete();
            // 成功处理...
        } catch (\Exception $e) {
            DB::rollBack();
            // 失败处理...
            if ($this->Records) {
                $this->Records->delete();
            }
            Log::info('job_error', '推广员拉新收益队列运行失败', ['data'=>$this->message_data, 'error' => $e->getMessage()]);
        }
    }

    public function failed(\Throwable $exception)
    {
        Log::info('job_error', '推广员拉新收益队列彻底失败', ['data'=>$this->message_data, 'error' => $exception]);
        // 失败处理...
        if ($this->Records) {
            $this->Records->delete();
        }
    }
}
