package com.tykj.dev.device.train.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.github.wenhao.jpa.PredicateBuilder;
import com.tykj.dev.device.train.dao.TrainThemeDao;
import com.tykj.dev.device.train.entity.TrainTheme;
import com.tykj.dev.device.train.entity.vo.*;
import com.tykj.dev.device.train.service.TrainThemeService;
import com.tykj.dev.device.user.subject.service.MgrcertService;
import com.tykj.dev.device.user.subject.service.UserService;
import com.tykj.dev.misc.utils.JacksonUtil;
import com.tykj.dev.misc.utils.StringSplitUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import com.github.wenhao.jpa.Specifications;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zjm
 * @version 1.0.0
 * @ClassName TrainServiceImpl.java
 * @Description 培训逻辑层
 * @createTime 2020年08月13日 15:25:00
 */
@Service
public class TrainThemeServiceImpl implements TrainThemeService {

    @Autowired
    TrainThemeDao trainThemeDao;

    @Autowired
    MgrcertService mgrcertService;

    @Autowired
    UserService userService;
    @Override
    public TrainTheme save(TrainTheme trainTheme) {
        return trainThemeDao.save(trainTheme);
    }

    @Override
    public TrainTheme findById(Integer trainThemeId) {

        return trainThemeDao.findById(trainThemeId).get();
    }

    @Override
    public List<TrainTheme> findAllStatus(Integer status) {
        return trainThemeDao.findAllByTrainStatus(status);
    }

    @Override
    public ByTrainingPeople findByTrainingPeople(Integer trainThemeId, Integer userId) {
       TrainTheme trainTheme= trainThemeDao.findById(trainThemeId).get();
        ByTrainingPeople byTrainingPeople= trainTheme.toByTrainingPeople();
        List<GradeEntry> gradeEntries =new ArrayList<>();
        if (trainTheme.getTrainingResults()!=null) {
            gradeEntries = JacksonUtil.readValue(trainTheme.getTrainingResults(), new TypeReference<List<GradeEntry>>() {
             });
         }
         if (gradeEntries!=null && gradeEntries.size()!=0){
             gradeEntries.forEach(gradeEntry -> {
                 if (gradeEntry.getUserId()==userId){
                     byTrainingPeople.setScore(gradeEntry.getScore());
                     byTrainingPeople.setEvaluation(gradeEntry.getEvaluation());
                     byTrainingPeople.setMgrcert(mgrcertService.findByUserId(userId));
                 }
             });
         }
        return byTrainingPeople;
    }

    @Override
    public TrainRegistrationVo findRegistrationVo(Integer trainThemeId) {
        TrainTheme trainTheme = trainThemeDao.findById(trainThemeId).get();
        TrainRegistrationVo trainRegistrationVo= trainTheme.toTrainRegistrationVo();
        List<Integer> signUp = StringSplitUtil.userIdSplit(trainTheme.getSignUp());
        trainRegistrationVo.setSignUpUser(userService.findByIdListUserTarinVo(signUp));
        List<Integer> integerList1=JacksonUtil.readValue(trainTheme.getNoJoinUserId(), new TypeReference<List<Integer>>() {
        });
        List<Integer> integerList2=JacksonUtil.readValue(trainTheme.getJoinUserId(), new TypeReference<List<Integer>>() {
        });
        integerList1.addAll(integerList2);
        integerList1.removeAll(signUp);
        trainRegistrationVo.setNoSignUpUser(userService.findByIdListUserTarinVo(integerList1));

        return trainRegistrationVo;
    }

    @Override
    public TrainTrainingVo findTrainTrainingVo(Integer trainThemeId) {
        TrainTheme trainTheme = trainThemeDao.findById(trainThemeId).get();
        TrainTrainingVo trainTrainingVo= trainTheme.toTrainTrainingVo();
        List<Integer> signUp = StringSplitUtil.userIdSplit(trainTheme.getSignUp());
        trainTrainingVo.setSignUpUser(userService.findByIdListUserTarinVo(signUp));
        return trainTrainingVo;
    }

    @Override
    public TrainAuditVo findTrainAuditVo(Integer trainThemeId) {
        TrainTheme trainTheme = trainThemeDao.findById(trainThemeId).get();
        TrainAuditVo trainAuditVo= trainTheme.toTrainAuditVo();
        trainAuditVo.setGradeEntry(JacksonUtil.readValue(trainTheme.getTrainingResults(), new TypeReference<List<GradeEntry>>() {
        }));
        return trainAuditVo;
    }

    @Override
    public TrainTheme updateTrain(TrainUpdateVo trainUpdateVo) {
        TrainTheme trainTheme= trainThemeDao.findById(trainUpdateVo.getTrainId()).get();
        if (trainUpdateVo.getEndTime()!=null){
            trainTheme.setEndTime(trainUpdateVo.getEndTime());
        }
        if (trainUpdateVo.getSpeakerUserId()!=null){
            trainTheme.setSpeakerUserId(trainUpdateVo.getSpeakerUserId());
        }
        if (trainUpdateVo.getStartTime()!=null){
            trainTheme.setStartTime(trainUpdateVo.getStartTime());
        }
        if (trainUpdateVo.getTrainDataName()!=null){
            trainTheme.setTrainDataName(trainUpdateVo.getTrainDataName());
        }
        if (trainUpdateVo.getTrainDataUrl()!=null){
            trainTheme.setTrainDataUrl(trainUpdateVo.getTrainDataUrl());
        }
        if (trainUpdateVo.getTrainLocation()!=null){
            trainTheme.setTrainLocation(trainUpdateVo.getTrainLocation());
        }
        if (trainUpdateVo.getTrainSynopsis()!=null){
            trainTheme.setTrainSynopsis(trainUpdateVo.getTrainSynopsis());
        }
        return trainThemeDao.save(trainTheme);
    }

    @Override
    public TrainThemePage findTrainPageVo(ConditionsTrainVo conditionsTrainVo) {
        Pageable pageable = PageRequest.of(conditionsTrainVo.getPage(), conditionsTrainVo.getSize(), Sort.Direction.ASC, "trainTime");
        Page<TrainTheme> all = getContacts(conditionsTrainVo, pageable);

        List<TrainThemeVo> list=new ArrayList<>();
                all.get().forEach(
                        trainTheme -> {
                            list.add(trainTheme.toTrainThemeVo());
                        }
        );

        return TrainThemePage.builder()
                .data(list)
                .page(conditionsTrainVo.getPage())
                .size(conditionsTrainVo.getSize())
                .total((int) all.getTotalElements()).build();
    }

        private Page<TrainTheme> getContacts(ConditionsTrainVo conditionsTrainVo, Pageable pageable) {
            PredicateBuilder<TrainTheme> predicateBuilder = Specifications.and();
                if (conditionsTrainVo.getEndTime()!=null && conditionsTrainVo.getStatusTime()!=null){
                    predicateBuilder.gt("startTime",conditionsTrainVo.getStatusTime());
                    predicateBuilder.lt("endTime",conditionsTrainVo.getEndTime());
                }
                if (conditionsTrainVo.getDimName() != null) {
                    Class<TrainTheme> trainThemeClass = TrainTheme.class;
                    Field[] declaredFields = trainThemeClass.getDeclaredFields();
                    PredicateBuilder<TrainTheme> p = Specifications.or();
                    for (Field field : declaredFields) {
                        if (field.getType().equals(String.class)) {
                            p.like(field.getName(), "%" + conditionsTrainVo.getDimName() + "%");
                        }
                    }
                    predicateBuilder.predicate(p.build());
                }
        return trainThemeDao.findAll(predicateBuilder.build(), pageable);
    }



}
