package com.ruoyi.wgz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.domain.Annex;
import com.ruoyi.common.domain.dto.AnnexDTO;
import com.ruoyi.common.service.IAnnexService;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.wgz.bo.WgzUserQueryBo;
import com.ruoyi.wgz.bo.req.WgzAppModifyingUserProfilePictureReq;
import com.ruoyi.wgz.bo.req.WgzAppPersonalBasicInformationReq;
import com.ruoyi.wgz.bo.req.WgzAppRegisterReq;
import com.ruoyi.wgz.bo.req.WgzAppRealNameAuthenticationReq;
import com.ruoyi.wgz.bo.res.WgzAppPersonalBasicInformationRes;
import com.ruoyi.wgz.common.SnowflakeIdUtil;
import com.ruoyi.wgz.domain.WgzUser;
import com.ruoyi.wgz.mapper.WgzUserMapper;
import com.ruoyi.wgz.service.IWgzUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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



/**
 * APP务工者Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-14
 */
@Service
public class WgzUserServiceImpl extends ServicePlusImpl<WgzUserMapper, WgzUser> implements IWgzUserService {

	@Autowired
	private IAnnexService iAnnexService;

	@Override
    public WgzUser queryById(String id){
        return getById(id);
    }

    @Override
    public TableDataInfo<WgzUser> queryPageList(WgzUserQueryBo bo) {
        Page<WgzUser> result = page(PageUtils.buildPage(), buildQueryWrapper(bo));
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<WgzUser> queryList(WgzUserQueryBo bo) {
        return list(buildQueryWrapper(bo));
    }

    private LambdaQueryWrapper<WgzUser> buildQueryWrapper(WgzUserQueryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<WgzUser> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, WgzUser::getUserId, bo.getUserId());
        lqw.like(StrUtil.isNotBlank(bo.getUsername()), WgzUser::getUsername, bo.getUsername());
        lqw.eq(StrUtil.isNotBlank(bo.getBirthdate()), WgzUser::getBirthdate, bo.getBirthdate());
        lqw.eq(StrUtil.isNotBlank(bo.getIdentityCard()), WgzUser::getIdentityCard, bo.getIdentityCard());
        lqw.eq(StrUtil.isNotBlank(bo.getPhone()), WgzUser::getPhone, bo.getPhone());
        lqw.eq(StrUtil.isNotBlank(bo.getCardNo()), WgzUser::getCardNo, bo.getCardNo());
        lqw.eq(StrUtil.isNotBlank(bo.getStatus()), WgzUser::getStatus, bo.getStatus());
        return lqw;
    }

    @Override
    public Boolean insert(WgzUser bo) {
        WgzUser add = BeanUtil.toBean(bo, WgzUser.class);
        validEntityBeforeSave(add);
        return save(add);
    }

    @Override
    public Boolean update(WgzUser bo) {
        WgzUser update = BeanUtil.toBean(bo, WgzUser.class);
        validEntityBeforeSave(update);
        return updateById(update);
    }

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

    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }

	/**
	 * 务工者APP相关
	 * =================================================================================================================
	 * =================================================================================================================
	 * =================================================================================================================
	 */


	//注册
	@Override
	@Transactional
	public Boolean userRegister(WgzAppRegisterReq bo) {
		WgzUser wgzUser = new WgzUser();
		//1、查询手机号是否存在
		Integer count = baseMapper.selectCount(
			new LambdaQueryWrapper<WgzUser>().
				eq(WgzUser::getPhone, wgzUser.getPhone())
		);
		if (count>0){
			throw new RuntimeException("当前手机号已存在！");
		}
		//2、组装数据 BeanUtils.copyProperties(bo,wgzUser);
		wgzUser.setPhone(bo.getPhone());
		wgzUser.setUserId(SnowflakeIdUtil.generateId());
		wgzUser.setPassword(SecurityUtils.encryptPassword(wgzUser.getPassword()));
		//3、保存数据
		return  baseMapper.insert(wgzUser) > 0;
	}

	@Override
	@Transactional
	public Boolean userModifyingUserProfilePicture(WgzAppModifyingUserProfilePictureReq req) {
		WgzUser user = new WgzUser();
		BeanUtils.copyProperties(req, user);
		int update = baseMapper.update(user, new LambdaQueryWrapper<WgzUser>().eq(WgzUser::getUserId, req.getUserId()));
		if (update == 0){
			throw new RuntimeException("当前用户不存在！");
		}
		return true;
	}

	//登录-获取用户
	@Override
	public WgzUser userLongIn(String phone) {
		return baseMapper.selectOne(new LambdaQueryWrapper<WgzUser>().eq(WgzUser::getPhone, phone));
	}

	//获取用户个人信息
    @Override
    public WgzAppPersonalBasicInformationRes userPersonalBasicInformation(WgzAppPersonalBasicInformationReq req) {
        //1、根据唯一标识查询用户基本信息
        WgzUser wgzUser = baseMapper.selectOne(new LambdaQueryWrapper<WgzUser>().eq(WgzUser::getUserId, req.getUserId()));
        if (wgzUser == null){
            throw new RuntimeException("当前用户不存在！");
        }
        //2、copy数据返回
        WgzAppPersonalBasicInformationRes wgzAppPersonalBasicInformationRes = new WgzAppPersonalBasicInformationRes();
        BeanUtils.copyProperties(wgzUser,wgzAppPersonalBasicInformationRes);
        return wgzAppPersonalBasicInformationRes;
    }

	//实名认证
	@Override
	@Transactional()
	public Boolean userRealNameAuthentication(WgzAppRealNameAuthenticationReq req) {
		//1、对指定用户进行实名认证
		WgzUser user = new WgzUser();
		BeanUtils.copyProperties(req, user);
		int update = baseMapper.update(user, new LambdaQueryWrapper<WgzUser>().eq(WgzUser::getUserId, req.getUserId()));
		if (update == 0){
			throw new RuntimeException("当前用户不存在！");
		}
		//2、新增附件
		List<Annex> annex = req.getAnnex();
		List<AnnexDTO> annexDTOS = new ArrayList<>();
		BeanUtils.copyProperties(annex, annexDTOS);
		iAnnexService.insertBatch(annexDTOS);
		return true;
	}

}
