package com.yida.data.school.smart.service.impl;

import cc.mrbird.febs.common.redis.service.RedisService;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yida.data.common.core.common.ResultMsgType;
import com.yida.data.common.core.entity.CurrentUser;
import com.yida.data.common.core.entity.constant.CachePrefixConstant;
import com.yida.data.common.core.entity.smart.EduSmartWelcomeGuideRoster;
import com.yida.data.common.core.utils.FebsUtil;
import com.yida.data.common.core.utils.FileUtil;
import com.yida.data.common.core.utils.QrCodeUtil;
import com.yida.data.school.dto.smart.GuideRosterErrorExportDTO;
import com.yida.data.school.dto.smart.GuideRosterImportDTO;
import com.yida.data.school.smart.mapper.EduSmartWelcomeGuideRosterMapper;
import com.yida.data.school.smart.service.ImportGuideRosterService;
import com.yida.data.school.vo.smart.ImportRosterDataVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.ehcache.impl.internal.concurrent.ConcurrentHashMap;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 注释
 *
 * @author ZYJ
 * @date 2023/6/1 14:54
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class ImportGuideRosterServiceImpl implements ImportGuideRosterService {

    private final EduSmartWelcomeGuideRosterMapper eduSmartWelcomeGuideRosterMapper;
    private final RedisService redisService;

    @Value("${febs.uploadUrl}")
    private String uploadUrl;

    @Override
    public void saveGuideRosterExcelData(ConcurrentHashMap<Integer, GuideRosterImportDTO> concurrentHashMap,
        List<GuideRosterErrorExportDTO> errorList, Long guideId, String uuid,
        CurrentUser currentUser, Integer totalCount, Integer handleCount) {

        int temp = 0;
        if (!CollectionUtils.isEmpty(concurrentHashMap)) {
            // 保存前判断是否已存在
            for (Map.Entry<Integer, GuideRosterImportDTO> entry : concurrentHashMap.entrySet()) {
                temp++;

                GuideRosterErrorExportDTO dto = new GuideRosterErrorExportDTO();
                GuideRosterImportDTO importDTO = new GuideRosterImportDTO();
                File qrCodeFile = null;
                try {
                    importDTO = entry.getValue();
                    BeanUtils.copyProperties(importDTO, dto);
                    // 验证导入信息是否为空
                    if (!checkRosterImportInfo(dto, importDTO)) {
                        errorList.add(dto);
                        continue;
                    }
                    // 验证学号在当前学校的学生表中是否重复
                    EduSmartWelcomeGuideRoster exist = eduSmartWelcomeGuideRosterMapper.selectOne(
                        Wrappers.lambdaQuery(new EduSmartWelcomeGuideRoster())
                            .eq(EduSmartWelcomeGuideRoster::getIdNumber, importDTO.getIdNumber())
                            .eq(EduSmartWelcomeGuideRoster::getGuideId, guideId));

                    if (Objects.nonNull(exist)) {
                        log.error("身份证号码已存在: {}", JSONUtil.toJsonStr(importDTO));
                        dto.setErrorMessage(ResultMsgType.ID_CARD_EXIST.getValue());
                        errorList.add(dto);
                        continue;
                    }
                    // 保存指南花名册信息
                    EduSmartWelcomeGuideRoster guideRoster = new EduSmartWelcomeGuideRoster();
                    BeanUtils.copyProperties(importDTO, guideRoster);
                    guideRoster.setDeptId(Objects.requireNonNull(currentUser).getDeptId());
                    guideRoster.setGuideId(guideId);
                    guideRoster.setGender(FebsUtil.getSexByIdCardNo(importDTO.getIdNumber()));
                    eduSmartWelcomeGuideRosterMapper.insert(guideRoster);

                    // 判断指南二维码开启状态
//                    EduSmartWelcomeGuide guide = eduSmartWelcomeGuideService.getById(guideId);
//                    if (Objects.nonNull(guide) && EnableStatusEnum.ENABLE_STATUS.getStatus()
//                        .equals(guide.getQrCodeEnableStatus())) {
                    // 转换二维码信息
                    JSONObject obj = JSONUtil.parseObj(importDTO)
                        .set("rosterId", guideRoster.getId())
                        .set("deptId", Objects.requireNonNull(currentUser).getDeptId())
                        .set("guideId", guideId);
                    // 生成文件名称
                    String fileName = UUID.randomUUID().toString(true) + ".png";
                    String filePath = FileUtil.getLocalUploadAddress() + fileName;
                    QrCodeUtil.generateQrCodeImage(obj.toString(), 400, 400, filePath);
                    // 上传文件到媒资
                    qrCodeFile = new File(filePath);
                    String qrCodeAddress = FileUtil.uploadFileToMediaServer(uploadUrl, qrCodeFile);
                    eduSmartWelcomeGuideRosterMapper.updateById(
                        EduSmartWelcomeGuideRoster.builder()
                            .id(guideRoster.getId())
                            .qrCodeUrl(qrCodeAddress)
                            .build());
//                    }
                    // TODO: 2023/10/18 后续优化花名册缓存信息
                    // 缓存花名册信息
//                    redisService.hset(CachePrefixConstant.WELCOME_ROSTER, guideRoster.getId().toString(),
//                        eduSmartWelcomeGuideRosterMapper.selectById(guideRoster.getId()));
                } catch (Exception e) {
                    log.error("导入指南花名册失败: {}", JSONUtil.toJsonStr(importDTO), e);
                    dto.setErrorMessage("数据异常！");
                    errorList.add(dto);
                } finally {
                    if (Objects.nonNull(qrCodeFile)) {
                        cn.hutool.core.io.FileUtil.del(qrCodeFile);
                    }
                    // 计算百分比
                    BigDecimal percent = NumberUtil
                        .div(new BigDecimal((temp + handleCount) * 100), new BigDecimal(totalCount), 2);
                    redisService.set(CachePrefixConstant.IMPORT_GUIDE_ROSTER_KEY + uuid,
                        ImportRosterDataVO.builder().percent(percent.intValue()).finish(0).key(uuid)
                            .build());
                }
            }
        }
    }

    private boolean checkRosterImportInfo(GuideRosterErrorExportDTO dto, GuideRosterImportDTO importDTO) {
        BeanUtils.copyProperties(importDTO, dto);
        // 判断姓名是否为空
        if (!StringUtils.isNotBlank(importDTO.getFullName())) {
            dto.setErrorMessage("姓名为空");
            return false;
        }
        // 判断身份证号码是否为空
        else if (!StringUtils.isNotBlank(importDTO.getIdNumber())) {
            dto.setErrorMessage("身份证号码为空");
            return false;
        }
        // 判断录取专业是否为空
        else if (!StringUtils.isNotBlank(importDTO.getAdmittedDepartment())) {
            dto.setErrorMessage("录取系部为空");
            return false;
        }
        // 判断录取专业是否为空
        else if (!StringUtils.isNotBlank(importDTO.getAdmittedMajor())) {
            dto.setErrorMessage("录取专业为空");
            return false;
        }
        // 判断手机号码是否为空
        else if (!StringUtils.isNotBlank(importDTO.getMobile())) {
            dto.setErrorMessage("手机号码为空");
            return false;
        }
        return true;
    }
}
