<?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\Orders as OrdersModel;
use App\Models\Api\Promoter\Configuration as ConfigurationModel;
use App\Models\Manager\Promoter\CommonProduct as CommonProductModel;
use App\Models\Manager\Promoter\EarningsRecord as EarningsRecordModel;
use App\Jobs\Api\Promoter\LevelThreeOrdersJobs;


/**
 * 二级推广员订单收益
 * @author 唐远望
 * @version 2.0
 * @date 2025-11-19
 */
class LevelTwoOrdersJobs 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-11-19
     * @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'];
            $custom_uid = $this->message_data['custom_uid']; //推广员用户ID

            $before_revenue_amount = 0;
            $UsersModel = new UsersModel();
            $OrdersProductModel = new OrdersProduct();
            $orderModel = new OrdersModel();
            $CommonProductModel = new CommonProductModel();
            $EarningsRecordModel = new EarningsRecordModel();
            //查询一级推广员状态
            $one_promoter_info = $UsersModel->where('custom_uid', $custom_uid)->first();
            if (!$one_promoter_info || $one_promoter_info['status'] == 0) {
                $this->Records->delete();
                return true; //不存在推广员或不是推广员状态，不赠送奖励
            }
            //查询二级推广员状态
            $promoter_info = $UsersModel->where('custom_uid', $one_promoter_info->superior_custom_uid)->first();
            if (!$promoter_info || $promoter_info['status'] == 0) {
                $this->Records->delete();
                return true; //不存在二级推广员或不是二级推广员状态，不赠送奖励
            }
            $before_revenue_amount = $promoter_info->total_commission_amount;
            $promoter_userid = $promoter_info->custom_uid;
            //查询推广员配置信息
            $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; //推广员功能未开启
            }
            //查询订单信息
            $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; //订单商品不存在
            }
            //获取佣金配置信息
            $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 = [];
            foreach ($product_data as $key => $value) {
                $product_id = $value['product_id'];
                $commission_rate = 0;
                $reward_amount = 0;
                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 = isset($promotion_product_config_data['mini_two_commission_rate']) ? $promotion_product_config_data['mini_two_commission_rate'] : 0;
                            $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 = isset($promotion_product_config_data['live_two_commission_rate']) ? $promotion_product_config_data['live_two_commission_rate'] : 0;
                            $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;
                        }
                        $product_info = $product_info->toArray();
                        if ($value['terminal_type'] == 1) { //终端类型1=小程序 2=H5 3=直播间 4=PC
                            $commission_rate = isset($product_info['mini_two_commission_rate']) ? $product_info['mini_two_commission_rate'] : 0;
                            $reward_amount = round($value['pay_total'] * $commission_rate / 100, 2);
                        }
                        if ($value['terminal_type'] == 3) { //终端类型1=小程序 2=H5 3=直播间 4=PC
                            $commission_rate = isset($product_info['live_two_commission_rate']) ? $product_info['live_two_commission_rate'] : 0;
                            $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 = isset($promotion_product_config_data['mini_two_commission_rate']) ? $promotion_product_config_data['mini_two_commission_rate'] : 0;
                            $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 = isset($promotion_product_config_data['live_two_commission_rate']) ? $promotion_product_config_data['live_two_commission_rate'] : 0;
                            $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;
                        }
                        $product_info = $product_info->toArray();
                        if ($value['terminal_type'] == 1) { //终端类型1=小程序 2=H5 3=直播间 4=PC
                            $commission_rate = isset($product_info['mini_two_commission_rate']) ? $product_info['mini_two_commission_rate'] : 0;
                            $reward_amount = round($value['pay_total'] * $commission_rate / 100, 2);
                        }
                        if ($value['terminal_type'] == 3) { //终端类型1=小程序 2=H5 3=直播间 4=PC
                            $commission_rate = isset($product_info['live_two_commission_rate']) ? $product_info['live_two_commission_rate'] : 0;
                            $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=注册收益
                    'commission_level' => '2', //推广等级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();
            // 开启三级推广员订单处理队列
            LevelThreeOrdersJobs::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();
        }
    }
}
