package com.ruoyi.jarvis.service.impl;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.jarvis.domain.TgScalperPhone;
import com.ruoyi.jarvis.mapper.TgScalperPhoneMapper;
import com.ruoyi.jarvis.service.ITgScalperPhoneService;

@Service
public class TgScalperPhoneServiceImpl implements ITgScalperPhoneService
{
    private static final Pattern MOBILE_11 = Pattern.compile("^1\\d{10}$");

    @Autowired
    private TgScalperPhoneMapper tgScalperPhoneMapper;

    @Override
    public TgScalperPhone selectTgScalperPhoneById(Long id)
    {
        return tgScalperPhoneMapper.selectTgScalperPhoneById(id);
    }

    @Override
    public List<TgScalperPhone> selectTgScalperPhoneList(TgScalperPhone q)
    {
        return tgScalperPhoneMapper.selectTgScalperPhoneList(q);
    }

    @Override
    public TgScalperPhone selectEnabledByPhone(String phone)
    {
        if (!StringUtils.hasText(phone))
        {
            return null;
        }
        String p = phone.trim();
        if (!MOBILE_11.matcher(p).matches())
        {
            return null;
        }
        return tgScalperPhoneMapper.selectEnabledByPhone(p);
    }

    @Override
    public int insertTgScalperPhone(TgScalperPhone row)
    {
        String phonesJson = normalizePhonesJson(row.getPhones());
        row.setPhones(phonesJson);
        if (!StringUtils.hasText(row.getRemark()))
        {
            throw new ServiceException("备注不能为空");
        }
        assertNoPhoneConflictAcrossRows(null, phonesJson);
        if (row.getStatus() == null)
        {
            row.setStatus(1);
        }
        return tgScalperPhoneMapper.insertTgScalperPhone(row);
    }

    @Override
    public int updateTgScalperPhone(TgScalperPhone row)
    {
        String phonesJson = normalizePhonesJson(row.getPhones());
        row.setPhones(phonesJson);
        if (!StringUtils.hasText(row.getRemark()))
        {
            throw new ServiceException("备注不能为空");
        }
        assertNoPhoneConflictAcrossRows(row.getId(), phonesJson);
        return tgScalperPhoneMapper.updateTgScalperPhone(row);
    }

    @Override
    public int deleteTgScalperPhoneByIds(Long[] ids)
    {
        return tgScalperPhoneMapper.deleteTgScalperPhoneByIds(ids);
    }

    @Override
    public int deleteTgScalperPhoneById(Long id)
    {
        return tgScalperPhoneMapper.deleteTgScalperPhoneById(id);
    }

    private void assertNoPhoneConflictAcrossRows(Long excludeId, String phonesJson)
    {
        for (String cell : parseDistinctPhones(phonesJson))
        {
            Long hit = tgScalperPhoneMapper.selectIdHavingPhone(excludeId, cell);
            if (hit != null)
            {
                throw new ServiceException("手机号已在其他记录中出现：" + cell);
            }
        }
    }

    /** 接受 JSON 数组字符串或非 JSON 的单个号码，规范为 JSON 数组字符串 */
    private static String normalizePhonesJson(String raw)
    {
        if (!StringUtils.hasText(raw))
        {
            throw new ServiceException("请至少填写一个11位手机号");
        }
        String s = raw.trim();
        List<String> cells = new ArrayList<>();
        if (s.startsWith("["))
        {
            try
            {
                JSONArray arr = JSON.parseArray(s);
                for (int i = 0; i < arr.size(); i++)
                {
                    Object o = arr.get(i);
                    if (o != null)
                    {
                        cells.add(String.valueOf(o).trim());
                    }
                }
            }
            catch (Exception e)
            {
                throw new ServiceException("phones 须为 JSON 数组，如 [\"13800138000\"]");
            }
        }
        else
        {
            for (String part : s.split("[,，;；\\s]+"))
            {
                String t = part.trim();
                if (StringUtils.hasText(t))
                {
                    cells.add(t);
                }
            }
        }
        Set<String> uniq = new LinkedHashSet<>();
        for (String c : cells)
        {
            if (!MOBILE_11.matcher(c).matches())
            {
                throw new ServiceException("请输入正确的11位手机号：" + c);
            }
            uniq.add(c);
        }
        if (uniq.isEmpty())
        {
            throw new ServiceException("请至少填写一个11位手机号");
        }
        return JSON.toJSONString(new ArrayList<>(uniq));
    }

    private static List<String> parseDistinctPhones(String phonesJson)
    {
        List<String> out = new ArrayList<>();
        try
        {
            JSONArray arr = JSON.parseArray(phonesJson);
            for (int i = 0; i < arr.size(); i++)
            {
                Object o = arr.get(i);
                if (o != null)
                {
                    out.add(String.valueOf(o).trim());
                }
            }
        }
        catch (Exception e)
        {
            throw new ServiceException("数据损坏：phones 非合法 JSON 数组");
        }
        return out;
    }
}
