package com.crm.custom.service.impl;

import com.crm.custom.dao.repository.SysCountryRepository;
import com.crm.custom.service.SysCountryService;
import com.crm.rely.backend.core.constant.CustomConstant;
import com.crm.rely.backend.core.dto.country.SysCountryDto;
import com.crm.rely.backend.core.entity.country.SysCountryEntity;
import com.crm.rely.backend.core.pojo.table.SysCountryTable;
import com.crm.rely.backend.core.exception.ServiceException;
import com.google.common.base.Strings;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CountryResponse;
import com.maxmind.geoip2.record.Country;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

@Service
public class SysCountryServiceImpl implements SysCountryService {

    private static DatabaseReader databaseReader;

    @Autowired
    private SysCountryRepository sysCountryRepository;

    @Override
    public List<SysCountryDto> getByPid(SysCountryEntity entity) throws ServiceException {

        List<SysCountryTable> sysCountryTables = sysCountryRepository.getAllByPidAndValidForStartedOrderByEnName(entity.getPid(), 1);

//        boolean isCn = Constants.CN_LANG.equals(entity.getLang());

        List<SysCountryDto> sysCountryDtos = new ArrayList<>();

        for (SysCountryTable sysCountryTable : sysCountryTables) {
            SysCountryDto sysCountryDto = new SysCountryDto();
            BeanUtils.copyProperties(sysCountryTable, sysCountryDto);

            //判断是否是中国 不是则返回英文名称
//            if (!isCn) {
//                sysCountryDto.setName(sysCountryTable.getEnName());
//            }
            sysCountryDtos.add(sysCountryDto);
        }

        return sysCountryDtos;
    }

    @Override
    public SysCountryTable getByCode(String code) throws ServiceException {

        //判断code不为空
        if (Strings.isNullOrEmpty(code)) {
            throw new ServiceException(CustomConstant.COUNTRY_NOT_NULL);
        }

        SysCountryTable sysCountryTable = sysCountryRepository.getByCode(code);
        if (sysCountryTable == null) {
            throw new ServiceException(CustomConstant.COUNTRY_NOT_EXIST_ERROR);
        }

        return sysCountryTable;
    }

    private static DatabaseReader getReader() {
        try {
            if (databaseReader == null) {
//                File file = new File(SysCountryServiceImpl.class.getClassLoader().getResource("country/GeoLite2-Country.mmdb").getFile());
                InputStream inputStream = SysCountryServiceImpl.class.getClassLoader().getResourceAsStream("country/GeoLite2-Country.mmdb");
                databaseReader = new DatabaseReader.Builder(inputStream).build();
                inputStream.close();
                return databaseReader;
            } else {
                return databaseReader;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return databaseReader;
        }
    }


    @Override
    public String getCodeByIp(String ip) throws Exception {
        Country country = null;
        try {
            InetAddress inetAddress = InetAddress.getByName(ip);
            CountryResponse countryResponse = getReader().country(inetAddress);
            country = countryResponse.getCountry();
        } catch (Exception e) {
            country = null;
        }

        if(country != null){
            if ("HK".equalsIgnoreCase(country.getIsoCode())){
                return "CNX";
            }else if ("TWN".equalsIgnoreCase(country.getIsoCode())){
                return "CNT";
            }else if ("TW".equalsIgnoreCase(country.getIsoCode())){
                return "CNT";
            }else if ("MC".equalsIgnoreCase(country.getIsoCode())){
                return "CNA";
            }
        }
        return country != null ? country.getIsoCode() : null;
    }
}
