package org.jeecg.modules.xcx.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.bean.ConvertUtils;
import org.jeecg.modules.bean.HttpConf;
import org.jeecg.modules.bean.LoginReq;
import org.jeecg.modules.hanHaiMember.entity.HanHaiMember;
import org.jeecg.modules.hanHaiMember.service.IHanHaiMemberService;
import org.jeecg.modules.hotelmemberaccount.entity.HotelMemberAccount;
import org.jeecg.modules.hotelmemberaccount.service.IHotelMemberAccountService;
import org.jeecg.modules.hotelshop.entity.HotelShop;
import org.jeecg.modules.hotelshop.service.IHotelShopService;
import org.jeecg.modules.xcx.user.service.ILoginService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
public class LoginServiceImpl implements ILoginService {

    //公共用户表
    @Resource
    private IHanHaiMemberService hanHaiMemberService;

    //公共缓存类
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private HttpConf httpConf;



    /**
     * 微信公众号-appid
     */
    @Value("${weixin.mpAppId}")
    private String mpAppId;

    /**
     * 微信公众号-appSecret
     */
    @Value("${weixin.mpAppSecret}")
    private String mpAppSecret;
    @Resource
    private IHanHaiMemberService memberService;
    @Resource
    private IHotelMemberAccountService hotelMemberAccountService;
    @Resource
    private IHotelShopService hotelShopService;


    /**
     * 公众号授权登录注册
     * @param loginReq
     * @return
     */
    @Override
    @Transactional(rollbackOn = Exception.class)
    public Result<?> officialLogin(LoginReq loginReq){
        Result<Object> result = new Result<>();
        Map<String, Object> map = new HashMap<>();
        if(loginReq.getLoginType() == 0){
            if (StringUtils.isBlank(loginReq.getCode())) {
                throw new JeecgBootException("小程序code为空");
            }
            String loginUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + mpAppId + "&secret=" + mpAppSecret+ "&js_code=" + loginReq.getCode() + "&grant_type=authorization_code";
            //使用工具类
            JSONObject json_test = httpConf.getJSONObject(loginUrl);
            String wxOpenid = json_test.getString("openid");
            String sessionKey = json_test.getString("session_key");
            if (StringUtils.isBlank(wxOpenid)) {
                throw new JeecgBootException("未获取到openid");
            }

            HanHaiMember member = memberService.lambdaQuery().eq(HanHaiMember::getAppletOpenid,wxOpenid).one();
            if (member == null) {
                if (loginReq.getLatitude() == null || loginReq.getLatitude() == 0 || loginReq.getLongitude() == null || loginReq.getLongitude() == 0){
                    throw new JeecgBootException("请授权定位信息");
                }
                HotelShop hotelShop = hotelShopService.getDistance(loginReq.getLatitude(), loginReq.getLongitude());
                if(hotelShop == null){
                    throw new JeecgBootException("目前无水洗店可绑定，请联系客服处理");
                }
                //如果user等于null说明该用户第一次登录，数据库没有该用户信息。
                loginReq.setOpenid(wxOpenid);
                loginReq.setSession_key(sessionKey);
                member = new HanHaiMember();
//            member.setSesssionKey(sessionKey);
                member.setAppletOpenid(wxOpenid);
                member.setNickName(loginReq.getNickName());
                member.setHeadImage(loginReq.getHeadimgurl());
                member.setShopId(hotelShop.getId());
                // 生成token返回给小程序端
                String token = JwtUtil.sign(member.getAppletOpenid(), wxOpenid);
                memberService.save(member);
                HotelMemberAccount hotelMemberAccount = new HotelMemberAccount();
                hotelMemberAccount.setUserId(member.getId());
                hotelMemberAccountService.save(hotelMemberAccount);
                redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
                // 设置超时时间
                redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 100);
                map.put("userInfo", member);
                map.put("token", token);

                result.setCode(200);
                result.setResult(map);
                return result;
            } else {
//            member.setHeadImage(loginReq.getHeadimgurl());
//            member.setSessionKey(sessionKey);
//            memberService.saveOrUpdate(member);
                // 生成token返回给小程序端
                String token = JwtUtil.sign(member.getAppletOpenid(), wxOpenid);
                redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
                // 设置超时时间
                redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 100);
                map.put("userInfo", member);
                map.put("token", token);
                //用户id做im账号
                result.setResult(map);
                result.setCode(200);
//            result.setMessage(member.getNickName()+"已于"+member.getCreateTime()+"注册成功！请勿重复注册！");
//            // 未绑定手机号，跳转授权绑定手机号
//            if (StringUtils.isBlank(member.getPhone())) {
//                result.setMessage("该微信用户尚未绑定手机号，请授权手机进行绑定");
//                result.setCode(905);
//                result.setResult(map);
//                return result;
//            }
            }
        }else{
            if(org.apache.commons.lang3.StringUtils.isBlank(loginReq.getAccount())){
                throw new JeecgBootException("请输入账号");
            }
            if(org.apache.commons.lang3.StringUtils.isBlank(loginReq.getPassword())){
                throw new JeecgBootException("请输入密码");
            }
            HanHaiMember hanHaiMember = hanHaiMemberService.lambdaQuery()
                    .eq(HanHaiMember::getPhone, loginReq.getAccount())
                    .one();

            if(hanHaiMember == null){
                throw new JeecgBootException("账号未注册");
            }

            String encrypt = PasswordUtil.encrypt(loginReq.getPassword(), loginReq.getAccount(), hanHaiMember.getPasswordSalt());
            if(!org.apache.commons.lang3.StringUtils.equals(encrypt,hanHaiMember.getPassword())){
                throw new JeecgBootException("密码不正确");
            }

            HotelShop hotelShop = hotelShopService.lambdaQuery()
                    .eq(HotelShop::getDelFlag, 0)
                    .eq(HotelShop::getStatus,1)
                    .eq(HotelShop::getUserId, hanHaiMember.getId())
                    .one();
            if(hotelShop == null){
                throw new JeecgBootException("您还不是水洗店，无法使用账号密码登录！");
            }
            hanHaiMember.setShop(hotelShop);
            String token = JwtUtil.sign(hanHaiMember.getPhone(), hanHaiMember.getPassword());
            redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
            // 设置超时时间
            redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 100);
            map.put("userInfo", hanHaiMember);
            map.put("token", token);
            //用户id做im账号
            result.setResult(map);
            result.setCode(200);
        }

        return result;
    }
}
