<?php

namespace App\Jobs\Api\Coupon;

use Illuminate\Bus\Queueable;
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\Facades\Servers\Logs\Log;

/**
 * 自动发放优惠券
 */
class AutoJobs implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $autoData;

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

    /**
     * 自动发放优惠券队列运行失败
     * @return void
     */
    public function handle()
    {
        try {
            $companyId  = empty($this->autoData['company_id']) ? 0 : $this->autoData['company_id'];
            $uid        = empty($this->autoData['custom_uid']) ? 0 : $this->autoData['custom_uid'];
            // 切换数据库
            $result     = (new DbService())->getConnectionNameByCompanyId($companyId);
            // 如果失败
            if( !isset($result['error']) ) $this->autoCoupon($uid);
            // 成功处理...
        } catch (\Exception $e) {
            Log::info('job_error', '自动发放优惠券队列运行失败', ['error' => $e->getMessage()]);
        }
    }

    public function failed(\Throwable $exception)
    {
        Log::info('job_error', '自动发放优惠券彻底失败', ['error' => $exception]);
    }

    /**
     * 自动发放优惠券
     *
     */
    private function autoCoupon($uid){
        // 模型实例
        $Rule 					= new \App\Models\Manager\CouponRewardRule();
        // 获取配置列表
        $ruleList				= $Rule->getList();
        // 如果没有信息的话
        if( !$ruleList )		return ['success'=>'暂无活动'];
        // 其他实例
        $RuleProduct 			= new \App\Models\Manager\CouponRewardProduct();
        $OrdersProduct 			= new \App\Models\Manager\OrdersProduct();
        $Custom					= new \App\Models\Manager\Custom();
        $Coupon					= new \App\Models\Manager\Coupon();
        $CustomCoupon			= new \App\Models\Manager\CustomCoupon();
        // 获取客户城市ID
        $customCityId			= (int) $Custom->getValue($uid,'city_id');
        // 循环配置列表
        foreach ( $ruleList as 	$value ) {
            // 如果存在城市范围，并且不在城市范围,不参与这个活动
            if( $value['city_ids'] && !in_array($customCityId,explode(',',$value['city_ids'])) ) continue;
            // 未到开始时间
            if( $value['start_time'] > time() )  continue;
            // 通过配置ID获取对应的商品范围
            $productList 		= $RuleProduct->getListByRule($value['id']);
            // 如果不存在产品范围，跳过
            if( !$productList ) continue;
            // 获取客户 规定时段内订单的商品ID以及购买数量
            $orderList 			= $OrdersProduct->query()->where([['custom_uid','=',$uid],['insert_time','>=',$value['start_time']],['insert_time','<=',$value['end_time']]])->whereIn('status',[0,2])->get(['product_id','buy_num'])->toArray();
            // 如果没有订单总数
            if( !$orderList ) 	continue;
            // 计算商品总量
            $total				= 0;
            // 循环商品范围
            foreach ($productList as $scope) {
                // 循环订单产品
                foreach ($orderList as $order) {
                    // 如果产品不相等
                    if( $scope['product_id'] != $order['product_id'] ) continue;
                    // 相等的计算总量
                    $total		+= $scope['product_units'] * $order['buy_num'];
                }
            }
            // 判断总数是不是达标
            if( $total < $value['std_num'] )  continue;
            if ($value['coupon_id']){
                $couponIdArray = explode(',',$value['coupon_id']);
                foreach ($couponIdArray as $couponId) {
                    // 达标的是否已经发送过优惠券
                    $havaCoupon			= $CustomCoupon->query()->where([['custom_uid','=',$uid],['coupon_id','=',$couponId]])->first(['status']);
                    // 已经发过优惠券的，不发
                    if( $havaCoupon )   continue;
                    // 获取优惠券的可用时间
                    $expTime			= $Coupon->query()->where([['id','=',$couponId]])->value('exp_time');
                    // 时间转时间
                    $expTime			= $Coupon->getExpTime($expTime);
                    // 发送优惠券
                    $CustomCoupon->add(['coupon_id'=>$couponId,'custom_uid'=>$uid,'exp_time'=>$expTime]);
                }
            }
        }
        // 返回成功
        return					['success'=>'操作成功'];
    }
}
