package com.loan.system.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    private final UserRepository userRepository;
    private final CustomerRepository customerRepository;
    private final RecommenderRepository recommenderRepository;
    private final WeChatProperties weChatProperties;
    public static final String WX_LOGIN="https://api.weixin.qq.com/sns/jscode2session";

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

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

    @Override
    public Customer getCustomerByMobile(String mobile) {
        return customerRepository.findByMobile(mobile, false);
    }

    @Override
    public void addCustomer(Customer  customer) {
        customerRepository.save(customer);
    }

    @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 Customer getCustomerById(Long id , Boolean isDelete) {
        return customerRepository.findByIdAndIsDelete(id,isDelete);
    }

    @Override
    public Customer getCustomerByKey(String key, boolean b) {
        return customerRepository.findByKey(key,b);
    }

    @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;
    }

    @Override
    public User findByIdAndIsDelete(Long userId) {
        return userRepository.findByUserIdAndIsDelete(userId, false);
    }

    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;
    }

}