package com.ematou.wxservice.service;

import com.ematou.wxservice.api.WeChatApiRestTemplate;
import com.ematou.wxservice.common.utils.SmsUtil;
import com.ematou.wxservice.config.SmsConfig;
import com.ematou.wxservice.entity.pojo.ScannVO;
import com.ematou.wxservice.entity.pojo.UserInfo;
import com.ematou.wxservice.entity.vo.BindingInfo;
import com.ematou.wxservice.mapper.UserInfoMapper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lhm
 * @version 1.0
 * 2021-05-15 17:51
 */
@Service
public class UserInfoService {

    private static final Logger logger = LoggerFactory.getLogger(UserInfoService.class);

    @Autowired
    SmsConfig smsConfig;

    @Autowired
    WeChatService weChatService;

    @Autowired
    UserInfoMapper userInfoMapper;

    @Autowired
    WeChatApiRestTemplate weChatApiRestTemplate;
    @Value("${wx.general.appId}")
    private String appId;

    public UserInfo get(String openId, String phoneNumber){

        if (!StringUtils.hasLength(openId) && !StringUtils.hasLength(phoneNumber)) {
            logger.error("查询用户数据时，openId和phoneNumber必须要带有有其中一个！");
            return null;
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("openId", openId);
        map.put("phoneNumber", phoneNumber);
        return userInfoMapper.queryUserInfoByOpenIdOrPhoneNumber(map);
    }

    public String sendMsg(String phoneNumber,String openId){
        long time = System.currentTimeMillis();
        if (StringUtils.hasLength(phoneNumber)) {
            // 一分钟内不允许再次发送
            Long before = SmsUtil.map.get(phoneNumber);
            if (null != before && time - before <= (1000 * 60)) {
                return "短信已经发送过，请注意查收！";
            }
            String code = SmsUtil.createRandomVcode();
            String msg = SmsUtil.sendMsg(phoneNumber, smsConfig.getSmsUrl(), String.format(smsConfig.getSmsContent(), SmsUtil.COMPANY_NAME, code));
            if (!StringUtils.hasLength(msg)) {
                SmsUtil.map.remove(phoneNumber);
                return "短信发送失败，请重新发送！";
            }
            SmsUtil.map.remove(phoneNumber);
            updateOrInsertUserInfo(new UserInfo(phoneNumber, code, openId));
            return "";
        }
        SmsUtil.map.remove(phoneNumber);
        return "请输入手机号！";
    }

    public UserInfo queryUserInfoByPhoneNumber(String phoneNumber){
        return userInfoMapper.queryUserInfoByPhoneNumber(phoneNumber);
    }

    public UserInfo updateOrInsertUserInfo(UserInfo userInfo) {
        if (null == userInfo) {
            logger.error("用户信息为空，不能为空！");
            return null;
        }
        // 注解：
        // 这里如果使用openId查询和修改就能完美解决这个问题
        // 但是手机号是主键，修改时按手机号去修改。
        // 如果根据openId去修改主键，一来不符合规范，二来历史数据如果再触发此代码就会出问题，会出现主键重复无法修改的问题
        // 此处解决办法暂为在此系统使用openId查询数据时，增加部分字段不为空的条件，保证取到的数据是唯一且正常的数据
        UserInfo info = queryUserInfoByPhoneNumber(userInfo.getTellPhoneNumber());
        if (null != info) {
//            System.currentTimeMillis() - info.getTmst().getTime() > (1000 * 60 * 3)
            userInfoMapper.updateOrInsertUserInfo(userInfo);
            return userInfo;
        } else {
            userInfoMapper.insertUserInfo(userInfo);
            return userInfo;
        }

    }

    public boolean binding(BindingInfo bindingInfo) {
        if (null == bindingInfo) {
            logger.error("绑定信息不能为空!");
            return false;
        }

        Map<String, String> map = new HashMap<>();
        map.put("phoneNumber", bindingInfo.getTellPhoneNumber());
        UserInfo userInfo = userInfoMapper.queryUserInfoByOpenIdOrPhoneNumber(map);

        if (null == userInfo) {
            logger.error("使用手机号未查询到此用户信息!");
            return false;
        }
        if (!userInfo.getValidateCode().equals(bindingInfo.getValidateCode())) {
            logger.error("验证码错误!");
            return false;
        }
        UserInfo info = weChatService.getUserInfo(bindingInfo);
        info.setValidateCode(bindingInfo.getValidateCode());
        info.setTellPhoneNumber(bindingInfo.getTellPhoneNumber());
        userInfoMapper.updateOrInsertUserInfo(info);

        return true;
    }

    public ScannVO getScanningture() {
        ScannVO scannVO = new ScannVO();
        scannVO.setAppId(appId);
        return scannVO;
    }

    public UserInfo queryUserInfoByOpenId(String openId){
        return userInfoMapper.queryUserInfoByOpenId(openId);
    }



    /**
     * 获取签名
     * @param url
     * @return
     */
    public  Map<String, String> sign(String url) {
        Map<String, String> resultMap = new HashMap<>(16);

        return resultMap;
    }

    public void deleUserInfoService(String openId) {
         userInfoMapper.deleUserInfoService(openId);
    }
}
