package com.ruoyi.user.service.impl;

import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.enums.ExceptionEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.user.domain.UserThirdIdentity;
import com.ruoyi.user.domain.bo.UserThirdIdentityBo;
import com.ruoyi.user.mapper.UserThirdIdentityMapper;
import com.ruoyi.user.service.IUserThirdIdentityService;
import com.ruoyi.weixin.domain.WxUserDto;
import com.ruoyi.weixin.service.WxMsgService;
import com.ruoyi.weixin.service.WxUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.user.domain.bo.UserBo;
import com.ruoyi.user.domain.vo.UserVo;
import com.ruoyi.user.domain.User;
import com.ruoyi.user.mapper.UserMapper;
import com.ruoyi.user.service.IUserService;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 小程序用户管理Service业务层处理
 *
 * @author wuchao
 * @date 2022-03-03
 */
@RequiredArgsConstructor
@Service
public class UserServiceImpl implements IUserService {

    private final UserMapper baseMapper;

    private final WxUserService wxUserService;

    private final UserThirdIdentityMapper userThirdIdentityMapper;

    /**
     * 查询小程序用户管理
     *
     * @param id 小程序用户管理主键
     * @return 小程序用户管理
     */
    @Override
    public UserVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询小程序用户管理列表
     *
     * @param bo 小程序用户管理
     * @return 小程序用户管理
     */
    @Override
    public TableDataInfo<UserVo> queryPageList(UserBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<User> lqw = buildQueryWrapper(bo);
        Page<UserVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询小程序用户管理列表
     *
     * @param bo 小程序用户管理
     * @return 小程序用户管理
     */
    @Override
    public List<UserVo> queryList(UserBo bo) {
        LambdaQueryWrapper<User> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<User> buildQueryWrapper(UserBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<User> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getMobile()), User::getMobile, bo.getMobile());
        lqw.like(StringUtils.isNotBlank(bo.getNickname()), User::getNickname, bo.getNickname());
        lqw.eq(StringUtils.isNotBlank(bo.getHeadPhoto()), User::getHeadPhoto, bo.getHeadPhoto());
        lqw.eq(bo.getAge() != null, User::getAge, bo.getAge());
        lqw.eq(bo.getGender() != null, User::getGender, bo.getGender());
        lqw.like(StringUtils.isNotBlank(bo.getRealName()), User::getRealName, bo.getRealName());
        lqw.eq(StringUtils.isNotBlank(bo.getBirthday()), User::getBirthday, bo.getBirthday());
        lqw.eq(bo.getStatus() != null, User::getStatus, bo.getStatus());
        lqw.eq(bo.getLastLoginTime() != null, User::getLastLoginTime, bo.getLastLoginTime());
        return lqw;
    }

    /**
     * 新增小程序用户管理
     *
     * @param bo 小程序用户管理
     * @return 结果
     */
    @Override
    public Boolean insertByBo(UserBo bo) {
        User add = BeanUtil.toBean(bo, User.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改小程序用户管理
     *
     * @param bo 小程序用户管理
     * @return 结果
     */
    @Override
    public Boolean updateByBo(UserBo bo) {
        User update = BeanUtil.toBean(bo, User.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(User entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除小程序用户管理
     *
     * @param ids 需要删除的小程序用户管理主键
     * @return 结果
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public User authorization(WxUserDto wxUserDto) {
        //获取openId
        String openId = wxUserService.getOpenIdByCode(wxUserDto.getCode());

        //查询此openid是否绑定过用户
        UserThirdIdentity userThirdIdentity = userThirdIdentityMapper.selectOne(
            new LambdaQueryWrapper<UserThirdIdentity>()
                .eq(UserThirdIdentity::getThirdType, 0)
                .eq(UserThirdIdentity::getIdentityCode, openId)
                .last("limit 1")
        );

        User user;
        //该用户未绑定过，则创建
        if (ObjectUtil.isNull(userThirdIdentity)) {
            //创建用户
            user = new User();
            user.setNickname(wxUserDto.getNickname());
            user.setHeadPhoto(wxUserDto.getHeadPhoto());
            user.setAge(wxUserDto.getAge());
            user.setGender(wxUserDto.getGender());//info.getGender()
            user.setRealName(wxUserDto.getRealName());
            user.setBirthday(wxUserDto.getBirthday());
            user.setStatus(true);
            //保存用户信息
            this.baseMapper.insert(user);

            //保存第三方关系
            userThirdIdentity = new UserThirdIdentity();
            userThirdIdentity.setUserId(user.getId());
            userThirdIdentity.setThirdType(0);
            userThirdIdentity.setIdentityCode(openId);
            userThirdIdentityMapper.insert(userThirdIdentity);
        } else {
            user = this.getById(userThirdIdentity.getUserId(), true);
        }

//        //TODO 自定义用户
//        User user = this.baseMapper.selectById(1L);
//        if (ObjectUtil.isNull(user)) {
//            user = new User();
//            user.setMobile("10086");
//            user.setNickname("老师");
//            user.setHeadPhoto("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fup.enterdesk.com%2Fedpic%2Fe8%2F34%2F02%2Fe834028fa4b313a1607872736437ef2d.jpg&refer=http%3A%2F%2Fup.enterdesk.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1648636830&t=5c4d53742351fbed90487a5b34e60058");
//            user.setAge(18);
//            user.setGender(0);//info.getGender()
//            user.setRealName("");
//            user.setBirthday("");
//            user.setStatus(true);
//            //保存用户信息
//            this.baseMapper.insert(user);
//
//            //保存用户的第三方身份
//            UserThirdIdentityBo userThirdIdentity = new UserThirdIdentityBo();
//            userThirdIdentity.setUserId(user.getId());
//            userThirdIdentity.setThirdType(0);
//            userThirdIdentity.setIdentityCode("openId");
//            userThirdIdentityService.insertByBo(userThirdIdentity);
//        }else {
//            //更新用户信息
//            this.baseMapper.updateById(user);
//        }

        return user;
    }


    @Override
    public User getById(Long userId, boolean isThrow) {
        User obj = this.baseMapper.selectById(userId);
        if (ObjectUtil.isNull(obj)) {
            if (isThrow) {
                throw new ServiceException("用户不存在");
            }
        }
        return obj;
    }
}
