<?php

namespace App\Models;

use App\Console\Commands\DmaQuestionNotice;
use BeyondCode\Comments\Traits\HasComments;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\DB;
use Log;

class Order extends BaseModel
{
    use HasComments;

    const ORDER_PRICE = 20000;

    //支付状态
    const UNPAID_STATUS = "UNPAID"; //未支付
    const PAID_STATUS = "PAID"; //已支付

    //服务状态
    const NOTSTART_STATUS = 'NOTSTART'; //未开始
    const STARTING_STATUS = "STARTING"; //进行中
    const FINISHED_STATUS = "FINISHED"; //已完成
    const SUSPEND_STATUS = "SUSPEND"; //暂停中

    const DELIVER_ONLINE = 1;
    const DELIVER_OFFLINE = 2;
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function payment()
    {
        return $this->hasOne(Payment::class, "id", "payment_id");
    }

    public function userInfo()
    {
        return $this->belongsTo(UserInfo::class, 'user_id', 'user_id');
    }

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

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

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

    public function service()
    {
        return $this->hasOne(Service::class, 'id', 'type_id');
    }

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

    public function offline_order()
    {
        return $this->hasOne(OfflineOrder::class);
    }

    public function orderSurveys()
    {
        return $this->hasMany(OrderSurvey::class);
    }

    public function commission()
    {
        return $this->hasMany(OrderCommission::class);
    }

    public function agency()
    {
        return $this->belongsTo(Partner::class, 'agency_id', 'id');
    }

    public function service_role()
    {
        return $this->hasMany(ServiceRoleOrder::class, 'order_id', 'id');
    }
    public function scheme()
    {
        return $this->hasOne(GuideScheme::class, 'order_id', 'id');
    }

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

    public function asginSigner()
    {
        return $this->hasOne(AsignSigner::class, 'order_id', 'id')->whereIn('status', [0, 1, 2]);
    }

    public function asginContract()
    {
        return $this->hasOne(AsignContract::class, 'order_id', 'id')->whereIn('status', [0, 1, 2]);
    }

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

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

    public function afterDmaQuestion()
    {
        return $this->hasOne(DmaQuestion::class, "order_id", "id")->where("type", 1);
    }

    public function afterMedicalReport()
    {
        return $this->hasOne(MedicalReport::class, "user_id", "user_id")->where("type", 1);
    }

    public function scopeScheme($query)
    {
        $scheme = request()->scheme;
        if (is_numeric($scheme)) {
            if ($scheme) {
                return $query->whereIn('service_status', ['SCHEME', 'DELIVER', 'FINISHED']);
            } else {
                return $query->where('service_status', 'NOSCHEME');
            }
        }
        return $query;
    }

    /**
     * 已支付订单
     * @param $query
     * @return mixed
     */
    public function scopePaid($query)
    {
        return $query->where('pay_status', 'PAID');
    }

    /**
     * 没有绑定企业微信订单
     * @param $query
     * @return mixed
     */
    public function scopeNoWorkChatGroup($query)
    {
        return $query->whereHas('group', function ($sql) {
            $sql->whereNull('chat_id');
        });
    }

    /**
     * 订单关键词搜索
     * @param $query
     * @return mixed
     */
    public function scopeKeyword($query)
    {
        $keyword = trim(request()->keyword);
        if (!$keyword)
            return $query;
        return $query->where('name', 'like', '%' . $keyword . '%')->orWhere('mobile', 'like', '%' . $keyword . '%');
    }

    public function scopeServiceOrder($query)
    {
        return $query->where('type', 'SERVICE');
    }

    public static function getHaveOrder($user_id, $mobile)
    {
        $have_order = self::where('mobile', $mobile)->where('user_id', 0)->orderByDesc('id')->first();
        if ($have_order) {
            $have_order->user_id = $user_id;
            $have_order->save();
        }
    }

    //推荐人
    public function recommendUser()
    {
        return $this->hasOneThrough(User::class, RecommendUser::class, 'user_id', 'id', 'user_id', 'recommend_user_id')->selectRaw("ufutx_users.id, ufutx_users.name, ufutx_users.mobile");
    }

    public function updateServerStatus($user, $service_status, $delivery_img = "")
    {
        DB::beginTransaction();
        $order = Order::getPayOrder($user->id);
        $order->service_status = $service_status;
        if (!empty($delivery_img)) {
            $order->delivery_img = $delivery_img;
        }
        $order->save();
        MarkOrderLog::create(['order_id' => $order->id, 'operate_id' => $user->id, 'operate_name' => $user->name, 'remark' => "用户确认收货,修改server_status:" . $service_status]);
        DB::commit();
        return true;
    }

    /**
     * 获取用户已支付订单
     * @param $user_id
     * @return mixed
     */
    public static function getPayOrder($user_id)
    {
        $order = Order::whereHas("group", function ($sql) {
            $sql->where("service_type", 1);
        })->where('user_id', $user_id)->where('pay_status', 'PAID')->orderByDesc('id')->first();
        return $order;
    }


    /**
     * 订单可操作权限
     * @param mixed $role_ids // 有权限的角色id
     * @return void
     */
    public function orderAuthStatus($user_id, $role_ids): bool
    {
        // 查询当前用户在订单中的角色
        $has_role_ids = $this->serviceRoleOrders()->where("user_id", $user_id)->pluck("role_id")->toArray();
        // 订单外行政角色
        $admin_role_id = DmaServiceUserRole::where("user_id", $user_id)->where("role", ServiceRole::ADMINISTRATIVE)->value("role");
        if ($admin_role_id) {
            $has_role_ids[] = $admin_role_id;
        }
        Log::info("当前用户id: " . $user_id);
        Log::info("当前用户角色：" . json_encode($has_role_ids));
        Log::info("有权限角色: " . json_encode($role_ids));

        // 比较角色时候在有权限角色内
        $res = array_intersect($role_ids, $has_role_ids);
        return count($res) ? true : false;
    }
}
