package com.hfkj.service.user.impl;

import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.security.AESEncodeUtil;
import com.hfkj.common.security.SessionObject;
import com.hfkj.common.security.UserCenter;
import com.hfkj.dao.BsUserMapper;
import com.hfkj.entity.BsUser;
import com.hfkj.entity.BsUserExample;
import com.hfkj.entity.BsUserSpreadPower;
import com.hfkj.entity.BsUserSpreadRel;
import com.hfkj.model.UserSessionObject;
import com.hfkj.service.spread.BsUserSpreadRelService;
import com.hfkj.service.user.BsUserLoginLogService;
import com.hfkj.service.user.BsUserService;
import com.hfkj.sysenum.user.UserLoginPlatform;
import com.hfkj.sysenum.user.UserLoginType;
import com.hfkj.sysenum.user.UserStatusEnum;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @className: BsUserServiceImpl
 * @author: HuRui
 * @date: 2024/6/11
 **/
@Service("bsUserService")
public class BsUserServiceImpl implements BsUserService {
    @Resource
    private BsUserMapper userMapper;
    @Resource
    private UserCenter userCenter;
    @Resource
    private BsUserLoginLogService userLoginLogService;
    @Resource
    private BsUserSpreadRelService userSpreadRelService;
    /**
     * 生成token
     * @param user 用户
     * @return
     * @throws Exception
     */
    public String token(BsUser user) throws Exception {
        // token 生成格式：账户id
        return AESEncodeUtil.aesEncrypt(user.getId().toString());
    }

    @Override
    public void editData(BsUser data) {
        data.setUpdateTime(new Date());
        if (data.getId() == null) {
            data.setCreateTime(new Date());
            userMapper.insert(data);
        } else {
            userMapper.updateByPrimaryKey(data);
        }
    }

    @Override
    public BsUser getUser(Long userId) {
        return userMapper.selectByPrimaryKey(userId);
    }

    @Override
    public BsUser getUser(String phone) {
        BsUserExample example = new BsUserExample();
        example.createCriteria()
                .andPhoneEqualTo(phone)
                .andStatusNotEqualTo(UserStatusEnum.status0.getCode());
        List<BsUser> list = userMapper.selectByExample(example);
        if (!list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public void bindOtherId(Integer type, String id, Long userId) throws Exception {
        // 查询用户信息
        BsUser user = getUser(userId);
        // 类型 1：小程序openid  2：公众号openid
        if (type == 1) {
            user.setWxMaOpenId(id);
        } else if (type == 2) {
            user.setWxMpOpenId(id);
        }
        editData(user);

        // 缓存
        UserSessionObject session = new UserSessionObject();
        session.setUser(user);

        SessionObject sessionObject = new SessionObject(token(user), session);
        userCenter.save(sessionObject);
    }

    @Override
    public BsUser getUser(UserLoginPlatform loginPlatform, String code) {
        BsUserExample example = new BsUserExample();
        BsUserExample.Criteria criteria = example.createCriteria().andStatusNotEqualTo(UserStatusEnum.status0.getCode());
        if (UserLoginPlatform.H5.getCode().equals(loginPlatform.getCode())) {
            criteria.andWxMpOpenIdEqualTo(code);
        } else if (UserLoginPlatform.WXAPPLETS.getCode().equals(loginPlatform.getCode())) {
            criteria.andWxMaOpenIdEqualTo(code);
        } else if (UserLoginPlatform.ALIPAY.getCode().equals(loginPlatform.getCode())) {
            criteria.andAlipayOpenIdEqualTo(code);
        }
        List<BsUser> list = userMapper.selectByExample(example);
        if (!list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public BsUser register(String phone, Map<String, Object> other) {
        // 查询手机号
        if (getUser(phone) != null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "用户手机号已存在，请更换");
        }
        BsUser user = new BsUser();
        user.setPhone(phone);
        user.setWxMaOpenId(MapUtils.getString(other, "wxMaOpenId"));
        user.setWxMpOpenId(MapUtils.getString(other, "wxMpOpenId"));
        user.setAgentAppid(MapUtils.getString(other, "agentAppid"));
        user.setStatus(UserStatusEnum.status1.getCode());
        editData(user);

        user.setUserName("用户"+user.getId());
        editData(user);

        if (MapUtils.getLong(other, "userSpreadParentId") != null) {
            BsUserSpreadRel spreadRel = new BsUserSpreadRel();
            spreadRel.setParentUserId(MapUtils.getLong(other, "userSpreadParentId"));
            spreadRel.setUserId(user.getId());
            userSpreadRelService.editData(spreadRel);
        }
        return user;
    }


    @Override
    public SessionObject login(UserLoginPlatform platform, UserLoginType loginType, String phone, Map<String, Object> other) throws Exception {
        // 查询用户
        BsUser user = getUser(phone);
        if (user == null) {
            user = register(phone, other);
        }

        // 缓存
        UserSessionObject session = new UserSessionObject();
        session.setUser(user);

        SessionObject sessionObject = new SessionObject(token(user), session);
        userCenter.save(sessionObject);
        // 异步记录登录信息
        userLoginLogService.asyncCreateLog(platform, loginType, user, MapUtils.getString(other, "agentAppid"), (HttpServletRequest) RequestContextHolder.getRequestAttributes().resolveReference(RequestAttributes.REFERENCE_REQUEST));
        return sessionObject;
    }


}
