<?php

declare(strict_types=1);

namespace app\admin\model\split;

use app\common\library\CountryIso;
use think\Model;

/**
 * 分流链接模型
 */
class Link extends Model
{
    protected $name = 'split_link';

    protected $autoWriteTimestamp = 'integer';

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

    protected $append = [
        'countries_text',
        'auto_reply_text',
        'ip_protect_text',
        'random_shuffle_text',
        'status_text',
    ];

    public function getIpProtectList(): array
    {
        return [
            '0' => __('Ip protect off'),
            '1' => __('Ip protect on'),
        ];
    }

    public function getRandomShuffleList(): array
    {
        return [
            '0' => __('Random shuffle off'),
            '1' => __('Random shuffle on'),
        ];
    }

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

    public function setCountriesAttr($value): string
    {
        if (is_array($value)) {
            return CountryIso::codesToStorage($value);
        }
        return CountryIso::codesToStorage(explode(',', (string)$value));
    }

    /**
     * 分流链接码统一为小写
     */
    public function setLinkCodeAttr($value): string
    {
        return strtolower(trim((string) $value));
    }

    /**
     * 自动回复：存储为一行一条（换行分隔）
     *
     * @param mixed $value
     */
    public function setAutoReplyAttr($value): string
    {
        return \app\common\service\SplitAutoReplyService::formatStorage($value);
    }

    /**
     * 自动回复语句数组
     *
     * @return array<int, string>
     */
    public function getAutoReplyLines(): array
    {
        return \app\common\service\SplitAutoReplyService::parseLines((string) $this->getAttr('auto_reply'));
    }

    public function getCountriesTextAttr($value, $data): string
    {
        return CountryIso::codesToText((string)($data['countries'] ?? ''));
    }

    /**
     * 列表「回复语」列预览（最多 50 字 + ...，悬停用原始 auto_reply 换行展示）
     */
    public function getAutoReplyTextAttr($value, $data): string
    {
        return \app\common\service\SplitAutoReplyService::previewForList((string) ($data['auto_reply'] ?? ''));
    }

    public function getIpProtectTextAttr($value, $data): string
    {
        $value = $value !== '' && $value !== null ? $value : ($data['ip_protect'] ?? '');
        $list = $this->getIpProtectList();
        return $list[(string)$value] ?? '';
    }

    public function getRandomShuffleTextAttr($value, $data): string
    {
        $value = $value !== '' && $value !== null ? $value : ($data['random_shuffle'] ?? '');
        $list = $this->getRandomShuffleList();
        return $list[(string)$value] ?? '';
    }

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

    /**
     * 已选国家 ISO 代码数组（供编辑表单多选回显）
     *
     * @return array<int, string>
     */
    public function getSelectedCountries(): array
    {
        $countries = (string)$this->getAttr('countries');
        if ($countries === '') {
            return [];
        }
        return CountryIso::normalizeCodes(explode(',', $countries));
    }
}
