package com.cool.store.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cool.store.dao.HyPhoneLocationDAO;
import com.cool.store.dto.partner.DescribePhoneNumberDTO;
import com.cool.store.dto.wx.PhoneInfoDTO;
import com.cool.store.entity.HyPhoneLocationDO;
import com.cool.store.mapper.HyPhoneLocationMapper;
import com.cool.store.service.AliyunService;
import com.cool.store.service.HyPhoneLocationService;
import com.cool.store.utils.RedisConstantUtil;
import com.cool.store.utils.RedisUtilPool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author suzhuhong
 * @Date 2023/6/30 15:04
 * @Version 1.0
 */
@Service
@Slf4j
public class HyPhoneLocationServiceImpl implements HyPhoneLocationService {
    @Resource
    HyPhoneLocationDAO hyPhoneLocationDAO;
    @Resource
    AliyunService aliyunService;
    @Resource
    RedisUtilPool redisUtilPool;
    @Resource
    RedisConstantUtil redisConstantUtil;

    @Override
    public String handleHyPhoneAddress(String phoneNumber) {
        if (StringUtils.isEmpty(phoneNumber)){
            return "";
        }
        String phone = redisUtilPool.getString(redisConstantUtil.getPhoneNumber(phoneNumber));
        if (StringUtils.isNotEmpty(phone)){
            DescribePhoneNumberDTO describePhoneNumberDTO = JSONObject.parseObject(phone, DescribePhoneNumberDTO.class);
            return String.format("%s %s", describePhoneNumberDTO.getProvince(), describePhoneNumberDTO.getCity());
        }
        HyPhoneLocationDO hyPhoneLocationDO = hyPhoneLocationDAO.selectByPhoneNumber(phoneNumber);
        if (hyPhoneLocationDO==null){
            try {
                DescribePhoneNumberDTO phoneNumberAttribute = aliyunService.getPhoneNumberAttribute(phoneNumber);
                HyPhoneLocationDO hy = new HyPhoneLocationDO();
                hy.setPhoneNumber(phoneNumber);
                hy.setPhoneAddress(String.format("%s %s", phoneNumberAttribute.getProvince(), phoneNumberAttribute.getCity()));
                hyPhoneLocationDAO.insertSelective(hy);
                //redis一周时间
                redisUtilPool.setString(redisConstantUtil.getPhoneNumber(phoneNumber),JSONObject.toJSONString(phoneNumberAttribute),7*24*60*60);
                return hy.getPhoneAddress();
            }catch (Exception e){
                return "未知";
            }
        }
        return hyPhoneLocationDO.getPhoneAddress();
    }
}
