package org.dromara.work.service.impl;

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.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.work.domain.TzUser;
import org.dromara.work.domain.bo.TzUserBo;
import org.dromara.work.domain.vo.TzUserVo;
import org.dromara.work.mapper.TzUserMapper;
import org.dromara.work.service.ITzUserService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 用户Service业务层处理
 *
 * @author Lion Li
 * @date 2024-07-30
 */
@RequiredArgsConstructor
@Service
public class TzUserServiceImpl extends MPJBaseServiceImpl<TzUserMapper, TzUser> implements ITzUserService {

    private final TzUserMapper baseMapper;

    /**
     * 查询用户
     *
     * @param userId 主键
     * @return 用户
     */
    @Override
    public TzUserVo queryById(Long userId){
        return baseMapper.selectVoById(userId);
    }

    /**
     * 分页查询用户列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 用户分页列表
     */
    @Override
    public TableDataInfo<TzUserVo> queryPageList(TzUserBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TzUser> lqw = buildQueryWrapper(bo);
        Page<TzUserVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        // 获取用户列表
        /*List<TzUserVo> userList = result.getRecords();

        // 遍历用户列表,查询每个用户的已完成订单数量
        for (TzUserVo user : userList) {
            LambdaQueryWrapper<HyOrderItem> orderWrapper = Wrappers.lambdaQuery();
            orderWrapper.eq(HyOrderItem::getUserId, user.getUserId());
            orderWrapper.eq(HyOrderItem::getStatus, 6);
            Long orderCount = hyOrderItemMapper.selectCount(orderWrapper);
            user.setOrderNum(orderCount);
        }*/
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的用户列表
     *
     * @param bo 查询条件
     * @return 用户列表
     */
    @Override
    public List<TzUserVo> queryList(TzUserBo bo) {
        LambdaQueryWrapper<TzUser> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 根据手机号查询用户信息
     *
     * @param userPhone 手机号
     * @return 用户信息
     */
    @Override
    public TzUserVo queryUserInfoByPhone(String userPhone) {
        return baseMapper.selectVoOne(new LambdaQueryWrapper<TzUser>().eq(TzUser::getUserMobile, userPhone));
    }

    private LambdaQueryWrapper<TzUser> buildQueryWrapper(TzUserBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TzUser> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getNickName()), TzUser::getNickName, bo.getNickName());
        lqw.like(StringUtils.isNotBlank(bo.getRealName()), TzUser::getRealName, bo.getRealName());
        lqw.eq(StringUtils.isNotBlank(bo.getUserMail()), TzUser::getUserMail, bo.getUserMail());
        lqw.eq(StringUtils.isNotBlank(bo.getLoginPassword()), TzUser::getLoginPassword, bo.getLoginPassword());
        lqw.eq(StringUtils.isNotBlank(bo.getPayPassword()), TzUser::getPayPassword, bo.getPayPassword());
        lqw.eq(StringUtils.isNotBlank(bo.getUserMobile()), TzUser::getUserMobile, bo.getUserMobile());
        lqw.eq(StringUtils.isNotBlank(bo.getIdCard()), TzUser::getIdCard, bo.getIdCard());
        lqw.eq(bo.getModifyTime() != null, TzUser::getModifyTime, bo.getModifyTime());
        lqw.eq(bo.getUserRegtime() != null, TzUser::getUserRegtime, bo.getUserRegtime());
        lqw.eq(bo.getIsMember() != null, TzUser::getIsMember, bo.getIsMember());
        lqw.eq(bo.getExamineFlag() != null, TzUser::getExamineFlag, bo.getExamineFlag());
        lqw.eq(StringUtils.isNotBlank(bo.getUserRegip()), TzUser::getUserRegip, bo.getUserRegip());
        lqw.eq(bo.getUserLasttime() != null, TzUser::getUserLasttime, bo.getUserLasttime());
        lqw.eq(StringUtils.isNotBlank(bo.getUserLastip()), TzUser::getUserLastip, bo.getUserLastip());
        lqw.eq(StringUtils.isNotBlank(bo.getUserMemo()), TzUser::getUserMemo, bo.getUserMemo());
        lqw.eq(StringUtils.isNotBlank(bo.getSex()), TzUser::getSex, bo.getSex());
        lqw.eq(StringUtils.isNotBlank(bo.getBirthDate()), TzUser::getBirthDate, bo.getBirthDate());
        lqw.eq(StringUtils.isNotBlank(bo.getPic()), TzUser::getPic, bo.getPic());
        lqw.eq(bo.getStatus() != null, TzUser::getStatus, bo.getStatus());
        lqw.eq(bo.getScore() != null, TzUser::getScore, bo.getScore());
        lqw.between(params.get("beginModifyTime") != null && params.get("endModifyTime") != null, TzUser::getModifyTime, params.get("beginModifyTime"), params.get("endModifyTime"));
        return lqw;
    }

