<?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\Promoter\Users as UsersModel;
use App\Models\Manager\OrdersProduct;
use App\Models\Manager\Promoter\Customers as CustomersModel;
use App\Models\Manager\Orders as OrdersModel;
use App\Models\Api\Promoter\Configuration as ConfigurationModel;
use App\Models\Manager\Promoter\Product as ProductModel;
use App\Models\Manager\Promoter\CommonProduct as CommonProductModel;
use App\Models\Manager\Promoter\EarningsRecord as EarningsRecordModel;
use App\Models\Manager\CustomExternal as CustomExternalModel;
use App\Models\Manager\Promoter\AuthCorp as AuthCorpModel;
use App\Models\Manager\Promoter\ExternalFollow as ExternalFollowModel;
use App\Models\Manager\Promoter\OpenworkGroupMember as OpenworkGroupMemberModel;
use App\Jobs\Api\Promoter\LevelTwoOrdersJobs;

/**
 * 推广员一级订单收益
 * @author 唐远望
 * @version 2.0
 * @date 2025-10-10
 */
class OrdersJobs 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-10
     * @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 . '_OrdersJobs',
                'name' => static::class,
                'payload' => json_encode($this->message_data),
                'status' => 'processing',
                'started_at' => now()
            ]);
            $uid = $this->message_data['uid'];
            $order_id = $this->message_data['order_id'];
            $share_uid = $this->message_data['share_uid'];

            $before_revenue_amount = 0;
            $UsersModel = new UsersModel();
            $OrdersProductModel = new OrdersProduct();
            $CustomersModel = new CustomersModel();
            $orderModel = new OrdersModel();
            // $ProductModel = new ProductModel();
            $CommonProductModel = new CommonProductModel();
            $EarningsRecordModel = new EarningsRecordModel();
            $CustomExternal = new CustomExternalModel();
            $AuthCorpModel = new AuthCorpModel();
            $ExternalFollowModel = new ExternalFollowModel();
            $OpenworkGroupMemberModel = new OpenworkGroupMemberModel();
            if ($share_uid == '') {
                //如果没有推广员分享用户ID时
                $promoter_customers_data = $CustomersModel->where('custom_uid', $uid)->first();
                if (!$promoter_customers_data) {
                    $this->Records->delete();
                    return true; //不存在推广员，不赠送奖励
                }
                $share_uid = $promoter_customers_data->promoter_userid;
                //查询推广员状态
                $promoter_info = $UsersModel->where('custom_uid', $share_uid)->first();
                if (!$promoter_info || $promoter_info['status'] == 0) {
                    $this->Records->delete();
                    return true; //不存在推广员或不是推广员状态，不赠送奖励
                }
            } else {
                //查询推广员状态
                $promoter_info = $UsersModel->where('custom_uid', $share_uid)->first();
                if (!$promoter_info || $promoter_info['status'] == 0) {
                    $this->Records->delete();
                    return true; //不存在推广员或不是推广员状态，不赠送奖励
                }
            }
            $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) {
                $this->Records->delete();
                return true; //推广员开关信息未配置
            }
            if ($application_switch_status_data->content == 0) {
                $this->Records->delete();
                return true; //推广员功能未开启
            }
            //查询客户关系配置
            $customer_relationship_rules_data = $ConfigurationModel->where(['code_name' => 'customer_relationship_rules', 'company_id' => $company_id])->first();
            if (!$customer_relationship_rules_data) {
                $this->Records->delete();
                return true; //客户关系配置信息未配置
            }
            //国内用户定义配置
            $application_domestic_user_data = $ConfigurationModel->where(['code_name' => 'application_domestic_user', 'company_id' => $company_id])->first();
            if (!$application_domestic_user_data) {
                $this->Records->delete();
                return true; //国内用户定义配置
            }
            //执行企微客户查询更新操作
            $CustomExternal->customToExternal($company_id, $uid);
            //查询绑定SCRM关系
            $corpId   = $AuthCorpModel->where('company_id', $company_id)->value('corpid');
            $application_domestic_user_content = $application_domestic_user_data->content;
            $add_wecom_customer_service_status = $application_domestic_user_content['effective_customer_definition']['add_wecom_customer_service_status'];//添加企微客服 状态0=关闭 1=开启
            $customer_churn_status = $application_domestic_user_content['effective_customer_definition']['customer_churn_status'];//企微客户状态为正常未流失状态 0=关闭 1=开启
            $exit_wechat_group_status = $application_domestic_user_content['effective_customer_definition']['exit_wechat_group_status'];//客户已入企微群且未退群 状态0=关闭 1=开启
            if ($add_wecom_customer_service_status == 1) { 
                if (!empty($corpId)) {
                    $externalUserId                      = $CustomExternal->where('custom_uid', $uid)->where('corpid', $corpId)->value('external_userid'); //Scrm平台外部联系人id
                    if (!$externalUserId) {
                        $this->Records->delete();
                        return true; //客户未绑定Scrm平台
                    }
                }
            }
            if ($customer_churn_status == 1) { 
                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) {
                            $this->Records->delete();
                            return true; //客户已流失
                        }
                    }
                }
            }
            if ($exit_wechat_group_status == 1) {
                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) {
                            $this->Records->delete();
                            return true; //客户已入企微群,且已退群
                        }
                    }
                }
            }
            $promoter_userid = 0;
            $content_config = $customer_relationship_rules_data->content;
            if ($content_config['customer_binding_model_type'] == 1) {  //客户关系绑定模型 1=简单模式 2=平衡模式 3=竞争模式 4=自定义
                //查询用户绑定的
                $promoter_customers_data = $CustomersModel->where('custom_uid', $uid)->first();
                if ($promoter_customers_data) {
                    $promoter_userid = $promoter_customers_data->promoter_userid;
                } else {
                    //新增用户绑定
                    $CustomersModel->insert(['custom_uid' => $uid, 'promoter_userid' => $share_uid, 'insert_time' => time(), 'binding_scene' => '推广下单', 'status' => '1','company_id'=>$company_id]);
                    $promoter_userid = $share_uid;
                }
            } else if ($content_config['customer_binding_model_type'] == 2) { //客户关系绑定模型 1=简单模式 2=平衡模式 3=竞争模式 4=自定义
                //查询用户绑定的
                $promoter_customers_data = $CustomersModel->where('custom_uid', $uid)->first();
                if ($promoter_customers_data) {
                    $end_time = $promoter_customers_data->insert_time + 86400 * 15; //15天之内奖励为原先推广员
                    if ($end_time >= time()) {
                        $promoter_userid = $promoter_customers_data->promoter_userid;
                    } else {
                        $promoter_userid = $share_uid; //15天之后奖励为新推广员
                        $promoter_customers_data->promoter_userid = $share_uid;
                        $promoter_customers_data->save();
                    }
                } else {
                    //新增用户绑定
                    $CustomersModel->insert(['custom_uid' => $uid, 'promoter_userid' => $share_uid, 'insert_time' => time(), 'binding_scene' => '推广下单', 'status' => '1','company_id'=>$company_id]);
                    $promoter_userid = $share_uid;
                }
            } else if ($content_config['customer_binding_model_type'] == 3) { //客户关系绑定模型 1=简单模式 2=平衡模式 3=竞争模式 4=自定义
                //查询用户绑定的
                $promoter_customers_data = $CustomersModel->where('custom_uid', $uid)->first();
                if ($promoter_customers_data) {
                    if ($promoter_customers_data->promoter_userid != $share_uid) {
                        $promoter_userid = $share_uid; //15天之后奖励为新推广员
                        $promoter_customers_data->promoter_userid = $share_uid;
                        $promoter_customers_data->save();
                    }
                } else {
                    //新增用户绑定
                    $CustomersModel->insert(['custom_uid' => $uid, 'promoter_userid' => $share_uid, 'insert_time' => time(), 'binding_scene' => '推广下单', 'status' => '1','company_id'=>$company_id]);
                    $promoter_userid = $share_uid;
                }
            }
            //查询订单信息
            $order_info = $orderModel->where('custom_uid', $uid)->where('id', $order_id)->first();
            if (!$order_info) {
                $this->Records->delete();
                return true; //订单不存在
            }
            $product_data = $OrdersProductModel->where('order_id', $order_id)->get(['product_id', 'product_name', 'shop_id', 'terminal_type', 'pay_total', 'buy_num'])->toArray();
            if (empty($product_data)) {
                $this->Records->delete();
                return true; //订单商品不存在
            }
            $is_first_order = 0;
            $first_order_reward_rules_data = '';
            //查询用户是否下单记录
            $other_order_info = $orderModel->where('custom_uid', $uid)->whereNotIN('id', [$order_id])->first();
            if (!$other_order_info) {
                //校验下单时间是否在配置时间范围内
                $first_order_reward_rules = $ConfigurationModel->where(['code_name' => 'first_order_reward_rules', 'company_id' => $company_id])->first();
                if (!$first_order_reward_rules) {
                    $is_first_order = 0; //首单不奖励,没有配置信息
                }
                $first_order_reward_rules_data = $first_order_reward_rules->content;
                if ($first_order_reward_rules_data['status'] != 1) {
                    $is_first_order = 0; //首单不奖励,没有开启奖励
                }
                if ($first_order_reward_rules_data['reward_amount_expiration_date'] != 1) {
                    $is_first_order = 0; //首单不奖励,没有开启奖励
                }
                //首单奖励截止时间
                $first_order_end_time = $order_info['insert_time'] + 86400 * $first_order_reward_rules_data['reward_amount_expiration_date'];
                if ($first_order_end_time < time()) {
                    $is_first_order = 0; //首单不奖励,奖励时间已过
                }
                $is_first_order = 1; //首单
            }
            //获取佣金配置信息
            $promotion_product_config = $ConfigurationModel->where(['code_name' => 'promotion_product_config', 'company_id' => $company_id])->first();
            if (!$promotion_product_config) {
                $this->Records->delete();
                return true; //佣金配置信息未配置
            }
            $promotion_product_config_data = $promotion_product_config->content;
            $insert_data = [];
            //如果是首单，则查询首单配置信息，给予奖励
            if ($is_first_order == 1) {
                //首单奖励佣金(下单范围&奖励条件类型)
                $is_give_first_order_reward = 1; //是否给予首单奖励1=是 0=否
                //商品件数
                $buy_num = '0';
                $first_commission_rate = 0;
                $first_reward_amount = 0;
                foreach ($product_data as $first_key => $first_value) {
                    $product_id = $first_value['product_id'];
                    $reward_conditions_product_ids = $first_order_reward_rules_data['reward_conditions_product_ids']; //下单产品范围
                    $reward_conditions_product_ids = $reward_conditions_product_ids ? explode(',', $reward_conditions_product_ids) : [];
                    if (!empty($reward_conditions_product_ids) && !in_array($product_id, $reward_conditions_product_ids)) {
                        $is_give_first_order_reward = 0; //不符合奖励条件
                    }
                    $buy_num += $first_value['buy_num'];
                }
                $reward_conditions_amount = array_key_exists('reward_conditions_amount',$first_order_reward_rules_data) ? $first_order_reward_rules_data['reward_conditions_amount']:'0'; //下单金额范围
                $reward_conditions_type =array_key_exists('reward_conditions_type',$first_order_reward_rules_data) ? $first_order_reward_rules_data['reward_conditions_type']:'0'; //奖励条件类型
                if ($reward_conditions_type == 1) { //首单奖励规则奖励条件类型 1=下单金额 2=下单商品数
                    if ($order_info['pay_total'] < $reward_conditions_amount) {
                        $is_give_first_order_reward = 0; //不符合奖励条件
                    }
                }
                if ($reward_conditions_type == 2) { //首单奖励规则奖励条件类型 1=下单金额 2=下单商品数
                    $reward_conditions_boxes_number = array_key_exists('reward_conditions_boxes_number',$first_order_reward_rules_data) ? $first_order_reward_rules_data['reward_conditions_boxes_number']:'0'; //下单商品数范围
                    if ($buy_num < $reward_conditions_boxes_number) {
                        $is_give_first_order_reward = 0; //不符合奖励条件
                    }
                }
                $reward_amount_number = $first_order_reward_rules_data['reward_amount_number']; //首单额外奖励金额
                if ($is_give_first_order_reward == 1 && $reward_amount_number > 0) {
                    $first_commission_rate = 100; //固定金额奖励，佣金比为100%
                    $first_reward_amount = $reward_amount_number;
                }
                if ($first_commission_rate > 0.01 && $first_reward_amount > 0.01) {
                    $after_revenue_amount = round($before_revenue_amount + $first_reward_amount, 2);
                    $insert_data[] = [
                        'company_id' => $company_id,
                        'order_id' => $order_id,
                        'product_id' => '0',
                        'is_first_order' => $is_first_order,
                        'product_name' => '',
                        'shop_id' => $order_info->shop_id,
                        'pay_total' => $order_info->pay_total,
                        'custom_uid' => $uid,
                        'promoter_userid' => $promoter_userid,
                        'commission_rate' => $first_commission_rate,
                        'reward_amount' => $first_reward_amount,
                        'before_revenue_amount' => $before_revenue_amount,
                        'after_revenue_amount' => $after_revenue_amount,
                        'revenue_type' => 1, //收益类型1=产品收益2=注册收益
                        'insert_time' => time(),
                        'status' => 1, //状态1=预计收益2=结算中3=审核中4=已转到余额
                    ];
                }
                //推广奖励佣金
                foreach ($product_data as $key => $value) {
                    $product_id = $value['product_id'];
                    $commission_rate = 0;
                    $reward_amount = 0;

                    //------旧规则，每个推广员商品配置独立的佣金规则------
                    //  $product_info = $ProductModel->where(['company_id' => $company_id, 'status' => 1, 'promoter_userid' => $promoter_userid, 'product_id' => $product_id])->first();
                    // if (!$product_info) {
                    //     continue;
                    // }
                    // if ($value['terminal_type'] == 1) { //终端类型1=小程序 2=H5 3=直播间 4=PC
                    //     $commission_rate = $product_info->mini_commission_rate;
                    //     $reward_amount = round($value['pay_total'] * $commission_rate / 100, 2);
                    // }
                    // if ($value['terminal_type'] == 3) { //终端类型1=小程序 2=H5 3=直播间 4=PC
                    //     $commission_rate = $product_info->live_commission_rate;
                    //     $reward_amount = round($value['pay_total'] * $commission_rate / 100, 2);
                    // }
                    // if ($commission_rate < 0.01 || $reward_amount < 0.01) {
                    //     continue;
                    // }
                    // ------新规则，公告商品池佣金规则------
                    if ($promotion_product_config_data['store_type'] == 1) {  //推广店铺类型1=全部店铺2=指定店铺
                        if ($promotion_product_config_data['product_type'] == 1) { //推广商品类型1=全部商品2=指定商品
                            if ($value['terminal_type'] == 1) { //终端类型1=小程序 2=H5 3=直播间 4=PC
                                $commission_rate = $promotion_product_config_data['mini_commission_rate'];
                                $reward_amount = $commission_rate > 0 ? round($value['pay_total'] * $commission_rate / 100, 2) : 0;
                            }
                            if ($value['terminal_type'] == 3) { //终端类型1=小程序 2=H5 3=直播间 4=PC
                                $commission_rate = $promotion_product_config_data['live_commission_rate'];
                                $reward_amount = $commission_rate > 0 ? round($value['pay_total'] * $commission_rate / 100, 2) : 0;
                            }
                        } else {
                            $product_info = $CommonProductModel->where(['company_id' => $company_id, 'status' => 1, 'product_id' => $product_id])->first();
                            if (!$product_info) {
                                continue;
                            }
                            if ($value['terminal_type'] == 1) { //终端类型1=小程序 2=H5 3=直播间 4=PC
                                $commission_rate = $product_info->mini_commission_rate;
                                $reward_amount = round($value['pay_total'] * $commission_rate / 100, 2);
                            }
                            if ($value['terminal_type'] == 3) { //终端类型1=小程序 2=H5 3=直播间 4=PC
                                $commission_rate = $product_info->live_commission_rate;
                                $reward_amount = round($value['pay_total'] * $commission_rate / 100, 2);
                            }
                            if ($commission_rate < 0.01 || $reward_amount < 0.01) {
                                continue;
                            }
                        }
                    }
                    if ($promotion_product_config_data['store_type'] == 2) {  //推广店铺类型1=全部店铺2=指定店铺
                        //校验店铺是否在配置范围内
                        $shopid_list = explode(',', $promotion_product_config_data['shopid_list']);
                        if (!in_array($value['shop_id'], $shopid_list)) {
                            continue;
                        }
                        if ($promotion_product_config_data['product_type'] == 1) { //推广商品类型1=全部商品2=指定商品
                            if ($value['terminal_type'] == 1) { //终端类型1=小程序 2=H5 3=直播间 4=PC
                                $commission_rate = $promotion_product_config_data['mini_commission_rate'];
                                $reward_amount = $commission_rate > 0 ? round($value['pay_total'] * $commission_rate / 100, 2) : 0;
                            }
                            if ($value['terminal_type'] == 3) { //终端类型1=小程序 2=H5 3=直播间 4=PC
                                $commission_rate = $promotion_product_config_data['live_commission_rate'];
                                $reward_amount = $commission_rate > 0 ? round($value['pay_total'] * $commission_rate / 100, 2) : 0;
                            }
                        } else {
                            $product_info = $CommonProductModel->where(['company_id' => $company_id, 'status' => 1, 'product_id' => $product_id])->first();
                            if (!$product_info) {
                                continue;
                            }
                            if ($value['terminal_type'] == 1) { //终端类型1=小程序 2=H5 3=直播间 4=PC
                                $commission_rate = $product_info->mini_commission_rate;
                                $reward_amount = round($value['pay_total'] * $commission_rate / 100, 2);
                            }
                            if ($value['terminal_type'] == 3) { //终端类型1=小程序 2=H5 3=直播间 4=PC
                                $commission_rate = $product_info->live_commission_rate;
                                $reward_amount = round($value['pay_total'] * $commission_rate / 100, 2);
                            }
                            if ($commission_rate < 0.01 || $reward_amount < 0.01) {
                                continue;
                            }
                        }
                    }
                    
                    if ($commission_rate < 0.01 || $reward_amount < 0.01) {
                        continue;
                    }
                    $after_revenue_amount = round($before_revenue_amount + $reward_amount, 2);
                    $insert_data[] = [
                        'company_id' => $company_id,
                        'order_id' => $order_id,
                        'product_id' => $product_id,
                        'is_first_order' => '0',
                        'product_name' => $value['product_name'],
                        'shop_id' => $value['shop_id'],
                        'pay_total' => $value['pay_total'],
                        'custom_uid' => $uid,
                        'promoter_userid' => $promoter_userid,
                        'commission_rate' => $commission_rate,
                        'reward_amount' => $reward_amount,
                        'before_revenue_amount' => $before_revenue_amount,
                        'after_revenue_amount' => $after_revenue_amount,
                        'revenue_type' => 1, //收益类型1=产品收益2=注册收益
                        'insert_time' => time(),
                        'status' => 1, //状态1=预计收益2=结算中3=审核中4=已转到余额
                    ];
                }
                $EarningsRecordModel->insert($insert_data);
                //统计首单奖励金额
                $UsersModel->where('custom_uid', $promoter_userid)->update([
                    'first_order_reward_amount' => DB::raw('first_order_reward_amount+' . $reward_amount),
                    'product_commission_amount' => DB::raw('product_commission_amount+' . $reward_amount)
                ]);
            } else {
                foreach ($product_data as $key => $value) {
                    $product_id = $value['product_id'];
                    $commission_rate = 0;
                    $reward_amount = 0;

                    //------旧规则，每个推广员商品配置独立的佣金规则------
                    // $product_info = $ProductModel->where(['company_id' => $company_id, 'status' => 1, 'promoter_userid' => $promoter_userid, 'product_id' => $product_id])->first();
                    // if (!$product_info) {
                    //     continue;
                    // }
                    // if ($value['terminal_type'] == 1) { //终端类型1=小程序 2=H5 3=直播间 4=PC
                    //     $commission_rate = $product_info->mini_commission_rate;
                    //     $reward_amount = round($value['pay_total'] * $commission_rate / 100, 2);
                    // }
                    // if ($value['terminal_type'] == 3) { //终端类型1=小程序 2=H5 3=直播间 4=PC
                    //     $commission_rate = $product_info->live_commission_rate;
                    //     $reward_amount = round($value['pay_total'] * $commission_rate / 100, 2);
                    // }
                    // if ($commission_rate < 0.01 || $reward_amount < 0.01) {
                    //     continue;
                    // }

                    //------新规则，公告商品池佣金规则------
                    if ($promotion_product_config_data['store_type'] == 1) {  //推广店铺类型1=全部店铺2=指定店铺
                        if ($promotion_product_config_data['product_type'] == 1) { //推广商品类型1=全部商品2=指定商品
                            if ($value['terminal_type'] == 1) { //终端类型1=小程序 2=H5 3=直播间 4=PC
                                $commission_rate = $promotion_product_config_data['mini_commission_rate'];
                                $reward_amount = $commission_rate > 0 ? round($value['pay_total'] * $commission_rate / 100, 2) : 0;
                            }
                            if ($value['terminal_type'] == 3) { //终端类型1=小程序 2=H5 3=直播间 4=PC
                                $commission_rate = $promotion_product_config_data['live_commission_rate'];
                                $reward_amount = $commission_rate > 0 ? round($value['pay_total'] * $commission_rate / 100, 2) : 0;
                            }
                        } else {
                            $product_info = $CommonProductModel->where(['company_id' => $company_id, 'status' => 1, 'product_id' => $product_id])->first();
                            if (!$product_info) {
                                continue;
                            }
                            if ($value['terminal_type'] == 1) { //终端类型1=小程序 2=H5 3=直播间 4=PC
                                $commission_rate = $product_info->mini_commission_rate;
                                $reward_amount = round($value['pay_total'] * $commission_rate / 100, 2);
                            }
                            if ($value['terminal_type'] == 3) { //终端类型1=小程序 2=H5 3=直播间 4=PC
                                $commission_rate = $product_info->live_commission_rate;
                                $reward_amount = round($value['pay_total'] * $commission_rate / 100, 2);
                            }
                            if ($commission_rate < 0.01 || $reward_amount < 0.01) {
                                continue;
                            }
                        }
                    }
                    if ($promotion_product_config_data['store_type'] == 2) {  //推广店铺类型1=全部店铺2=指定店铺
                        //校验店铺是否在配置范围内
                        $shopid_list = explode(',', $promotion_product_config_data['shopid_list']);
                        if (!in_array($value['shop_id'], $shopid_list)) {
                            continue;
                        }
                        if ($promotion_product_config_data['product_type'] == 1) { //推广商品类型1=全部商品2=指定商品
                            if ($value['terminal_type'] == 1) { //终端类型1=小程序 2=H5 3=直播间 4=PC
                                $commission_rate = $promotion_product_config_data['mini_commission_rate'];
                                $reward_amount = $commission_rate > 0 ? round($value['pay_total'] * $commission_rate / 100, 2) : 0;
                            }
                            if ($value['terminal_type'] == 3) { //终端类型1=小程序 2=H5 3=直播间 4=PC
                                $commission_rate = $promotion_product_config_data['live_commission_rate'];
                                $reward_amount = $commission_rate > 0 ? round($value['pay_total'] * $commission_rate / 100, 2) : 0;
                            }
                        } else {
                            $product_info = $CommonProductModel->where(['company_id' => $company_id, 'status' => 1, 'product_id' => $product_id])->first();
                            if (!$product_info) {
                                continue;
                            }
                            if ($value['terminal_type'] == 1) { //终端类型1=小程序 2=H5 3=直播间 4=PC
                                $commission_rate = $product_info->mini_commission_rate;
                                $reward_amount = round($value['pay_total'] * $commission_rate / 100, 2);
                            }
                            if ($value['terminal_type'] == 3) { //终端类型1=小程序 2=H5 3=直播间 4=PC
                                $commission_rate = $product_info->live_commission_rate;
                                $reward_amount = round($value['pay_total'] * $commission_rate / 100, 2);
                            }
                            if ($commission_rate < 0.01 || $reward_amount < 0.01) {
                                continue;
                            }
                        }
                    }

                    if ($commission_rate < 0.01 || $reward_amount < 0.01) {
                        continue;
                    }
                    $after_revenue_amount = round($before_revenue_amount + $reward_amount, 2);
                    $insert_data[] = [
                        'company_id' => $company_id,
                        'order_id' => $order_id,
                        'product_id' => $product_id,
                        'is_first_order' => $is_first_order,
                        'product_name' => $value['product_name'],
                        'shop_id' => $value['shop_id'],
                        'pay_total' => $value['pay_total'],
                        'custom_uid' => $uid,
                        'promoter_userid' => $promoter_userid,
                        'commission_rate' => $commission_rate,
                        'reward_amount' => $reward_amount,
                        'before_revenue_amount' => $before_revenue_amount,
                        'after_revenue_amount' => $after_revenue_amount,
                        'revenue_type' => 1, //收益类型1=产品收益2=注册收益
                        'commission_level' => '1', //推广等级1=一级推广员2=二级推广员3=三级推广员
                        'insert_time' => time(),
                        'status' => 1, //状态1=预计收益2=结算中3=审核中4=已转到余额
                    ];
                }
                $EarningsRecordModel->insert($insert_data);
                //统计非首单奖励金额
                $UsersModel->where('custom_uid', $promoter_userid)->update([
                    'product_commission_amount' => DB::raw('product_commission_amount+' . $reward_amount)
                ]);
            }
            DB::connection('company')->commit();
            // 开启二级推广员订单处理队列
            // LevelTwoOrdersJobs::dispatch(['uid'=>$uid,'custom_uid'=>$promoter_userid,'company_id'=>$company_id,'order_id'=>$order_id]);
            //删除任务记录
            $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();
        }
    }
}
