package com.zd.exam.service.impl;

import cn.hutool.core.date.DateUtil;
import com.zd.common.core.exception.ServiceException;
import com.zd.common.core.utils.DateUtils;
import com.zd.common.core.utils.FileConfigUtils;
import com.zd.common.core.utils.SecurityUtils;
import com.zd.common.core.utils.UrlFormatUtils;
import com.zd.common.security.service.TokenService;
import com.zd.exam.domain.ElExam;
import com.zd.exam.domain.ElExamCertRelation;
import com.zd.exam.domain.ElUserCert;
import com.zd.exam.domain.LabCertificate;
import com.zd.exam.mapper.ElExamCertRelationMapper;
import com.zd.exam.mapper.ElUserCertMapper;
import com.zd.exam.service.IElUserCertService;
import com.zd.exam.service.ILabCertificateService;
import com.zd.exam.util.CertUtil;
import com.zd.system.api.domain.SysUser;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;

/**
 * 用户考试获取的证书Service业务层处理
 *
 * @author zd
 * @date 2021-09-13
 */
@Service
public class ElUserCertServiceImpl implements IElUserCertService {
    @Autowired
    private ElUserCertMapper elUserCertMapper;
    @Autowired
    private ElExamCertRelationMapper examCertRelationMapper;
    @Autowired
    private ILabCertificateService labCertificateService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private CertUtil certUtil;
    @Autowired
    private FileConfigUtils fileConfigUtils;


    /**
     * 查询用户考试获取的证书
     *
     * @param id 用户考试获取的证书主键
     * @return 用户考试获取的证书
     */
    @Override
    public ElUserCert selectElUserCertById(Long id) {
        return elUserCertMapper.selectElUserCertById(id);
    }

    /**
     * 查询用户考试获取的证书列表
     *
     * @param elUserCert 用户考试获取的证书
     * @return 用户考试获取的证书
     */
    @Override
    public List<ElUserCert> selectElUserCertList(ElUserCert elUserCert) {
        return elUserCertMapper.selectElUserCertList(elUserCert);
    }

    /**
     * 新增用户考试获取的证书
     *
     * @param elUserCert 用户考试获取的证书
     * @return 结果
     */
    @Override
    public ElUserCert insertElUserCert(ElUserCert elUserCert, HttpServletRequest request) {

        ElUserCert myCert = new ElUserCert();
        myCert.setJoinUserId(elUserCert.getJoinUserId());
        if(CollectionUtils.isNotEmpty(queryMyCert(myCert))) {
            // 如果获得证书则不再获得
            return null;
        }

        List<LabCertificate> certList = labCertificateService.selectLabCertificateList(new LabCertificate());
        // 2.1 需求根据模板生成，且模板只有一个，如果添加多个不考虑
        if(CollectionUtils.isEmpty(certList)){
            return null;
        }
        LabCertificate certificate = certList.get(0);

        elUserCert.setCertId(certificate.getId());
        elUserCert.setCode(DateUtil.format(DateUtils.getNowDate(), "yyyyMMdd") + (int)(Math.random() * 90 + 10));
        elUserCert.setCreateTime(DateUtils.getNowDate());
        elUserCert.setExpirationTime(DateUtils.getPostdate(certificate.getCertValidity(), 2));

        // 此时的登录用户应该等同于交卷用户

        SysUser user = tokenService.getLoginUser().getSysUser();
        if(!user.getUserId().equals(myCert.getJoinUserId())){
            throw new ServiceException("证书生成失败，用户不匹配！");
        }
        String baseUrl=request.getServerName() ;
        String url="";
        if(baseUrl.contains("192.168")){
            url=fileConfigUtils.getLocalUrl()+certificate.getCertUrl();
        }else{
            url=fileConfigUtils.getRemoteUrl()+certificate.getCertUrl();
        }
        url= UrlFormatUtils.getHttpsORHttpUrl(url);
        elUserCert.setCertUrl(url);
        elUserCert.setUserNickName(user.getNickName());
        elUserCert.setUserName(user.getUserName());
        elUserCert.setDeptId(user.getDeptId());
        elUserCert.setDeptName(Optional.ofNullable(user.getDept().getDeptName()).orElse(""));

        // 证书模板生成方法, 证书生成需要查询用户的所属学院
        String userCertUrl = certUtil.generateCert(elUserCert);
        if(StringUtils.isNotBlank(userCertUrl)){
            elUserCert.setCertUrl(userCertUrl);
            elUserCertMapper.insertElUserCert(elUserCert);
            return elUserCert;
        }
        return null;
    }

