package com.cool.store.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cool.store.constants.CommonConstants;
import com.cool.store.constants.RedisConstant;
import com.cool.store.context.LoginUserInfo;
import com.cool.store.dao.*;
import com.cool.store.dto.SmallVideoDTO;
import com.cool.store.dto.SmallVideoInfoDTO;
import com.cool.store.dto.StaffExamInfoDTO;
import com.cool.store.dto.openPreparation.PlanLineDTO;
import com.cool.store.entity.*;
import com.cool.store.enums.*;
import com.cool.store.enums.point.ShopSubStageEnum;
import com.cool.store.enums.point.ShopSubStageStatusEnum;
import com.cool.store.enums.video.ResourceStatusEnum;
import com.cool.store.enums.video.UploadTypeEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.request.*;
import com.cool.store.service.*;
import com.cool.store.utils.NumberConverter;
import com.cool.store.utils.RedisUtilPool;
import com.cool.store.utils.poi.DateUtils;
import com.cool.store.utils.vod.SmallVideoParam;
import com.cool.store.vo.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @author byd
 * @date 2024-04-30 10:16
 */
@Service
public class EmployeeTrainingServiceImpl implements EmployeeTrainingService {

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private UserAuthMappingService userAuthMappingService;

    @Resource
    private EmployeeTrainingDAO employeeTrainingDAO;

    @Resource
    private RegionService regionService;

    @Resource
    private RegionDao regionDao;

    @Resource
    private TempUserDetailDAO tempUserDetailDAO;

    @Resource
    private ShopInfoDAO shopInfoDAO;

    @Resource
    private EnterpriseUserDAO enterpriseUserDAO;

    @Resource
    private StoreDao storeDAO;

    @Resource
    private AssessmentTemplateDAO assessmentTemplateDAO;

    @Resource
    private AssessmentDataDAO assessmentDataDAO;

    @Resource
    private RedisUtilPool redisUtilPool;

    @Resource
    private XfsgEhrService xfsgEhrService;

    @Resource
    private LineInfoDAO lineInfoDAO;

    @Resource
    private CommonService commonService;

    @Resource
    private ShopStageInfoDAO shopStageInfoDAO;

    @Resource
    private PreparationService preparationService;

    @Override
    public PageInfo<EmployeeTrainingVO> employeeTrainingList(String userId, EmployeeTrainingRequest request) {
        List<String> authRegionIdList = new ArrayList<>();
        if (!sysRoleService.checkIsAdmin(userId)) {
            authRegionIdList = userAuthMappingService.getAuthRegionIdAndSubRegionIdByUserId(userId);
        }
        if (CollectionUtils.isNotEmpty(request.getRegionIdList())) {
            if (request.getRegionIdList().contains(CommonConstants.ROOT_DEPT_ID_STR)) {
                request.setRegionIdList(null);
            } else {
                request.setRegionIdList(regionService.getSubRegionIdsByRegionIds(request.getRegionIdList()));
            }
        }
        List<String> storeNumList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(request.getStoreIdList())){
            storeNumList = storeDAO.getStoreNumByStoreIds(request.getStoreIdList());
            if(CollectionUtils.isEmpty(storeNumList)){
                return new PageInfo<>();
            }
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<EmployeeTrainingVO> list = employeeTrainingDAO.employeeTrainingList(request.getKeyWord(), request.getRegionIdList(), authRegionIdList, request.getAssignFlag(),
                DateUtils.parseLongDateToStr(request.getBeginTime()),
                DateUtils.parseLongDateToStr(request.getEndTime()), storeNumList,
                request.getTheoreticalExamStatus(), request.getPracticalExamStatus(), request.getAssessmentStatus(), request.getAssignStoreFlag());
        if (CollectionUtils.isEmpty(list)) {
            return new PageInfo<>(list);
        }

        List<Long> regionIds = list.stream().map(EmployeeTrainingVO::getRegionId).distinct().collect(Collectors.toList());

        List<Long> lineIdList = list.stream().map(EmployeeTrainingVO::getLineId).distinct().collect(Collectors.toList());

        List<String> storeIdList = list.stream().map(EmployeeTrainingVO::getTrainingStoreId).distinct().collect(Collectors.toList());

        List<StoreDO> storeDOList = storeDAO.getEffectiveStoreByStoreIds(storeIdList);
        Map<String, String> storeNameMap = storeDOList.stream().collect(Collectors.toMap(StoreDO::getStoreId, StoreDO::getStoreName));

        List<String> userIdList = list.stream().map(EmployeeTrainingVO::getTrainingTeacherUserId).distinct().collect(Collectors.toList());


        List<String> practicalUserIdList = list.stream().map(EmployeeTrainingVO::getPracticalAssessmentUserId).distinct().collect(Collectors.toList());

        if (CollectionUtils.isNotEmpty(practicalUserIdList)) {
            userIdList.addAll(practicalUserIdList);
        }

        List<PlanLineDTO> lineInfoList = lineInfoDAO.getLines(lineIdList);
        Map<Long, String> lineInfoMap = lineInfoList.stream().collect(Collectors.toMap(PlanLineDTO::getLineId, PlanLineDTO::getUsername));

        Map<String, String> userNameMap = enterpriseUserDAO.getUserNameMap(userIdList);

        Map<Long, String> regionNameMap = regionService.getBelongWarRegionNameMap(regionIds);

        list.forEach(item -> {
            item.setRegionNodeName(regionNameMap.get(item.getRegionId()));
            item.setTrainingStoreName(storeNameMap.get(item.getTrainingStoreId()));
            item.setTrainingTeacherUserName(userNameMap.get(item.getTrainingTeacherUserId()));
            item.setPracticalAssessmentUserName(userNameMap.get(item.getPracticalAssessmentUserId()));
            item.setFranchiseeName(lineInfoMap.get(item.getLineId()));
        });
        return new PageInfo<>(list);
    }

