<?php

namespace App\Services;

use App\Models\DmaProcessLog;
use App\Models\DmaServiceUserRole;
use App\Models\S2CustomerTask;
use App\Models\ServiceRoleOrder;
use App\Models\User;


class TaskService
{
    public function AddTask($userId, $customerId, $theme, $dmaServiceId = [], $orderId = 0, $detail = "", $principal = "", $remindTime = "", $processKey = "", $excludeUserIds = []): bool
    {
        $keyName = "";
        $taskType = "DMA";
        if (empty($userId) && count($dmaServiceId) == 0)
            return false;
        if (empty($theme))
            return false;
        if ($processKey) {
            $log = DmaProcessLog::where("order_id", $orderId)->where("key_name", $processKey)->first();
            if ($log)
                return false;
            $keyName = $processKey . "_" . $orderId;
        }
        if (empty($detail))
            $detail = $theme;
        if (empty($remindTime))
            $remindTime = date("Y-m-d H:i:s", strtotime("+1 day"));
        if ($userId > 0) {
            if (empty($principal)) {
                $user = User::find($userId);
                if ($user) {
                    $principal = $user->name;
                }
            }
            S2CustomerTask::create([
                "user_id" => $userId,
                "key_name" => $keyName,
                "remind_time" => $remindTime,
                "principal" => $principal,
                "customer_id" => $customerId,
                "theme" => $theme,
                "detail" => $detail,
                "type" => $taskType,
                "status" => 0,
            ]);
        } else {
            if ($orderId) {
                $user_ids = ServiceRoleOrder::where("order_id", $orderId)->whereIn("role_id", $dmaServiceId)->pluck("user_id")->toArray();
            } else {
                $user_ids = DmaServiceUserRole::whereIn("role", $dmaServiceId)->where('status', 1)->pluck("user_id")->toArray();
            }

            $users = User::whereIn("id", $user_ids)->whereNotIn("id", $excludeUserIds)->get();
            foreach ($users as $user) {
                S2CustomerTask::create([
                    "user_id" => $user->id,
                    "key_name" => $keyName,
                    "remind_time" => $remindTime,
                    "principal" => $user->name ?: "",
                    "customer_id" => $customerId,
                    "theme" => $theme,
                    "detail" => $detail,
                    "type" => $taskType,
                    "status" => 0,
                ]);
            }
        }

        return true;
    }

    public function checkTask($orderId, $processKey)
    {
        if (empty($orderId))
            return;
        $keyName = $processKey . "_" . $orderId;
        S2CustomerTask::where("key_name", $keyName)->update(["status" => 1]);
    }
}