<?php
namespace App\Models;

use App\Facades\TaskService;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class DmaProcessLog extends BaseModel
{
    use HasFactory;
    protected $table = 'dma_process_log';

    public static function addUserProcessLog($user_id = 0, $order_id = 0, $status = 0, $key_name, $remark, $operate_user_id = 0, $role = "")
    {
        $new_user_id = Order::query()->where("id", $order_id)->value("user_id");
        if (!empty($new_user_id)) {
            $user_id = $new_user_id;
        }
        $roleIdsStr = $role;
        if (empty($role) && $user_id != $operate_user_id) {
            $roleIds = ServiceRoleOrder::where("order_id", $order_id)->where("user_id", $operate_user_id)->pluck("role_id")?->toArray();
            $role = $roleIdsStr = implode(',', $roleIds);
        }
        $operate_name = "";
        if ($role == 4) {
            $operate_name = Admin::where("id", $operate_user_id)->value("name");
        }
        if ($role != 0 && !in_array($role, [4, 5])) {
            $operate_name = User::where("id", $operate_user_id)->value("name");
        }
        if (!empty($operate_name)) {
            $operate_name = $operate_name . "·";
        }
        if ($user_id > 0) {
            $map = [];
            $map["user_id"] = $user_id;
            $map["order_id"] = $order_id;
            $map["key_name"] = $key_name;
            $map["remark"] = $operate_name . $remark;
            $map["status"] = $status;
            $map["role"] = $roleIdsStr;
            $map["operate_user_id"] = $operate_user_id;
            self::query()->create($map);
        }

        TaskService::checkTask($order_id, $key_name);

    }
}