    /**
     * 修改用户考试获取的证书
     *
     * @param elUserCert 用户考试获取的证书
     * @return 结果
     */
    @Override
    public int updateElUserCert(ElUserCert elUserCert) {
        return elUserCertMapper.updateElUserCert(elUserCert);
    }

    /**
     * 批量删除用户考试获取的证书
     *
     * @param ids 需要删除的用户考试获取的证书主键
     * @return 结果
     */
    @Override
    public int deleteElUserCertByIds(Long[] ids) {
        return elUserCertMapper.deleteElUserCertByIds(ids);
    }

    /**
     * 删除用户考试获取的证书信息
     *
     * @param id 用户考试获取的证书主键
     * @return 结果
     */
    @Override
    public int deleteElUserCertById(Long id) {
        return elUserCertMapper.deleteElUserCertById(id);
    }

    /**
     * 保存用户通过考试获得的证书
     * 1. 同一个证书只能获取一次
     * 2. 同一个证书获取两次，更新获取时间
     *
     * @param examId 考试Id
     */
    @Override
    public void insertOrUpdateBatchElUserCert(Long examId) {
        Long userId = SecurityUtils.getUserId();
        ElExam exam = new ElExam();
        exam.setId(examId);
        List<ElExamCertRelation> examCertRelations = examCertRelationMapper.queryCertById(exam.getId());
        if (CollectionUtils.isEmpty(examCertRelations)) {
            return;
        }
        List<ElUserCert> userCerts = elUserCertMapper.selectByCertIds(examCertRelations, userId);

        Long id;
        LabCertificate certificate;
        for (ElExamCertRelation examCertRelation : examCertRelations) {
            id = null;
            for (ElUserCert userCert : userCerts) {
                if (examCertRelation.getCertId().equals(userCert.getCertId())) {

                    id = userCert.getId();
                    certificate = labCertificateService.selectLabCertificateById(userCert.getCertId());
                    if (certificate == null) {
                        // 考试管理的证书无效，暂跳过处理
                        continue;
                    }
                    if (certificate.getCertValidity() != null) {
                        userCert.setExpirationTime(DateUtils.getPostdate(certificate.getCertValidity(), 2));
                    }

                    // 更新证书获取时间
                    userCert.setExamId(examId);
                    userCert.setCreateTime(DateUtils.getNowDate());
                    elUserCertMapper.updateElUserCert(userCert);
                    break;
                }
            }
            if (id != null) {
                continue;
            }
            // 增加新的证书
            ElUserCert userCert = new ElUserCert();
            userCert.setJoinUserId(userId);
            userCert.setExamId(examId);
            userCert.setCertId(examCertRelation.getCertId());
            userCert.setCreateTime(DateUtils.getNowDate());
            certificate = labCertificateService.selectLabCertificateById(examCertRelation.getCertId());
            if (certificate == null) {
                // 考试管理的证书无效，暂跳过处理
                continue;
            }
            if (certificate.getCertValidity() != null) {
                userCert.setExpirationTime(DateUtils.getPostdate(certificate.getCertValidity(), 2));
            }
            elUserCertMapper.insertElUserCert(userCert);
        }

    }

    @Override
    public List<ElUserCert> queryMyCert(ElUserCert userCert) {
        return elUserCertMapper.queryMyCert(userCert);
    }
}