    /**
     * 新增用户
     *
     * @param bo 用户
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(TzUserBo bo) {
        TzUser add = MapstructUtils.convert(bo, TzUser.class);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setUserId(add.getUserId());
        }
        return flag;
    }

    /**
     * 修改用户
     *
     * @param bo 用户
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(TzUserBo bo) {
        TzUser update = MapstructUtils.convert(bo, TzUser.class);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 开启设计师开关
     *
     * @param userPhone
     * @param status
     * @return
     */
    @Override
    public Boolean queryByUserPhone(String userPhone, Integer status) {
        TzUser user = baseMapper.selectOne(Wrappers.<TzUser>lambdaQuery().eq(TzUser::getUserMobile, userPhone));
        if (user == null){
            throw new ServiceException("该用户未注册");
        } else{
            if(status == 1){
                user.setIsDesigner(1);
            } else if (status == 2) {
                user.setIsDesigner(0);
            }
        }
        return baseMapper.updateById(user) > 0;
    }

    /**
     * 校验并批量删除用户信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 提交实名认证
     *
     * @param bo 用户认证信息
     * @return 是否提交成功
     */
    @Override
    public Boolean submitAuth(TzUserBo bo) {
        // 检查是否已提交过认证
        TzUser user = baseMapper.selectById(bo.getUserId());
        if (user == null) {
            throw new ServiceException("用户不存在");
        }
        if (user.getExamineFlag() == 2 || user.getExamineFlag() == 3) {
            throw new ServiceException("已提交过认证申请");
        }
        TzUser update = MapstructUtils.convert(bo, TzUser.class);
        update.setExamineFlag(2);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 提交设计师认证
     *
     * @param bo 设计师认证信息
     * @return 是否提交成功
     */
    @Override
    public Boolean submitSjsAuth(TzUserBo bo) {
        // 检查是否已提交过认证
        TzUser user = baseMapper.selectById(bo.getUserId());
        if (user == null) {
            throw new ServiceException("用户不存在");
        }
        if (user.getSjsFlag() == 2 || user.getSjsFlag() == 3) {
            throw new ServiceException("已提交过设计师认证申请");
        }
        TzUser update = MapstructUtils.convert(bo, TzUser.class);
        update.setSjsFlag(2);
        return baseMapper.updateById(update) > 0;
    }

   /* @Override
    public TableDataInfo<TzUserVo> queryPageListChart(TzUserBo bo, PageQuery pageQuery) {
        // 使用MPJLambdaWrapper构建多表关联查询
        MPJLambdaWrapper<TzUser> wrapper = new MPJLambdaWrapper<TzUser>()
            .selectAs(TzUser::getUserId, "userId")
            .selectAs(TzUser::getRealName, "realName")
            .selectCount(HyOrderItem::getId, "orderNum")
            .selectSum(HyOrderItem::getTotal, "orderTotal")
            .leftJoin(HyOrderItem.class, HyOrderItem::getUserId, TzUser::getUserId)
            .groupBy(TzUser::getUserId)
            .orderByDesc("orderTotal");

        // 添加查询条件
        if (bo != null) {
            Map<String, Object> params = bo.getParams();
            wrapper.eq(HyOrderItem::getDelFlag, 1);
            wrapper.ne(HyOrderItem::getPayState, 1);
            wrapper.like(StringUtils.isNotBlank(bo.getNickName()), TzUser::getNickName, bo.getNickName());
            wrapper.like(StringUtils.isNotBlank(bo.getRealName()),TzUser::getRealName, bo.getRealName());
            wrapper.between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
                HyOrderItem::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));
        }
        // 执行分页查询
        Page<TzUserVo> page = baseMapper.selectJoinPage(pageQuery.build(), TzUserVo.class, wrapper);
        return TableDataInfo.build(page);
    }*/
}
