package jnpf.cultivate.v2.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jnpf.cultivate.mapper.FtbCultivateCertificateMapper;
import jnpf.cultivate.mapper.FtbCultivateCertificateUserMapper;
import jnpf.cultivate.utils.CultivateImUtil;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.cultivate.v2.service.V2CultivateCertificateService;
import jnpf.model.cultivate.po.certificate.FtbCertificateEntity;
import jnpf.model.cultivate.po.certificate.FtbCertificateUserEntity;
import jnpf.model.enums.CourseEnums;
import jnpf.model.enums.SelfrowingEnum;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.util.SelfGrowthUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;


@Service
@Slf4j
public class V2CultivateCertificateServiceImpl implements V2CultivateCertificateService {


    @Autowired
    private UserApiV2Util userApiV2Util;

    @Autowired
    private FtbCultivateCertificateUserMapper ftbCultivateCertificateUserMapper;

    @Autowired
    private FtbCultivateCertificateMapper ftbCultivateCertificateMapper;

    @Autowired
    private CultivateImUtil cultivateImUtil;


    /**
     * 触发证书
     *
     * @param userId        用户id
     * @param certificateId 证书id
     * @param tenantId      租户id
     */
    @Override
    public void triggerCertificate(String userId, String certificateId, String tenantId) {
        UserBoundVO userPrimaryBoundOne = userApiV2Util.getUserPrimaryBoundOne(userId, null);
        if (userPrimaryBoundOne == null) {
            log.error("颁发证书 用户不存在 userId = {},certificateId={}", userId, certificateId);
            return;
        }

        // 证书是否下架及删除
        FtbCertificateEntity ftbCertificateEntity = ftbCultivateCertificateMapper.selectById(certificateId);
        if (ftbCertificateEntity.getStatus() == 0 || CourseEnums.EnabledMarkType.INVALID.getCode().equals(ftbCertificateEntity.getEnabledMark())) {
            log.error("证书已下架 userId = {},certificateId={}", userId, certificateId);
            return;
        }


        FtbCertificateUserEntity certificateUserOldEntity = queryUserCertificate(userId, certificateId, ftbCultivateCertificateUserMapper);

        //说明证书存在但是是 1已失效，2已吊销 就删除重新颁发
        if (certificateUserOldEntity != null) {
            if (ftbCertificateEntity.getExpireType().equals(CourseEnums.CertExpireType.NEVER.getCode()) && certificateUserOldEntity.getStatus().equals(0)) {
                return;
            }
            certificateUserOldEntity.setEnabledMark(0);
            ftbCultivateCertificateUserMapper.updateById(certificateUserOldEntity);
        }
        FtbCertificateUserEntity ftbCertificateUserNewEntity = new FtbCertificateUserEntity();
        ftbCertificateUserNewEntity.setUserId(userId);
        ftbCertificateUserNewEntity.setUserName(userPrimaryBoundOne.getUserName());
        ftbCertificateUserNewEntity.setCertificateId(certificateId);
        ftbCertificateUserNewEntity.setCertificateName(ftbCertificateEntity.getName());
        ftbCertificateUserNewEntity.setCompanyName(userPrimaryBoundOne.getOrganizeName());
        ftbCertificateUserNewEntity.setOrganizeId(userPrimaryBoundOne.getOrganizeId());
        ftbCertificateUserNewEntity.setPositionId(userPrimaryBoundOne.getPositionId());
        ftbCertificateUserNewEntity.setReason("");
        ftbCertificateUserNewEntity.setStatus(CourseEnums.CertUserStatus.USING.getCode());
        ftbCertificateUserNewEntity.setEnabledMark(CourseEnums.EnabledMarkType.VALID.getCode());
        Integer entityExpireTime = ftbCertificateEntity.getExpireTime();
        if (certificateUserOldEntity != null) {
            ftbCertificateUserNewEntity.setNumber(certificateUserOldEntity.getNumber());
            ftbCertificateUserNewEntity.setEffectTime(LocalDateTime.now());
            ftbCertificateUserNewEntity.setCreatorTime(certificateUserOldEntity.getCreatorTime());
            ftbCertificateUserNewEntity.setCreatorUserId(certificateUserOldEntity.getCreatorUserId());

            if (!CourseEnums.CertExpireType.NEVER.getCode().equals(ftbCertificateEntity.getExpireType())) {
                //设置失效时间 ExpireTime=0时 null表示永久
                Date expireTime = certificateUserOldEntity.getExpireTime();
                if (CourseEnums.CertExpireType.DAY.getCode().equals(ftbCertificateEntity.getExpireType())) {
                    //添加天数
                    expireTime = DateUtil.offsetDay(expireTime, ftbCertificateEntity.getExpireTime());
                } else if (CourseEnums.CertExpireType.MONTH.getCode().equals(ftbCertificateEntity.getExpireType())) {
                    expireTime = DateUtil.offsetMonth(expireTime, ftbCertificateEntity.getExpireTime());
                }
                ftbCertificateUserNewEntity.setExpireTime(expireTime);
            }
        } else {
            ftbCertificateUserNewEntity.setNumber(SelfGrowthUtil.provideACustomIDBasedOnTheModule(SelfrowingEnum.CERTIFICATE_ENCODING_PREFIX, 4));
            ftbCertificateUserNewEntity.setCreatorTime(new Date());
            ftbCertificateUserNewEntity.setCreatorUserId(userId);
            ftbCertificateUserNewEntity.setEffectTime(LocalDateTime.now());
            if (!CourseEnums.CertExpireType.NEVER.getCode().equals(ftbCertificateEntity.getExpireType())) {
                //设置失效时间 ExpireTime=0时 null表示永久
                LocalDateTime expireTime = LocalDateTime.now();
                if (CourseEnums.CertExpireType.DAY.getCode().equals(ftbCertificateEntity.getExpireType())) {
                    expireTime = expireTime.plusDays(entityExpireTime.longValue());
                } else if (CourseEnums.CertExpireType.MONTH.getCode().equals(ftbCertificateEntity.getExpireType())) {
                    expireTime = expireTime.plusMonths(entityExpireTime.longValue());
                }
                Date date = Date.from(expireTime.atZone(ZoneId.systemDefault()).toInstant());
                ftbCertificateUserNewEntity.setExpireTime(date);
            }
        }
        ftbCultivateCertificateUserMapper.insert(ftbCertificateUserNewEntity);

        String contentMessage = "恭喜获得" + ftbCertificateEntity.getName() + "证书。您可前往“我的证书”模块查看更多证书！";
        cultivateImUtil.sendMessage(List.of(userId), tenantId, contentMessage);
    }

    public FtbCertificateUserEntity queryUserCertificate(String userId, String certificateId, FtbCultivateCertificateUserMapper ftbCultivateCertificateUserMapper) {
        LambdaQueryWrapper<FtbCertificateUserEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(FtbCertificateUserEntity::getCertificateId, certificateId)
                .eq(FtbCertificateUserEntity::getUserId, userId)
                .eq(FtbCertificateUserEntity::getEnabledMark, CourseEnums.EnabledMarkType.VALID.getCode())
                .last("limit 1");
        return ftbCultivateCertificateUserMapper.selectOne(queryWrapper);
    }
}
