package com.iotechn.unimall.app.api.commonUser;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.iotechn.unimall.biz.service.user.UserBizService;
import com.iotechn.unimall.core.Const;
import com.iotechn.unimall.core.exception.AppServiceException;
import com.iotechn.unimall.core.exception.ExceptionDefinition;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.core.exception.ThirdPartServiceException;
import com.iotechn.unimall.core.notify.SMSClient;
import com.iotechn.unimall.core.notify.SMSResult;
import com.iotechn.unimall.core.util.GeneratorUtil;
import com.iotechn.unimall.core.util.SHA1Util;
import com.iotechn.unimall.data.component.CacheComponent;
import com.iotechn.unimall.data.domain.UserDO;
import com.iotechn.unimall.data.domain.CommonUserInfo;
import com.iotechn.unimall.data.dto.UserDTO;
import com.iotechn.unimall.data.enums.UserLoginType;
import com.iotechn.unimall.data.mapper.UserMapper;
import com.iotechn.unimall.data.util.SessionUtil;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.apache.commons.codec.digest.Md5Crypt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.iotechn.unimall.data.mapper.CommonUserInfoMapper;
/**
 * Created by rize on 2019/6/30.
 */
@Service
public class CommonUserServiceImpl implements CommonUserService {

    private static final String VERIFY_CODE_PREFIX = "VERIFY_CODE_";

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

    @Autowired
    private CommonUserInfoMapper commonUserInfoMapper;


    @Autowired
    private StringRedisTemplate userRedisTemplate;

    private OkHttpClient okHttpClient = new OkHttpClient();

    @Value("${com.iotechn.unimall.wx.mini.app-id}")
    private String wxMiNiAppid;

    @Value("${com.iotechn.unimall.wx.mini.app-secret}")
    private String wxMiNiSecret;

    @Override
    public CommonUserInfo commonUserLogin(String ip, String raw) throws ServiceException, IOException {
        JSONObject thirdPartJsonObject = JSONObject.parseObject(raw);
        String code = thirdPartJsonObject.getString("code");
        String body = okHttpClient.newCall(new Request.Builder()
                .url("https://api.weixin.qq.com/sns/jscode2session?appid=" + wxMiNiAppid +
                        "&secret=" + wxMiNiSecret +
                        "&grant_type=authorization_code&js_code=" + code).get().build()).execute().body().string();
        JSONObject jsonObject = JSONObject.parseObject(body);
        Integer errcode = jsonObject.getInteger("errcode");
        if (errcode == null || errcode == 0) {
            String miniOpenId = jsonObject.getString("openid");
            List<CommonUserInfo> list = commonUserInfoMapper.selectList(new EntityWrapper<CommonUserInfo>().eq("open_id", miniOpenId));
            CommonUserInfo newUserDO;
            if (CollectionUtils.isEmpty(list)) {
                //若用户为空，则注册此用户
                Date now = new Date();
                newUserDO = new CommonUserInfo();
                newUserDO.setOpenId(miniOpenId);
                newUserDO.setGmtUpdate(now);
                newUserDO.setGmtCreate(now);
                commonUserInfoMapper.insert(newUserDO);
                //更新数据库默认值
                newUserDO = commonUserInfoMapper.selectById(newUserDO.getId());
            } else {
                newUserDO = list.get(0);
            }
            //检查帐号是否已经冻结
            if (newUserDO.getStatus() == 0) {
                throw new AppServiceException(ExceptionDefinition.USER_CAN_NOT_ACTICE);
            }
            String accessToken = GeneratorUtil.genSessionId();
            userRedisTemplate.opsForValue().set(Const.USER_REDIS_PREFIX + accessToken, JSONObject.toJSONString(newUserDO));
            newUserDO.setAccessToken(accessToken);
            newUserDO.setSessionKey(jsonObject.getString("session_key"));
            return newUserDO;
        } else {
            throw new AppServiceException(ExceptionDefinition.USER_THIRD_UNEXPECT_RESPONSE);
        }
    }

    @Override
    public CommonUserInfo edit(CommonUserInfo commonUserInfo) {
        commonUserInfoMapper.updateById(commonUserInfo);
        return commonUserInfo;
    }
}
