<?php

declare(strict_types=1);

namespace app\admin\model\split;

use app\common\service\SplitPlatformDomainService;
use think\Db;
use think\Model;

/**
 * 分流号码模型
 */
class Number extends Model
{
    protected $name = 'split_number';

    protected static function init(): void
    {
        self::beforeInsert(function (self $row): void {
            if ((int) ($row['weigh'] ?? 0) > 0) {
                return;
            }
            $linkId = (int) ($row['split_link_id'] ?? 0);
            if ($linkId <= 0) {
                return;
            }
            $maxWeigh = (int) self::where('split_link_id', $linkId)->max('weigh');
            $row->setAttr('weigh', $maxWeigh + 1);
        });
    }

    protected $autoWriteTimestamp = 'integer';

    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    protected $append = [
        'number_type_text',
        'link_url_text',
        'status_text',
        'manual_manage_text',
        'platform_status_text',
    ];

    /**
     * 号码类型（与工单模块一致）
     *
     * @return array<string, string>
     */
    public function getNumberTypeList(): array
    {
        return [
            'whatsapp' => 'WhatsApp',
            'telegram' => 'Telegram',
            'line'     => 'Line',
            'custom'   => __('Number type custom'),
        ];
    }

    /**
     * @return array<string, string>
     */
    public function getStatusList(): array
    {
        return [
            'normal' => __('Status normal'),
            'hidden' => __('Status hidden'),
        ];
    }

    /**
     * @return array<string, string>
     */
    public function getManualManageList(): array
    {
        return [
            '0' => __('Manual manage no'),
            '1' => __('Manual manage yes'),
        ];
    }

    /**
     * @return array<string, string>
     */
    public function getPlatformStatusList(): array
    {
        return [
            'online'  => __('Platform status online'),
            'offline' => __('Platform status offline'),
            'unknown' => __('Platform status unknown'),
        ];
    }

    /**
     * 关联分流链接
     */
    public function splitLink()
    {
        return $this->belongsTo(Link::class, 'split_link_id', 'id', [], 'LEFT')->setEagerlyType(1);
    }

    public function setNumberTypeCustomAttr($value): string
    {
        return trim((string) $value);
    }

    public function setManualManageAttr($value): int
    {
        return (int) $value === 1 ? 1 : 0;
    }

    public function getNumberTypeTextAttr($value, $data): string
    {
        $type = (string) ($data['number_type'] ?? '');
        if ($type === 'custom') {
            $custom = trim((string) ($data['number_type_custom'] ?? ''));
            return $custom !== '' ? $custom : (string) __('Number type custom');
        }
        $list = $this->getNumberTypeList();
        return $list[$type] ?? $type;
    }

    /**
     * 列表展示用：仅显示分流链接码（非完整 URL）
     */
    public function getLinkUrlTextAttr($value, $data): string
    {
        if (isset($data['split_link']) && is_array($data['split_link'])) {
            return (string) ($data['split_link']['link_code'] ?? '');
        }
        $linkId = (int) ($data['split_link_id'] ?? 0);
        if ($linkId <= 0) {
            return '';
        }
        return (string) Link::where('id', $linkId)->value('link_code');
    }

    public function getStatusTextAttr($value, $data): string
    {
        $key = (string) ($data['status'] ?? '');
        $list = $this->getStatusList();
        return $list[$key] ?? $key;
    }

    public function getManualManageTextAttr($value, $data): string
    {
        $key = (string) ((int) ($data['manual_manage'] ?? 0));
        $list = $this->getManualManageList();
        return $list[$key] ?? $key;
    }

    public function getPlatformStatusTextAttr($value, $data): string
    {
        $key = (string) ($data['platform_status'] ?? 'unknown');
        $list = $this->getPlatformStatusList();
        return $list[$key] ?? $key;
    }

    /**
     * 根据链接码生成完整分流 URL
     */
    public static function buildLinkUrl(string $linkCode): string
    {
        $linkCode = trim($linkCode);
        if ($linkCode === '') {
            return '';
        }
        $raw = trim((string) \think\Config::get('site.split_platform_domain'));
        if ($raw === '') {
            $raw = trim((string) Db::name('config')->where('name', 'split_platform_domain')->value('value'));
        }
        $domains = SplitPlatformDomainService::parseList($raw);
        $domain = $domains[0] ?? '';
        if ($domain === '') {
            return '';
        }
        return 'https://' . $domain . '/s/' . $linkCode;
    }

    /**
     * 解析 textarea 号码列表
     *
     * @return array<int, string>
     */
    public static function parseNumbersText(string $text): array
    {
        $lines = preg_split('/\r\n|\r|\n/', $text) ?: [];
        $numbers = [];
        foreach ($lines as $line) {
            $num = trim((string) $line);
            if ($num === '') {
                continue;
            }
            $numbers[$num] = $num;
        }
        return array_values($numbers);
    }
}
