<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ActivityOrder extends BaseModel
{
    use HasFactory;
    protected $table = 'activity_orders';
    public $fillable = ['activity_id', 'user_id', 'trade_no', 'sku', 'is_pay', 'num', 'sex', 'name', 'mobile', 'area_code', 'amount', 'residue_amount', 'introduce_user_id','sub_mch_id', 'introduce_unusual','unusual_target_id','is_apply_food', 'remark'];

    public const PAID_STATUS = "PAID";
    public const UNPAID_STATUS = "UNPAID";

    public const ADMIN_REFUND_STATUS = "ADMIN_REFUND";
    public const SHARE_REFUND_STATUS = "SHARE_REFUND";
    public const UNUSUAL_STATUS = "UNUSUAL";

    const PRICE = 200;
    public function activity()
    {
        return $this->hasOne(Activity::class,'id', 'activity_id')->withTrashed();
    }

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'user_id');
    }

    public function introduceUser()
    {
        return $this->hasOne(User::class, 'id', 'introduce_user_id');
    }
    /**
     * 指定用户
     * @param $query
     * @param $user_id
     * @return mixed
     */
    public function scopeOwner($query, $user_id)
    {
        return $query->where("user_id", $user_id);
    }

    public function scopeNotOwner($query, $user_id)
    {
        return $query->where("user_id", '<>', $user_id);
    }

    /**
     * 指定活动
     * @param $query
     * @param $activity_id
     * @return mixed
     */
    public function scopeActivity($query, $activity_id)
    {
        return $query->where("activity_id", $activity_id);
    }

    /**
     * 已支付
     * @param $query
     * @return mixed
     */
    public function scopePaid($query)
    {
        return $query->where("is_pay", 1);
    }

    public function scopeUnpaid($query)
    {
        return $query->where("is_pay", 0);
    }

    public function scopeUnusual($query)
    {
        return $query->where("introduce_unusual", 1);
    }

    /**
     * 还有余额
     * @param $query
     * @return mixed
     */
    public function scopeResidue($query)
    {
        return $query->where("residue_amount", ">" ,0);
    }

    public function scopeIntroduce($query, $user_id)
    {
        return $query->where("introduce_user_id", $user_id);
    }

    public function introduceLog()
    {
        return $this->hasOne(ActivityIntroduceLog::class, 'order_id', 'id');
    }

    public function refunds()
    {
        return $this->hasMany(ActivityShareRefund::class, 'order_id', 'id');
    }

    public function targetRefunds()
    {
        return $this->hasMany(ActivityShareRefund::class, 'target_order_id', 'id');
    }

    //介绍人 用户购买活动票记录
    public function recommendUserLog()
    {
        return $this->hasOne(RecommendUser::class, 'user_id', 'user_id');
    }
    //介绍人
    public function recommendUser()
    {
        return $this->hasOneThrough(User::class, RecommendUser::class, 'user_id', 'id', 'user_id', 'recommend_user_id');
    }

    public function unusualOrder()
    {
        return $this->belongsTo(ActivityOrder::class, 'unusual_target_id', 'id');
    }

    public function agentUser()
    {
        return $this->hasOne(AgentUser::class,'user_id', 'user_id')->orderByDesc("level");
    }

    public function markActivityOrder($order)
    {
        DB::beginTransaction();
        //修改订单状态
        $order->update(['is_pay'=>1]);
        //增加介绍人
        if ($order->introduce_user_id) {
            $this->addRecommendUser($order);
        }
        //用户介绍人
        $introduce_user_id = $order->user->recommendUser?$order->user->recommendUser->id:null;
//        //通过介绍人购买，减扣介绍人订单金额
//        if ($order->introduce_user_id && $order->amount && $order->introduce_user_id == $introduce_user_id && $order->introduce_user_id != $order->user_id) {
//            $this->decrementAmount($order->introduce_user_id , $order->amount, $type="INTRODUCE", $order);
//        }
        //通过其他人分享购买，其他人含有余额生成退款记录, 退款金额小于等于当前用户支付金额
//        if ($order->introduce_user_id && $order->amount && $order->introduce_user_id != $order->user_id && $introduce_user_id == $order->introduce_user_id) {
//            $this->refundAmount($order->introduce_user_id, $order->amount, $type="INTRODUCE", $order);
//        }
        //注册准批发商(批发商)
//        $this->registerAgentUser($order);
        AgentUser::changeLevel($order->user_id, AgentUser::AgentLevelBeing, "购买活动门票");

        $activity = $order->activity;
        //插入余额记录
        ActivityOrderLog::addActivityOrderLog($order->user_id,$order->id,$order->amount,"购买活动【{$activity->title}】门票", null,null,ActivityOrderLog::ORDER_TYPE);
        //记录问题介绍人分享  介绍人并且分享的订单并且没有退款绑定订单
        $this->markOrderUnusual($order);
        //加入当前小会抽奖
//        $this->joinRegularActivityLottery($order);
        //加入当前大会抽奖池
        $this->joinActivityLottery($order);
        //加入当前大会签到池
        $this->joinActivityMember($order);
        DB::commit();
    }

    //加入当前大会签到池
    public function joinActivityMember($order)
    {
        $activity = $order->activity;
        //签到状态  购买时间在活动期间
        $status = 0;
        $now = date("Y-m-d H:i:s");
        if ($activity->start_time <= $now && $activity->end_time >= $now) {
            $status = 1;
            //扣除参加费用 200
            if ($order->amount >= Activity::SIGN_FEE) {
                $this->decrementOrderAmount($order, Activity::SIGN_FEE, $activity);
            }
        }
        $activity->members()->updateOrCreate(['user_id'=>$order->user_id, 'activity_id'=>$activity->id], ['status'=>$status]);
    }

    /**
     * 减扣指定订单的余额
     * @param $order  当前扣费订单
     * @param $amount 扣费金额
     */
    public function decrementOrderAmount($order, float $amount, $activity)
    {
        //判断订单余额是否充足
        if ($order->residue_amount < $amount) return false;
        $order->decrement('residue_amount', $amount);
        //插入余额记录
        ActivityOrderLog::addActivityOrderLog($order->user_id,$order->id,number_format($amount * -1,2,'.',''),"【{$activity->title}】活动期间下单并签到",null, null, ActivityOrderLog::SIGNIN_TYPE);
        return true;
    }


    //加入当前大会抽奖池
    public function joinActivityLottery($order)
    {
        $activity = $order->activity;
        $activity->lottery->members()->updateOrCreate(['user_id'=>$order->user_id, 'lottery_id'=>$activity->lottery->id], ['name'=>$order->user->name, 'mobile'=>$order->user->mobile]);
    }

    /**
     * 推荐的订单 没有作为退款目标订单记录
     * @param $order
     */
    public function markOrderUnusual($order)
    {
        Log::info("检查异常分享订单");
        $target_order = ActivityOrder::whereDoesntHave("targetRefunds")->whereHas("recommendUser", function ($sql) use($order) {
            $sql->where('recommend_user_id', $order->user_id);
        })->paid()->where('introduce_user_id', $order->user_id)->first();
        if ($target_order) {
            $order->update(['introduce_unusual'=>1, 'unusual_target_id'=>$target_order->id]);
        }

    }


    // 大会签到记录
    public function signActivities() {
        return $this->hasManyThrough(Activity::class, ActivityMember::class, "user_id", "id", "user_id", "activity_id")->whereIn("activity.id", [17,18,27]);
    }

    // 小会签到记录
    public function signRegularActivities() {
        return $this->hasManyThrough(RegularActivity::class, RegularActivityMember::class, "user_id","id", 'user_id', 'activity_id');
    }

    // 手环订单
    public function bandOrders() { 
        return $this->hasMany(S2ShopOrder::class, 'user_id', 'user_id')->where("sku_id", 86)->whereIn("status", [2,6]);
    }

    // 酒订单
    public function wineOrders() { 
        return $this->hasMany(S2ShopOrder::class, 'user_id', 'user_id')->where("sku_id", 3)->whereIn("status", [2,6]);
    }

    //用户中奖记录
    public function winLotteries() {
        $test_lottery_ids = Lottery::where("title", "like", "%测试%")->pluck("id")->toArray();
        return $this->hasMany(LotteryWinMember::class, "user_id", "user_id")->whereNotIn("lottery_id", $test_lottery_ids);
    }

    public function orderLogs() {
        return $this->hasMany(ActivityOrderLog::class,"order_id", "id");
    }
}
