package com.loan.system.service.Impl;

import com.alibaba.fastjson.JSON;
import com.loan.system.constant.MessageConstant;
import com.loan.system.domain.dto.UserLoginDTO;
import com.loan.system.domain.entity.BizRecommender;
import com.loan.system.domain.entity.Customer;
import com.loan.system.domain.entity.User;
import com.loan.system.domain.enums.ExceptionEnum;
import com.loan.system.domain.pojo.Result;
import com.loan.system.exception.DescribeException;
import com.loan.system.properties.WeChatProperties;
import com.loan.system.repository.CustomerRepository;
import com.loan.system.repository.RecommenderRepository;
import com.loan.system.repository.UserRepository;
import com.loan.system.service.UserService;
import com.loan.system.utils.HttpClientUtil;
import com.loan.system.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    private final UserRepository userRepository;
    private final CustomerRepository customerRepository;
    private final RecommenderRepository recommenderRepository;
    private final WeChatProperties weChatProperties;
    private final StringRedisTemplate redisTemplate;
    public static final String WX_LOGIN="https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    public UserServiceImpl(UserRepository userRepository, CustomerRepository customerRepository, RecommenderRepository recommenderRepository,
                           WeChatProperties weChatProperties, StringRedisTemplate redisTemplate) {
        this.userRepository = userRepository;
        this.customerRepository = customerRepository;
        this.recommenderRepository = recommenderRepository;
        this.weChatProperties = weChatProperties;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public User getUserByMobile(String mobile) {
        return userRepository.findByMobile(mobile);
    }


    @Override
    public List<Customer> getAllCustomers(Boolean isDelete) {
        return customerRepository.findByIsDelete(isDelete);
    }

    @Override
    public List<User> getAllUsers(Boolean isDelete) {
        return userRepository.findByIsDelete(isDelete);
    }

    @Override
    public List<BizRecommender> getAllRecommenders(Boolean isDelete) {
        return recommenderRepository.findByIsDelete(isDelete);
    }


//    @Override
//    public User wxLogin(UserLoginDTO userLoginDTO) {
//        //调用微信接口服务，获得当前微信用户的openid
//        String openid=getOpenid(userLoginDTO.getCode());
//
//        //判断openid是否为空，如果为空表示登录失败，抛出业务异常
//        if (openid==null)
//            throw new DescribeException(ExceptionEnum.LOGIN_EXPIRED);
//
//        //判断当前用户是否为新用户
//        User user = userRepository.findByMobile(userLoginDTO.getTel());
////        if(user==null)
////        {
////            user = User.builder()
////                    .openid(openid)
////                    .createTime(LocalDateTime.now())
////                    .build();
////            userMapper.insert(user);
////        }
//
//
//        //返回这个用户对象
//        return user;
//    }

//    private String getOpenid(String code){
//        Map<String,String> map=new HashMap<>();
//        map.put("appid",weChatProperties.getAppid());
//        map.put("secret",weChatProperties.getSecret());
//        map.put("js_code",code);
//        map.put("grant_type","authorization_code");
//        String json = HttpClientUtil.doGet(weChatProperties.getLoginUrl(), map);
//
//        JSONObject jsonObject= JSON.parseObject(json);
//        String openid = jsonObject.getString("openid");
//
//        return openid;
//    }

    @Override
    public Result get_sessionId(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session"
                + "?appid=" + weChatProperties.getAppid()
                + "&secret=" + weChatProperties.getSecret()
                + "&js_code=" + code
                + "&grant_type=authorization_code";

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        String res = "";
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                res = response.body().string();
                log.info("成功获取数据: {}", res);

                // 解析返回的JSON数据
                JSONObject obj = new JSONObject(res);
                String openid = obj.getString("openid");
                String sessionKey = obj.getString("session_key");

                // 存储到Redis
                String uuid = UUID.randomUUID().toString();
                Map<String, String> sessionData = new HashMap<>();
                sessionData.put("openid", openid);
                sessionData.put("session_key", sessionKey);
                redisTemplate.opsForValue().set("wx_session_id_" + uuid,
                        JSON.toJSONString(sessionData), 30, TimeUnit.MINUTES);

                Map<String, String> result = new HashMap<>();
                result.put("session_id", uuid);
                result.put("openid", openid);
                return ResultUtil.success("success", result);

            } else {
                String body = response.body().string();
                try {
                    JSONObject obj = new JSONObject(body);
                    int errCode = obj.getInt("errcode");
                    String errMsg = obj.getString("errmsg");
                    return ResultUtil.error(errCode, errMsg);
                } catch (Exception e) {
                    return ResultUtil.error(response.code(), "服务器返回格式异常");
                }
            }
        } catch (Exception e) {
            log.error("获取 session_id 失败，code: {}, error: {}", code, e.getMessage());
            return ResultUtil.error(500, "网络异常");
        }
    }

    /**
     * 根据手机号查询用户
     * @param phoneNumber
     * @return
     */
    @Override
    public boolean existsByMobileAndIsDelete(String phoneNumber){
        return userRepository.existsByMobileAndIsDelete(phoneNumber,false);
    }
    @Override
    public User findByPhoneNumberAndIsDelete(String phoneNumber){
        return userRepository.findByMobileAndIsDelete(phoneNumber,false);
    }
    @Override
    public User findByIdAndIsDelete(Long id){
        return userRepository.findByIdAndIsDelete(id,false);
    }

}