package com.ruoyi.xq.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.util.PhoneUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.BeanConvertUtil;
import com.ruoyi.xq.domain.User;
import com.ruoyi.xq.domain.UserInfo;
import com.ruoyi.xq.domain.UserPictures;
import com.ruoyi.xq.domain.UserVip;
import com.ruoyi.xq.dto.admin.user.UserAdminVo;
import com.ruoyi.xq.dto.admin.user.req.UpdateMobileAdminReq;
import com.ruoyi.xq.dto.app.user.HomePageReq;
import com.ruoyi.xq.dto.app.user.vo.HomeUserListVo;
import com.ruoyi.xq.dto.app.user.vo.HomeUserVo;
import com.ruoyi.xq.dto.common.user.MinUser;
import com.ruoyi.xq.enums.common.SystemConfigEnum;
import com.ruoyi.xq.enums.userinfo.UserGenderEnum;
import com.ruoyi.xq.manager.SystemConfigManager;
import com.ruoyi.xq.mapper.UserMapper;
import com.ruoyi.xq.service.UserInfoService;
import com.ruoyi.xq.service.UserPicturesService;
import com.ruoyi.xq.service.UserService;
import com.ruoyi.xq.service.UserVipService;
import com.ruoyi.xq.util.BirthdayUtil;
import com.ruoyi.yunxin.client.ImUserRefClient;
import com.ruoyi.yunxin.req.UpdateUinfoReq;
import com.ruoyi.yunxin.resp.YxCommonR;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 用户管理Service业务层处理
 *
 * @author 77
 * @date 2024-03-04
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {
    @Autowired
    private UserInfoService userInfoService;
    @Resource
    private ImUserRefClient userRefClient;
    @Autowired
    private SystemConfigManager systemConfigManager;
    @Autowired
    private UserPicturesService userPicturesService;
    @Autowired
    private UserVipService userVipService;

    @Override
    public MinUser getMinUserById(Long userId){
        return baseMapper.getMinUserById(userId);
    }

    @Override
    public User getByUsername(String username) {
        return this.getOne(Wrappers.lambdaQuery(User.class)
                .eq(User::getMobile,username));
    }

    @Override
    public void resetPassword(Long userId, String password) {
        if(userId == null || StringUtils.isEmpty(password)){
            throw new ServiceException("参数异常");
        }
        this.update(Wrappers.lambdaUpdate(User.class)
                .eq(User::getId,userId)
                .set(User::getPassword, BCrypt.hashpw(password)));
    }

    @Override
    public User getByUsercode(String usercode) {
        return this.getOne(Wrappers.lambdaQuery(User.class)
                .eq(User::getUsercode,usercode).last("limit 1"));
    }

    @Override
    public HomeUserVo homeUser(Long userId) {
        User user = this.getById(userId);
        UserInfo userInfo = userInfoService.getByUserId(userId);
        HomeUserVo result = new HomeUserVo();
        BeanConvertUtil.copyProperties(userInfo,result);
        BeanConvertUtil.copyProperties(user,result);
        List<UserPictures> userPicturesList = userPicturesService.listByUserIdSuccess(userId);
        result.setUserPictureList(userPicturesList.stream().map(UserPictures::getPicture).collect(Collectors.toList()));
        return result;
    }

    @Override
    public boolean updateMobileUser(UpdateMobileAdminReq bo) {
        if(!PhoneUtil.isMobile(bo.getMobile())){
            throw new ServiceException("请填写正常的手机号");
        }
        User user = this.getById(bo.getId());
        if(com.ruoyi.common.utils.StringUtils.isNotEmpty(bo.getMobile())){
            long count = this.count(Wrappers.lambdaQuery(User.class)
                    .eq(User::getMobile, bo.getMobile())
                    .ne(User::getId, user.getId()));
            if(count > 0){
                throw new BaseException("手机号已存在，无法修改");
            }
        }
        User update = new User();
        update.setId(user.getId());
        update.setMobile(bo.getMobile());
        this.updateById(update);
        return true;
    }


    @Override
    public void resetAvatar(Long userId) {
        User user = this.getById(userId);
        if(user == null){
            return;
        }
        String cos = systemConfigManager.getSystemConfig(SystemConfigEnum.COS_DOMAIN);
        Integer gender = user.getGender();
        UserGenderEnum genderEnum = UserGenderEnum.getByCode(gender);
        if(genderEnum == null){
            return;
        }
        String avatar = cos + genderEnum.getDefaultAvatar();
        this.update(Wrappers.lambdaUpdate(User.class)
                .eq(User::getId,user.getId())
                .set(User::getAvatar,avatar));
        UpdateUinfoReq uinfoReq = new UpdateUinfoReq();
        uinfoReq.setAccid(user.getId()+"");
        uinfoReq.setIcon(avatar);
        YxCommonR r = userRefClient.updateUinfo(uinfoReq);
        if(!r.isSuccess()){
            log.error("云信更新失败，需要检查！{}", JSON.toJSONString(r));
        }
    }

    @Override
    public void resetNickname(Long userId) {
        User user = this.getById(userId);
        if(user == null){
            return;
        }
        boolean update = this.update(Wrappers.lambdaUpdate(User.class)
                .eq(User::getId, user.getId())
                .set(User::getNickname, "用户" + user.getUsercode()));
        if(!update){
            return;
        }
        UpdateUinfoReq uinfoReq = new UpdateUinfoReq();
        uinfoReq.setAccid(user.getId()+"");
        uinfoReq.setName("用户"+user.getUsercode());
        YxCommonR r = userRefClient.updateUinfo(uinfoReq);
        if(!r.isSuccess()){
            log.error("云信更新失败，需要检查！{}", JSON.toJSONString(r));
        }
    }

    @Override
    public Page<UserAdminVo> pageAdmin(PageQuery pageQuery, UserAdminVo bo) {
        return baseMapper.pageAdmin(pageQuery.build(), bo);
    }

    @Override
    public Page<HomeUserListVo> homePage(HomePageReq params) {
        HomePageReq.VipQuery vipQuery = params.getVipQuery();
        if(vipQuery != null){
            if(StringUtils.isNotEmpty(vipQuery.getProfession()) ||
                vipQuery.getAnnualIncome() != null  || vipQuery.getZodiac() != null ||
                vipQuery.getSign() != null || vipQuery.getChildStatus() != null || vipQuery.getHousingStatus() != null  ||
                vipQuery.getCarStatus() != null || StringUtils.isNotEmpty(vipQuery.getAddressCode())){
                Long userId = LoginHelper.getUserId();
                if(userId == null){
                    throw new ServiceException("开通VIP才能开通查询",600100);
                }
                UserVip userVip = userVipService.getByUserVipMaster(userId);
                if(userVip == null){
                    throw new ServiceException("开通VIP才能开通查询",600100);
                }
            }
        }
        Page<HomeUserListVo> page = baseMapper.homePageApp(params.build(), params);
        List<HomeUserListVo> records = page.getRecords();
        List<Long> userIdArray = new ArrayList<>();
        for (HomeUserListVo record : records) {
            userIdArray.add(record.getUserId());
            record.setBirthdayStr(BirthdayUtil.getMinBirthday(record.getBirthday()));
            record.setAge(BirthdayUtil.getAge(record.getBirthday()));
        }
        List<UserVip> vips = userVipService.listUserVipMaster(userIdArray);
        Map<Long, UserVip> userVipMap = vips.stream().collect(Collectors.toMap(UserVip::getUserId, Function.identity()));
        for (HomeUserListVo record : records) {
            UserVip userVip = userVipMap.get(record.getUserId());
            if(userVip != null){
                record.setOpenVip(true);
                record.setVipType(userVip.getVipType());
            }
        }
        return page;
    }

    @Override
    public List<HomeUserListVo> vipHomePage() {
        List<HomeUserListVo> result = baseMapper.vipHomePage(20);
        for (HomeUserListVo record : result) {
            record.setBirthdayStr(BirthdayUtil.getMinBirthday(record.getBirthday()));
            record.setAge(BirthdayUtil.getAge(record.getBirthday()));
        }
        return null;
    }
}
