<?php

namespace app\api\service;

use think\facade\Cache;

class UtilService
{

    const TOKEN_PREFIX = 'sms_token:';


//    public static function generateOrderNo($userId = 0,$str=null)
//    {
//        $microtime = microtime(true);
//        $timestamp = date('YmdHis') . substr($microtime, 11, 3);
//
//
//        $random = str_pad(mt_rand(0, 999999), 6, '0', STR_PAD_LEFT);
//
//
//        $userPart = $userId ? substr(str_pad($userId, 4, '0', STR_PAD_LEFT), -4) : '';
//
//
//        return $str.'-'. $timestamp . $random . ($userPart ? ('-' . $userPart) : '');
//    }

    //生成订单号 示例 ORD-042-230815123456789
    public static function generateCompactOrderNo($userId = null, $prefix = null)
    {
        $time = date('ymdHis');
        $rand = mt_rand(100, 999);
        $userCode = $userId ? str_pad($userId % 1000, 3, '0', STR_PAD_LEFT) : '';

        return trim(implode('-', array_filter([$prefix, $userCode, $time.$rand])), '-');
    }

    public static function listWithTags($list, string $modelClass, string $tagIdsField = 'tag_ids'): array
    {
        $allTagIds = [];
        foreach ($list->items() as $item) {
            if (!empty($item->{$tagIdsField})) {
                $tagIds = explode(',', $item->{$tagIdsField});
                $allTagIds = array_merge($allTagIds, $tagIds);
            }
        }

        $tags = [];
        if (!empty($allTagIds)) {
            $tags = $modelClass::where('is_del', 0)
                ->whereIn('id', array_unique($allTagIds))
                ->field('id,title')
                ->select()
                ->toArray();
            $tags = array_column($tags, null, 'id');
        }

        $result = $list->toArray();
        foreach ($result['data'] as &$item) {
            $itemTags = [];
            if (!empty($item[$tagIdsField])) {
                $tagIds = explode(',', $item[$tagIdsField]);
                foreach ($tagIds as $tagId) {
                    if (isset($tags[$tagId])) {
                        $itemTags[] = $tags[$tagId];
                    }
                }
            }
            $item['tags'] = $itemTags;
        }

        return $result;
    }

    public static function checkSmsCode($mobile, $code)
    {
        $cacheCode = Cache::get(self::TOKEN_PREFIX.$mobile);
        if ($code!=$cacheCode)
        {
            return false;
        }
        return true;
    }
}