package com.ruoyi.bgt.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
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.bgt.bo.BgtUserQueryBo;
import com.ruoyi.bgt.domain.dto.UserRealNameAuthenticationDTO;
import com.ruoyi.bgt.mapper.BgtUserMapper;
import com.ruoyi.bgt.service.IBgtUserService;
import com.ruoyi.common.core.domain.entity.BgtUser;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.service.IAnnexService;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.wgz.common.SnowflakeIdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * APP包工头Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-14
 */
@Service
public class BgtUserServiceImpl extends ServicePlusImpl<BgtUserMapper, BgtUser> implements IBgtUserService {

	@Autowired
	private IAnnexService annexService;

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

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

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

    private LambdaQueryWrapper<BgtUser> buildQueryWrapper(BgtUserQueryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BgtUser> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, BgtUser::getUserId, bo.getUserId());
        lqw.like(StrUtil.isNotBlank(bo.getUsername()), BgtUser::getUsername, bo.getUsername());
        lqw.eq(StrUtil.isNotBlank(bo.getGender()), BgtUser::getGender, bo.getGender());
        lqw.eq(StrUtil.isNotBlank(bo.getNation()), BgtUser::getNation, bo.getNation());
        lqw.eq(StrUtil.isNotBlank(bo.getBirthdate()), BgtUser::getBirthdate, bo.getBirthdate());
        lqw.eq(StrUtil.isNotBlank(bo.getIdentityCard()), BgtUser::getIdentityCard, bo.getIdentityCard());
        lqw.eq(StrUtil.isNotBlank(bo.getArea()), BgtUser::getArea, bo.getArea());
        lqw.eq(StrUtil.isNotBlank(bo.getSite()), BgtUser::getSite, bo.getSite());
        lqw.eq(StrUtil.isNotBlank(bo.getPhone()), BgtUser::getPhone, bo.getPhone());
        lqw.eq(StrUtil.isNotBlank(bo.getBank()), BgtUser::getBank, bo.getBank());
        lqw.eq(StrUtil.isNotBlank(bo.getCardNo()), BgtUser::getCardNo, bo.getCardNo());
        lqw.like(StrUtil.isNotBlank(bo.getAvatarName()), BgtUser::getAvatarName, bo.getAvatarName());
        lqw.eq(StrUtil.isNotBlank(bo.getPassword()), BgtUser::getPassword, bo.getPassword());
        lqw.eq(StrUtil.isNotBlank(bo.getFrontPath()), BgtUser::getFrontPath, bo.getFrontPath());
        lqw.eq(StrUtil.isNotBlank(bo.getReverseSidePath()), BgtUser::getReverseSidePath, bo.getReverseSidePath());
        lqw.eq(StrUtil.isNotBlank(bo.getBankCardPath()), BgtUser::getBankCardPath, bo.getBankCardPath());
        lqw.eq(StrUtil.isNotBlank(bo.getStatus()), BgtUser::getStatus, bo.getStatus());
        return lqw;
    }

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

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

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(BgtUser entity){
		List<BgtUser> bgtUsers = baseMapper.selectList(new LambdaQueryWrapper<BgtUser>()
			.eq(BgtUser::getPhone, entity.getPhone())
			.ne(entity.getId()!=null,BgtUser::getId, entity.getId()));
		if(CollectionUtil.isNotEmpty(bgtUsers)){
			throw new BaseException("手机号已存在");
		}
		//TODO 做一些数据校验,如唯一约束
    }

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

	@Override
	public BgtUser selectUserByPhone(String phone) {
		return baseMapper.selectOne(new LambdaQueryWrapper<BgtUser>().eq(BgtUser::getPhone, phone));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean realNameAuthentication(UserRealNameAuthenticationDTO dto) {
		BgtUser bgtUser = BeanUtil.copyProperties(dto, BgtUser.class);
		//todo: 资格证书附件类型
		annexService.deleteByTypes(Arrays.asList("1"));
		annexService.insertBatch(dto.getAnnexList());
		return baseMapper.updateById(bgtUser)>0;
	}

	@Override
	public BgtUser selectUserByUserId(Long userId) {
		return baseMapper.selectOne(new LambdaQueryWrapper<BgtUser>().eq(BgtUser::getUserId, userId));
	}
}
