package com.changhu.module.miniProgram.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.changhu.common.enums.ResultCode;
import com.changhu.common.exception.MessageException;
import com.changhu.common.utils.SnowFlakeIdUtil;
import com.changhu.mapper.SecurityUserMapper;
import com.changhu.module.miniProgram.pojo.params.SecurityUserSaveOrUpdateParams;
import com.changhu.module.miniProgram.pojo.params.UserRegisterParams;
import com.changhu.module.miniProgram.pojo.queryParams.ServiceProjectSecurityUserPagerQueryParams;
import com.changhu.module.miniProgram.pojo.vo.ServiceProjectSecurityUserPagerVo;
import com.changhu.module.miniProgram.service.UserService;
import com.changhu.pojo.entity.MiniProgramUser;
import com.changhu.pojo.entity.SecurityUser;
import com.changhu.support.mybatisplus.pojo.params.PageParams;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 20252
 * @createTime 2024/11/22 下午4:14
 * @desc UserServiceImpl...
 */
@Service("miniProgramUserService")
public class UserServiceImpl implements UserService {
    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private SecurityUserMapper securityUserMapper;

    @Override
    public void register(UserRegisterParams params) {
        MiniProgramUser miniProgramUser = BeanUtil.copyProperties(params, MiniProgramUser.class);
        try {
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(params.getCode());
            miniProgramUser.setOpenId(sessionInfo.getOpenid());
            miniProgramUser.setSessionKey(sessionInfo.getSessionKey());
        } catch (WxErrorException e) {
            throw new MessageException(e.getMessage());
        }
        boolean exists = Db.lambdaQuery(MiniProgramUser.class).eq(MiniProgramUser::getOpenId, miniProgramUser.getOpenId()).exists();
        if (exists) {
            throw new MessageException("该用户已存在，请勿重复注册!");
        }
        long userId = SnowFlakeIdUtil.snowflakeId();
        miniProgramUser.setSnowFlakeId(userId);
        boolean save = Db.save(miniProgramUser);
        if (!save) {
            throw new MessageException();
        }
    }

    @Override
    public void saveOrUpdateSecurityUser(SecurityUserSaveOrUpdateParams params) {
        SecurityUser securityUser = BeanUtil.copyProperties(params, SecurityUser.class);
        //新增的情况
        Long snowFlakeId = securityUser.getSnowFlakeId();
        if (snowFlakeId == null) {
            //判断是否已经存在
            boolean exists = Db.lambdaQuery(SecurityUser.class)
                    .eq(SecurityUser::getServiceProjectId, securityUser.getServiceProjectId())
                    .eq(SecurityUser::getIdCard, securityUser.getIdCard())
                    .exists();
            if (exists) {
                throw new MessageException("服务项目下已经存在该人员");
            }
        } else {
            //如果修改了身份证 需要查重
            SecurityUser byId = Db.getById(snowFlakeId, SecurityUser.class);
            if (!securityUser.getIdCard().equals(byId.getIdCard())) {
                boolean exists = Db.lambdaQuery(SecurityUser.class)
                        .eq(SecurityUser::getServiceProjectId, securityUser.getServiceProjectId())
                        .eq(SecurityUser::getIdCard, securityUser.getIdCard())
                        .exists();
                if (exists) {
                    throw new MessageException("服务项目下已经存在该人员");
                }
            }
        }
        Assert.isTrue(Db.saveOrUpdate(securityUser), ResultCode.ERROR.getMessage());
    }

    @Override
    public void qrCodeFormInputSecurityUser(SecurityUserSaveOrUpdateParams params) {
        this.saveOrUpdateSecurityUser(params);
    }

    @Override
    public Page<ServiceProjectSecurityUserPagerVo> securityUserPager(PageParams<ServiceProjectSecurityUserPagerQueryParams, ServiceProjectSecurityUserPagerVo> queryParams) {
        return securityUserMapper.securityUserPager(queryParams.getPage(), queryParams.getParams());
    }

    @Override
    public void deleteSecurityUserById(Long securityUserId) {
        Assert.isTrue(Db.removeById(securityUserId, SecurityUser.class), ResultCode.ERROR.getMessage());
    }
}