    @Override
    public EmployeeTrainingDetailVO employeeTrainingDetail(Long id) {
        TempUserDetailDO tempUserDetailDO = tempUserDetailDAO.selectById(id);

        EmployeeTrainingDO employeeTrainingDO = employeeTrainingDAO.selectByUserDetailId(id);

        EmployeeTrainingDetailVO employeeTrainingVO = new EmployeeTrainingDetailVO();
        employeeTrainingVO.setRoleId(tempUserDetailDO.getRoleId());
        employeeTrainingVO.setMobile(tempUserDetailDO.getMobile());
        employeeTrainingVO.setUsername(tempUserDetailDO.getUsername());
        employeeTrainingVO.setIdCard(tempUserDetailDO.getIdCard());
        employeeTrainingVO.setId(tempUserDetailDO.getId());
        Map<Long, String> regionNameMap = regionService.getBelongWarRegionNameMap(Collections.singletonList(tempUserDetailDO.getRegionId()));
        employeeTrainingVO.setRegionNodeName(regionNameMap.get(tempUserDetailDO.getRegionId()));
        employeeTrainingVO.setRegionId(tempUserDetailDO.getRegionId());
        ShopInfoDO shopInfoDO = shopInfoDAO.getShopInfo(tempUserDetailDO.getShopId());
        employeeTrainingVO.setShopName(shopInfoDO.getShopName());
        employeeTrainingVO.setShopId(tempUserDetailDO.getShopId());
        employeeTrainingVO.setAssignFlag(Boolean.FALSE);
        if(employeeTrainingDO != null){
            employeeTrainingVO.setTrainingStartTime(employeeTrainingDO.getTrainingStartTime());
            employeeTrainingVO.setTrainingEndTime(employeeTrainingDO.getTrainingEndTime());
            employeeTrainingVO.setTrainingStoreId(employeeTrainingDO.getTrainingStoreId());
            employeeTrainingVO.setEmployeeTrainingId(employeeTrainingDO.getId());
            StoreDO storeDO = storeDAO.getByStoreId(employeeTrainingDO.getTrainingStoreId());
            if (storeDO != null) {
                employeeTrainingVO.setTrainingStoreName(storeDO.getStoreName());
            }
            employeeTrainingVO.setTrainingTeacherUserId(employeeTrainingDO.getTrainingTeacherUserId());
            employeeTrainingVO.setTrainingTeacherUserName(enterpriseUserDAO.getUserName(employeeTrainingDO.getTrainingTeacherUserId()));
            employeeTrainingVO.setAssessmentStatus(employeeTrainingDO.getAssessmentStatus());
            employeeTrainingVO.setAssessmentNum(employeeTrainingDO.getAssessmentNum());
            employeeTrainingVO.setAssessmentTotalNum(employeeTrainingDO.getAssessmentTotalNum());
            employeeTrainingVO.setPracticalExamStatus(employeeTrainingDO.getPracticalExamStatus());
            employeeTrainingVO.setPracticalExamScore(employeeTrainingDO.getPracticalExamScore());
            employeeTrainingVO.setEstimatedAssessmentTime(employeeTrainingDO.getEstimatedAssessmentTime());
            employeeTrainingVO.setActualAssessmentTime(employeeTrainingDO.getActualAssessmentTime());
            employeeTrainingVO.setPracticalAssessmentUserId(employeeTrainingDO.getPracticalAssessmentUserId());
            employeeTrainingVO.setPracticalAssessmentUserName(enterpriseUserDAO.getUserName(employeeTrainingDO.getPracticalAssessmentUserId()));
            employeeTrainingVO.setAssignFlag(employeeTrainingDO.getAssignFlag());
            employeeTrainingVO.setShopId(employeeTrainingDO.getShopId());
        }
        return employeeTrainingVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void distribution(EmployeeTrainingDetailRequest request) {
        TempUserDetailDO tempUserDetailDO = tempUserDetailDAO.selectById(request.getId());

        EmployeeTrainingDO employeeTrainingDO = employeeTrainingDAO.selectByUserDetailId(request.getId());

        if (employeeTrainingDO != null && employeeTrainingDO.getAssignFlag()) {
            throw new ServiceException("已经分配培训，无法再次分配");
        }
        if (employeeTrainingDO == null) {
            employeeTrainingDO = new EmployeeTrainingDO();
        }
        List<AssessmentTemplateDO> assessmentTemplateDOList = assessmentTemplateDAO.listByType(AssessmentTemplateType.TRAINER.getCode());

        employeeTrainingDO.setAssignFlag(true);
        employeeTrainingDO.setTrainingTeacherUserId(request.getTrainingTeacherUserId());
        employeeTrainingDO.setTrainingStoreId(request.getTrainingStoreId());
        employeeTrainingDO.setTrainingStartTime(request.getTrainingStartTime());
        employeeTrainingDO.setTrainingEndTime(request.getTrainingEndTime());
        employeeTrainingDO.setEstimatedAssessmentTime(request.getEstimatedAssessmentTime());
        employeeTrainingDO.setAssessmentNum(0);
        employeeTrainingDO.setAssessmentTotalNum(assessmentTemplateDOList.size());
        employeeTrainingDO.setAssessmentStatus(0);
        if (employeeTrainingDO.getId() == null) {
            employeeTrainingDO.setXfsgUserDetailId(tempUserDetailDO.getId());
            employeeTrainingDO.setRegionId(tempUserDetailDO.getRegionId());
            employeeTrainingDO.setShopId(tempUserDetailDO.getShopId());
            employeeTrainingDAO.insertSelective(employeeTrainingDO);
        } else {
            employeeTrainingDAO.updateByPrimaryKeySelective(employeeTrainingDO);
        }
        Long shopId = tempUserDetailDO.getShopId();

        //分配教练员之后初始化实训数据
        List<AssessmentDataDO> assessmentDataDOList = new ArrayList<>();
        assessmentTemplateDOList.forEach(assessmentTemplateDO -> {
            AssessmentDataDO assessmentDataDO = new AssessmentDataDO();
            assessmentDataDO.setTemplateId(assessmentTemplateDO.getId());
            assessmentDataDO.setAssessmentUserId(tempUserDetailDO.getIdCard());
            assessmentDataDO.setShopId(shopId);
            assessmentDataDOList.add(assessmentDataDO);
        });
        assessmentDataDAO.batchInsertDO(assessmentDataDOList);


        Map<String, String> messageMap = new HashMap<>();
        messageMap.put("userName", tempUserDetailDO.getUsername());
        messageMap.put("mobile", tempUserDetailDO.getMobile());
        messageMap.put("registerTime", DateUtils.dateTime(tempUserDetailDO.getRegisterTime()));
        messageMap.put("userDetailId", tempUserDetailDO.getId().toString());
        commonService.sendMessage(Collections.singletonList(employeeTrainingDO.getTrainingTeacherUserId()), MessageEnum.MESSAGE_22, messageMap);
    }

    @Override
    public List<EmployeeTrainingVO> trainingListByShopId(Long shopId) {

        List<EmployeeTrainingVO> list = employeeTrainingDAO.trainingListByShopId(shopId, null, null);
        if (CollectionUtils.isEmpty(list)) {
            return list;
        }
        List<String> storeIdList = list.stream().map(EmployeeTrainingVO::getTrainingStoreId).collect(Collectors.toList());
        List<StoreDO> storeDOList = storeDAO.getEffectiveStoreByStoreIds(storeIdList);
        Map<String, String> storeNameMap = storeDOList.stream().collect(Collectors.toMap(StoreDO::getStoreId, StoreDO::getStoreName));

        List<Long> regionIdList = list.stream().map(EmployeeTrainingVO::getRegionId).collect(Collectors.toList());
        Map<Long, String> regionNameMap = regionService.getBelongWarRegionNameMap(regionIdList);

        list.forEach(item -> {
            item.setTrainingStoreName(storeNameMap.get(item.getTrainingStoreId()));
            item.setRegionNodeName(regionNameMap.get(item.getRegionId()));
            if(item.getAssessmentStatus() == null){
                //培训未开始
                item.setAssessmentStatus(-1);
            }
        });
        return list;
    }

    @Override
    public PageInfo<EmployeeTrainingVO> trainerUserList(String userId, Integer status, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<EmployeeTrainingVO> list = employeeTrainingDAO.trainingListByShopId(null, userId, status);
        if (CollectionUtils.isEmpty(list)) {
            return new PageInfo<>();
        }
        List<String> storeIdList = list.stream().map(EmployeeTrainingVO::getTrainingStoreId).collect(Collectors.toList());
        List<StoreDO> storeDOList = storeDAO.getEffectiveStoreByStoreIds(storeIdList);
        Map<String, String> storeNameMap = storeDOList.stream().collect(Collectors.toMap(StoreDO::getStoreId, StoreDO::getStoreName));

        List<Long> regionIdList = list.stream().map(EmployeeTrainingVO::getRegionId).collect(Collectors.toList());
        Map<Long, String> regionNameMap = regionService.getBelongWarRegionNameMap(regionIdList);

        list.forEach(item -> {
            item.setTrainingStoreName(storeNameMap.get(item.getTrainingStoreId()));
            item.setRegionNodeName(regionNameMap.get(item.getRegionId()));
        });
        return new PageInfo<>(list);
    }

    @Override
    public EmployeeUserTrainingVO trainerUserDetail(Long id) {
        EmployeeUserTrainingVO employeeUserTrainingVO = new EmployeeUserTrainingVO();
        TempUserDetailDO tempUserDetailDO = tempUserDetailDAO.selectById(id);

        EmployeeTrainingDO employeeTrainingDO = employeeTrainingDAO.selectByUserDetailId(id);
        employeeUserTrainingVO.setEmployeeTrainingId(employeeTrainingDO.getId());
        employeeUserTrainingVO.setTrainingTeacherUserId(employeeTrainingDO.getTrainingTeacherUserId());
        employeeUserTrainingVO.setTrainingStoreId(employeeTrainingDO.getTrainingStoreId());
        employeeUserTrainingVO.setTrainingStartTime(employeeTrainingDO.getTrainingStartTime());
        employeeUserTrainingVO.setTrainingEndTime(employeeTrainingDO.getTrainingEndTime());
        employeeUserTrainingVO.setAssessmentNum(employeeTrainingDO.getAssessmentNum());
        employeeUserTrainingVO.setAssessmentTotalNum(employeeTrainingDO.getAssessmentTotalNum());
        employeeUserTrainingVO.setMobile(tempUserDetailDO.getMobile());
        employeeUserTrainingVO.setRoleId(tempUserDetailDO.getRoleId());
        employeeUserTrainingVO.setIdCard(tempUserDetailDO.getIdCard());
        employeeUserTrainingVO.setId(tempUserDetailDO.getId());
        employeeUserTrainingVO.setUsername(tempUserDetailDO.getUsername());
        employeeUserTrainingVO.setRegionId(tempUserDetailDO.getRegionId());
        employeeUserTrainingVO.setShopId(tempUserDetailDO.getShopId());
        ShopInfoDO shopInfoDO = shopInfoDAO.getShopInfo(tempUserDetailDO.getShopId());
        if (shopInfoDO != null) {
            employeeUserTrainingVO.setShopName(shopInfoDO.getShopName());
        }
        StoreDO storeDO = storeDAO.getByStoreId(employeeTrainingDO.getTrainingStoreId());
        if (storeDO != null) {
            employeeUserTrainingVO.setTrainingStoreName(storeDO.getStoreName());
        }

        employeeUserTrainingVO.setTrainingTeacherUserName(enterpriseUserDAO.getUserName(employeeTrainingDO.getTrainingTeacherUserId()));
        List<AssessmentTemplateDO> assessmentTemplateDOList = assessmentTemplateDAO.listByType(AssessmentTemplateType.TRAINER.getCode());
        List<Long> templateIdList = assessmentTemplateDOList.stream().map(AssessmentTemplateDO::getId).collect(Collectors.toList());

        List<AssessmentDataDO> assessmentDataDOList = assessmentDataDAO.selectList(tempUserDetailDO.getIdCard(), templateIdList);

        Map<String, AssessmentDataDO> assessmentDataMap = new HashMap<>();
        assessmentDataDOList.forEach(item -> {
            assessmentDataMap.put(item.getTemplateId() + CommonConstants.COLON + item.getAssessmentUserId(), item);
        });
        List<AssessmentTemplateDataVO> templateDataVOList = new ArrayList<>();
        assessmentTemplateDOList.forEach(item -> {
            AssessmentTemplateDataVO assessmentTemplateDataVO = new AssessmentTemplateDataVO();
            AssessmentDataDO assessmentDataDO = assessmentDataMap.get(item.getId() + CommonConstants.COLON + tempUserDetailDO.getIdCard());
            if (assessmentDataDO != null) {
                assessmentTemplateDataVO.setGoalScore(assessmentDataDO.getScore());
                assessmentTemplateDataVO.setReason(assessmentDataDO.getReason());
                assessmentTemplateDataVO.setComments(assessmentDataDO.getComments());
                assessmentTemplateDataVO.setQualified(assessmentDataDO.getQualified());
                assessmentTemplateDataVO.setAssessmentDataId(assessmentDataDO.getId());
            }
            assessmentTemplateDataVO.setScore(item.getScore());
            assessmentTemplateDataVO.setTemplateName(item.getTemplateName());
            assessmentTemplateDataVO.setTemplateRemarkList(Arrays.asList(item.getTemplateRemark().split(CommonConstants.COMMA)));
            assessmentTemplateDataVO.setCategory(item.getCategory());
            assessmentTemplateDataVO.setId(item.getId());
            assessmentTemplateDataVO.setType(item.getType());
            assessmentTemplateDataVO.setTemplateRequirements(item.getTemplateRequirements());
            templateDataVOList.add(assessmentTemplateDataVO);
        });
        employeeUserTrainingVO.setTemplateDataList(templateDataVOList);
        Map<Long, String> regionNameMap = regionService.getBelongWarRegionNameMap(Collections.singletonList(employeeTrainingDO.getRegionId()));
        employeeUserTrainingVO.setRegionNodeName(regionNameMap.get(employeeTrainingDO.getRegionId()));
        return employeeUserTrainingVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void trainerUserCommit(EmployeeTrainingCommitListRequest request) {
        if (CollectionUtils.isEmpty(request.getList())) {
            return;
        }

        Long userDetailId = request.getUserDetailId();
        TempUserDetailDO tempUserDetailDO = tempUserDetailDAO.selectById(userDetailId);
        EmployeeTrainingDO employeeTrainingDO = employeeTrainingDAO.selectByUserDetailId(userDetailId);

        String idCard = tempUserDetailDO.getIdCard();
        request.getList().forEach(item -> {
            AssessmentDataDO assessmentDataDO = null;
            if (item.getId() != null) {
                assessmentDataDO = assessmentDataDAO.selectByPrimaryKey(item.getId());
            } else {
                assessmentDataDO = assessmentDataDAO.selectByTemplateId(item.getTemplateId(), item.getUserDetailId(), item.getShopId());
            }
            if (assessmentDataDO != null) {
                assessmentDataDO.setQualified(item.getQualified());
                assessmentDataDAO.updateByPrimaryKeySelective(assessmentDataDO);
            } else {
                assessmentDataDO = new AssessmentDataDO();
                assessmentDataDO.setTemplateId(item.getTemplateId());
                assessmentDataDO.setAssessmentUserId(idCard);
                assessmentDataDO.setShopId(item.getShopId());
                assessmentDataDO.setQualified(item.getQualified());
                assessmentDataDAO.insertSelective(assessmentDataDO);
            }
        });
        Integer num = assessmentDataDAO.selectCount(idCard, tempUserDetailDO.getShopId());
        employeeTrainingDO.setAssessmentNum(num);
        if (num.equals(employeeTrainingDO.getAssessmentTotalNum())) {
            employeeTrainingDO.setAssessmentStatus(1);
        }
        employeeTrainingDAO.updateByPrimaryKeySelective(employeeTrainingDO);
    }

    @Override
    public PageInfo<EmployeeTrainingVO> assessmentUserList(String userId, EmployeeAssessmentRequest request) {

        List<String> requestStoreIdList = request.getStoreIdList();
        Boolean isAdmin = sysRoleService.checkIsAdmin(userId);
        if (CollectionUtils.isEmpty(requestStoreIdList) && StringUtils.isNotBlank(userId) && !isAdmin) {
            requestStoreIdList = userAuthMappingService.getAuthStoreIdAndSubRegionIdByUserId(userId);
            if(CollectionUtils.isEmpty(requestStoreIdList)){
                return new PageInfo<>();
            }
        }
        String practicalAssessmentUserId = userId;
        //空意味着管理员
        if(isAdmin){
            practicalAssessmentUserId = null;
        }

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<EmployeeTrainingVO> employeeTrainingVOList = employeeTrainingDAO
                .assessmentUserList(request.getName(), practicalAssessmentUserId, request.getAssessmentStatus(),
                DateUtils.parseLongDateToStr(request.getEstimatedAssessmentBeginTime()),
                DateUtils.parseLongDateToStr(request.getEstimatedAssessmentEndTime()),
                DateUtils.parseLongDateToStr(request.getActualAssessmentBeginTime()),
                DateUtils.parseLongDateToStr(request.getActualAssessmentEndTime()), requestStoreIdList);
        if (CollectionUtils.isEmpty(employeeTrainingVOList)) {
            return new PageInfo<>(employeeTrainingVOList);
        }
        List<String> storeIdList = employeeTrainingVOList.stream().map(EmployeeTrainingVO::getTrainingStoreId).collect(Collectors.toList());
        List<StoreDO> storeDOList = storeDAO.getEffectiveStoreByStoreIds(storeIdList);
        Map<String, String> storeNameMap = storeDOList.stream().collect(Collectors.toMap(StoreDO::getStoreId, StoreDO::getStoreName));

        List<Long> regionIdList = employeeTrainingVOList.stream().map(EmployeeTrainingVO::getRegionId).collect(Collectors.toList());
        Map<Long, String> regionNameMap = regionService.getBelongWarRegionNameMap(regionIdList);

        employeeTrainingVOList.forEach(item -> {
            item.setTrainingStoreName(storeNameMap.get(item.getTrainingStoreId()));
            item.setRegionNodeName(regionNameMap.get(item.getRegionId()));
        });
        return new PageInfo<>(employeeTrainingVOList);
    }

    @Override
    public AssessmentUserTrainingVO assessmentUserDetail(Long id) {
        AssessmentUserTrainingVO assessmentUserTrainingVO = new AssessmentUserTrainingVO();
        TempUserDetailDO tempUserDetailDO = tempUserDetailDAO.selectById(id);

        EmployeeTrainingDO employeeTrainingDO = employeeTrainingDAO.selectByUserDetailId(id);
        assessmentUserTrainingVO.setEmployeeTrainingId(employeeTrainingDO.getId());
        assessmentUserTrainingVO.setTrainingStoreId(employeeTrainingDO.getTrainingStoreId());
        StoreDO storeDO = storeDAO.getByStoreId(employeeTrainingDO.getTrainingStoreId());
        if (storeDO != null) {
            assessmentUserTrainingVO.setTrainingStoreName(storeDO.getStoreName());
        }
        assessmentUserTrainingVO.setPracticalAssessmentUserId(employeeTrainingDO.getPracticalAssessmentUserId());
        assessmentUserTrainingVO.setPracticalAssessmentUserName(enterpriseUserDAO.getUserName(employeeTrainingDO.getPracticalAssessmentUserId()));
        assessmentUserTrainingVO.setMobile(tempUserDetailDO.getMobile());
        assessmentUserTrainingVO.setRoleId(tempUserDetailDO.getRoleId());
        assessmentUserTrainingVO.setIdCard(tempUserDetailDO.getIdCard());
        assessmentUserTrainingVO.setActualAssessmentTime(employeeTrainingDO.getActualAssessmentTime());
        assessmentUserTrainingVO.setEstimatedAssessmentTime(employeeTrainingDO.getEstimatedAssessmentTime());
        assessmentUserTrainingVO.setUsername(tempUserDetailDO.getUsername());
        assessmentUserTrainingVO.setAssessmentStatus(employeeTrainingDO.getAssessmentStatus());
        assessmentUserTrainingVO.setShopId(tempUserDetailDO.getShopId());

        assessmentUserTrainingVO.setAssessmentNum(employeeTrainingDO.getAssessmentNum());
        assessmentUserTrainingVO.setAssessmentTotalNum(employeeTrainingDO.getAssessmentTotalNum());
        assessmentUserTrainingVO.setPracticalExamScore(employeeTrainingDO.getPracticalExamScore());
        assessmentUserTrainingVO.setPracticalExamStatus(employeeTrainingDO.getPracticalExamStatus());
        assessmentUserTrainingVO.setId(tempUserDetailDO.getId());
        assessmentUserTrainingVO.setRegionId(tempUserDetailDO.getRegionId());
        ShopInfoDO shopInfoDO = shopInfoDAO.getShopInfo(employeeTrainingDO.getShopId());
        if (shopInfoDO != null) {
            assessmentUserTrainingVO.setShopName(shopInfoDO.getShopName());
        }

        Map<Long, String> regionNameMap = regionService.getBelongWarRegionNameMap(Collections.singletonList(employeeTrainingDO.getRegionId()));
        assessmentUserTrainingVO.setRegionNodeName(regionNameMap.get(employeeTrainingDO.getRegionId()));

        Integer templateType = AssessmentTemplateType.STORE_MANAGER.getCode();
        if(UserRoleEnum.XFSG_CLERK.getCode().equals(tempUserDetailDO.getRoleId())){
            templateType = AssessmentTemplateType.CLERK.getCode();
        }

        List<AssessmentTemplateDO> assessmentTemplateDOList = assessmentTemplateDAO.listByType(templateType);

        List<Long> templateIdList = assessmentTemplateDOList.stream().map(AssessmentTemplateDO::getId).collect(Collectors.toList());

        List<AssessmentDataDO> assessmentDataDOList = assessmentDataDAO.selectList(tempUserDetailDO.getIdCard(), templateIdList);

        Map<String, AssessmentDataDO> assessmentDataMap = new HashMap<>();
        assessmentDataDOList.forEach(item -> {
            assessmentDataMap.put(item.getTemplateId() + CommonConstants.COLON + item.getAssessmentUserId(), item);
        });
        List<AssessmentTemplateDataVO> templateDataVOList = new ArrayList<>();
        assessmentTemplateDOList.forEach(item -> {
            AssessmentTemplateDataVO assessmentTemplateDataVO = new AssessmentTemplateDataVO();
            AssessmentDataDO assessmentDataDO = assessmentDataMap.get(item.getId() + CommonConstants.COLON + tempUserDetailDO.getIdCard());
            if (assessmentDataDO != null) {
                assessmentTemplateDataVO.setGoalScore(assessmentDataDO.getScore());
                assessmentTemplateDataVO.setReason(assessmentDataDO.getReason());
                assessmentTemplateDataVO.setComments(assessmentDataDO.getComments());
                assessmentTemplateDataVO.setQualified(assessmentDataDO.getQualified());
                assessmentTemplateDataVO.setAssessmentDataId(assessmentDataDO.getId());
                assessmentTemplateDataVO.setPicture(assessmentDataDO.getPicture());
                assessmentTemplateDataVO.setVideo(assessmentDataDO.getVideo());
            }
            assessmentTemplateDataVO.setScore(item.getScore());
            assessmentTemplateDataVO.setTemplateName(item.getTemplateName());
            assessmentTemplateDataVO.setTemplateRemarkList(Arrays.asList(item.getTemplateRemark().split(CommonConstants.COMMA)));
            assessmentTemplateDataVO.setCategory(item.getCategory());
            assessmentTemplateDataVO.setId(item.getId());
            assessmentTemplateDataVO.setType(item.getType());
            assessmentTemplateDataVO.setCategory(item.getCategory());
            assessmentTemplateDataVO.setTemplateRequirements(item.getTemplateRequirements());
            assessmentTemplateDataVO.setCheckType(item.getCheckType());
            templateDataVOList.add(assessmentTemplateDataVO);
        });
        assessmentUserTrainingVO.setTemplateDataList(templateDataVOList);
        return assessmentUserTrainingVO;
    }

    @Override
    public void turn(Long id, String userId, String turnUserId) {
        TempUserDetailDO tempUserDetailDO = tempUserDetailDAO.selectById(id);

        EmployeeTrainingDO employeeTrainingDO = employeeTrainingDAO.selectByUserDetailId(id);

        employeeTrainingDO.setPracticalAssessmentUserId(turnUserId);

        employeeTrainingDAO.updateByPrimaryKeySelective(employeeTrainingDO);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void assessmentUserCommit(EmployeeAssessmentCommitListRequest request, LoginUserInfo user) {
        if (CollectionUtils.isEmpty(request.getList())) {
            return;
        }
        EmployeeTrainingDO employeeTrainingDO = employeeTrainingDAO.selectById(request.getEmployeeTrainingId());
        TempUserDetailDO tempUserDetailDO = tempUserDetailDAO.selectById(employeeTrainingDO.getXfsgUserDetailId());
        ShopInfoDO shopInfoDO = shopInfoDAO.getShopInfo(tempUserDetailDO.getShopId());
        String idCard = tempUserDetailDO.getIdCard();
        AtomicReference<Long> totalScore = new AtomicReference<>(0L);
        Integer templateType = AssessmentTemplateType.STORE_MANAGER.getCode();
        if(UserRoleEnum.XFSG_CLERK.getCode().equals(tempUserDetailDO.getRoleId())){
            templateType = AssessmentTemplateType.CLERK.getCode();
        }
        List<AssessmentTemplateDO> assessmentTemplateDOList = assessmentTemplateDAO.listByType(templateType);

        List<Long> templateIdList = assessmentTemplateDOList.stream().map(AssessmentTemplateDO::getId).collect(Collectors.toList());

        List<AssessmentDataDO> assessmentDataDOList = assessmentDataDAO.selectList(idCard, templateIdList);
        request.getList().forEach(item -> {
            AssessmentDataDO assessmentDataDO = null;
            totalScore.set(totalScore.get() + item.getScore());
            if (item.getId() != null) {
                assessmentDataDO = assessmentDataDAO.selectByPrimaryKey(item.getId());
            } else {
                assessmentDataDO = assessmentDataDAO.selectByTemplateId(item.getTemplateId(), idCard, item.getShopId());
            }
            if (assessmentDataDO != null) {
                assessmentDataDO.setScore(item.getScore());
                assessmentDataDO.setComments(item.getComments());
                assessmentDataDO.setPicture(item.getPicture());
                assessmentDataDO.setVideo(item.getVideo());
            } else {
                assessmentDataDO = new AssessmentDataDO();
                assessmentDataDO.setTemplateId(item.getTemplateId());
                assessmentDataDO.setShopId(item.getShopId());
                assessmentDataDO.setComments(item.getComments());
                assessmentDataDO.setScore(item.getScore());
                assessmentDataDO.setAssessmentUserId(idCard);
                assessmentDataDO.setPicture(item.getPicture());
                assessmentDataDO.setVideo(item.getVideo());
                assessmentDataDAO.insertSelective(assessmentDataDO);
            }
            assessmentDataDOList.add(assessmentDataDO);
        });
        checkVideoHandel(assessmentDataDOList);
        assessmentDataDAO.batchInsertOrUpdate(assessmentDataDOList);

        employeeTrainingDO.setPracticalAssessmentUserId(user.getUserId());
        employeeTrainingDO.setPracticalExamScore(totalScore.get().intValue());
        if (totalScore.get().intValue() > CommonConstants.NINETY) {
            employeeTrainingDO.setPracticalExamStatus(1);
        } else {
            employeeTrainingDO.setPracticalExamStatus(2);
        }
        employeeTrainingDO.setPracticalExamScore(totalScore.get().intValue());
        employeeTrainingDO.setActualAssessmentTime(new Date());


        if (employeeTrainingDO.getPracticalExamStatus() == CommonConstants.TWO) {
            employeeTrainingDO.setAssessmentStatus(CommonConstants.THREE);
        }
        if (employeeTrainingDO.getPracticalExamStatus() == 1) {
            employeeTrainingDO.setAssessmentStatus(CommonConstants.TWO);
        }
        employeeTrainingDAO.updateByPrimaryKeySelective(employeeTrainingDO);

        //查询员工是否全部培训完成
        Integer unCompleteNum = employeeTrainingDAO.unCompleteNum(employeeTrainingDO.getShopId());
        if (unCompleteNum != null && unCompleteNum == 0) {
            // 培训全部结束

            //登记人员，培训状态由未开始到培训中
//            ShopStageInfoDO shopStageInfoDO = shopStageInfoDAO.getShopSubStageInfo(tempUserDetailDO.getShopId(), ShopSubStageEnum.SHOP_STAGE_6);
//            if(shopStageInfoDO != null && shopStageInfoDO.getShopSubStageStatus().equals(ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_60.getShopSubStageStatus())){
//                shopStageInfoDAO.updateShopStageInfo(tempUserDetailDO.getShopId(), ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_61);
//                //状态结束
//                preparationService.whetherToOpenForAcceptance(tempUserDetailDO.getShopId());
//            }

            Map<String, String> messageMap = new HashMap<>();
            messageMap.put("storeName", shopInfoDO.getShopName());
            LineInfoDO lineInfoDO = lineInfoDAO.getLineInfo(tempUserDetailDO.getLineId());
        }
    }

    private void checkVideoHandel(List<AssessmentDataDO> assessmentDataDOList) {
        if (CollectionUtils.isEmpty(assessmentDataDOList)) {
            return;
        }
        for (AssessmentDataDO assessmentDataDO : assessmentDataDOList) {
            SmallVideoInfoDTO smallVideoInfo = JSONObject.parseObject(assessmentDataDO.getVideo(), SmallVideoInfoDTO.class);
            if (smallVideoInfo != null && CollectionUtils.isNotEmpty(smallVideoInfo.getVideoList())) {
                String callbackCache;
                SmallVideoDTO smallVideoCache;
                SmallVideoParam smallVideoParam;
                for (SmallVideoDTO smallVideo : smallVideoInfo.getVideoList()) {
                    //如果转码完成
                    if (smallVideo.getStatus() != null && smallVideo.getStatus() >= ResourceStatusEnum.TRANSCODE_FINISH.getValue()) {
                        continue;
                    }
                    callbackCache = redisUtilPool.getString(RedisConstant.VIDEO_CALLBACK_CACHE + smallVideo.getVideoId());
                    if (StringUtils.isNotBlank(callbackCache)) {
                        smallVideoCache = JSONObject.parseObject(callbackCache, SmallVideoDTO.class);
                        if (smallVideoCache != null && smallVideoCache.getStatus() != null && smallVideoCache.getStatus() >= 3) {
                            BeanUtils.copyProperties(smallVideoCache, smallVideo);
                        } else {
                            smallVideoParam = new SmallVideoParam();
                            setNotCompleteCache(smallVideoParam, smallVideo, assessmentDataDO.getId());
                        }
                    } else {
                        smallVideoParam = new SmallVideoParam();
                        setNotCompleteCache(smallVideoParam, smallVideo, assessmentDataDO.getId());
                    }
                }
                assessmentDataDO.setVideo(JSONObject.toJSONString(smallVideoInfo));
            }
        }
    }

    public void setNotCompleteCache(SmallVideoParam smallVideoParam, SmallVideoDTO smallVideo, Long businessId) {
        smallVideoParam.setVideoId(smallVideo.getVideoId());
        smallVideoParam.setUploadType(UploadTypeEnum.ASSESSMENT_DATA_CONTENT.getValue());
        smallVideoParam.setBusinessId(businessId);
        smallVideoParam.setUploadTime(new Date());
        //存入未转码完成的map，vod回调的时候使用
        redisUtilPool.hashSet(RedisConstant.VIDEO_NOT_COMPLETE_CACHE, smallVideo.getVideoId(), JSONObject.toJSONString(smallVideoParam));
    }
}
