package com.ssj.service.kmt.kmt.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.ssj.bean.kmt.kmt.domain.KmtExerciseBook;
import com.ssj.bean.kmt.kmt.domain.KmtExerciseBookLib;
import com.ssj.bean.weixin.libmy.domain.TbLibJoin;
import com.ssj.dao.kmt.kmt.dao.KmtExerciseBookDao;
import com.ssj.dao.weixin.library.dao.ILibJoinDao;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.security.exception.CommonException;
import com.ssj.framework.core.util.StringUtil;
import com.ssj.service.kmt.constant.KnowledgeVersion;
import com.ssj.service.kmt.service.KmtExerciseBookLibService;
import com.ssj.service.kmt.service.KmtExerciseBookService;
import com.ssj.service.mapper.KmtExerciseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Transactional
@Service(version = "1.0")
public class KmtExerciseBookServiceImpl extends BaseServiceImpl<KmtExerciseBook, String> implements KmtExerciseBookService {

    @Autowired
    private KmtExerciseBookDao dao;

    @Autowired
    private KnowledgeVersion knowledgeVersion;

    @Autowired
    private ILibJoinDao libJoinDao;

    @Autowired
    private KmtExerciseBookLibService KmtExerciseBookLibService;

    @Autowired
    private KmtExerciseMapper kmtExerciseMapper;


    @Autowired
    private KmtExerciseBookLibService kmtExerciseBookLibService;

    @Override
    public PagingAndSortingRepository<KmtExerciseBook, String> getDao() {
        return dao;
    }

    @Override
    public KmtExerciseBook findSameBook(String bookName, String grade, String courseName, int semester, int version, int userYear, int bookType) {
        return dao.findTopByBookNameAndGradeAndCourseNameAndSemesterAndVersionAndBookYearAndBookType(bookName, grade, courseName, semester, version, userYear, bookType);
    }

    @Override
    public void updateAnswerCorrecterIdById(String teacherId, String exerciseBookId) {
        dao.updateAnswerCorrecterIdById(teacherId, exerciseBookId);
    }

    @Override
    public void updateAnswerCorrecterIdByIds(String teacherId, List<String> exerciseBookIds) {
        //dao.updateAnswerCorrecterIdByIds(teacherId, exerciseBookIds);
        kmtExerciseMapper.updateAnswerCorrecterIdByIds(teacherId,exerciseBookIds);
    }

    @Override
    public void updateHandleUserIdByIds(String teacherId, List<String> exerciseBookIds) {
        dao.updateHandleUserIdByIds(teacherId, exerciseBookIds);
    }

    @Override
    public void updateAuditingUserId(String teacherId, List<String> exerciseBookIds) {
        dao.updateAuditingUserId(teacherId, exerciseBookIds);
    }

    @Override
    public void updateAnalysisUserId(String teacherId, List<String> exerciseBookIds) {
        dao.updateAnalysisUserId(teacherId, exerciseBookIds);
    }

    @Override
    public void updateAnalysisAuditerId(String teacherId, List<String> exerciseBookIds) {
        dao.updateAnalysisAuditerId(teacherId, exerciseBookIds);
    }

    @Override
    public void updateVersion(int type, String subject, Integer version) {
        List<KmtExerciseBook> list;
        if (type == 1) {
            if (StringUtil.isNotBlank(subject)) {
                if (version != null) {
                    list = dao.findByCourseNameAndVersion(subject, version);
                } else {
                    list = dao.findByCourseName(subject);
                }
            } else {
                list = dao.findAll();
            }
        } else {
            list = dao.findByVersionNameIsNull();
        }
        list.forEach(e -> {
            e.setVersionName(knowledgeVersion.getVersionNameBySubjectAndVersionNum(e.getCourseName(), e.getVersion()));
        });
        this.save(list);
    }

    @Override
    public void updateExerciseLib() {
        List<KmtExerciseBook> list = dao.findByLibNameIsNotNull();
        //保存更新的
        list.forEach(e -> {
            //保存更新前的数据
            e.setMongodbComment("更新馆绑定备份数据");
//            mongoTemplate.save(e);
            //将已经绑定的图书馆解绑
            e.setOrgNums(0);
            List<KmtExerciseBookLib> exerciseBookLibList = KmtExerciseBookLibService.findByExerciseBookId(e.getId());
            exerciseBookLibList.forEach(exerciseBookLib -> exerciseBookLib.setIsDelete(1));
            KmtExerciseBookLibService.save(exerciseBookLibList);
            //重新绑定
            if (!"0".equals(e.getLibName())) {
                String[] libNames = e.getLibName().split(",");
                int nums = libNames.length;
                for (String libName : libNames) {
                    List<TbLibJoin> libList = libJoinDao.findByLeagueName(libName);
                    if (libList.size() == 1) {
                        KmtExerciseBookLib kmtExerciseBookLib = new KmtExerciseBookLib();
                        kmtExerciseBookLib.setLibId(libList.get(0).getId());
                        kmtExerciseBookLib.setExerciseBookId(e.getId());
                        kmtExerciseBookLib.setIsDelete(0);
                        KmtExerciseBookLibService.save(kmtExerciseBookLib);
                    } else if (libList.size() == 0) {
                        throw new CommonException(libName + "机构不存在");
                        //System.out.println("不存在的机构:"+libName);
                        //nums--;
                    } else if (libList.size() > 0) {
                        throw new CommonException(libName + "机构找到多个");
                        //System.out.println("机构找到多个:"+libName);
                        //nums--;
                    }
                }
                e.setOrgNums(nums);
            }
            if (e.getVersion() == 0) {
                e.setVersion(knowledgeVersion.getVersionNumBySubjectAndVersionName(e.getCourseName(), e.getVersionName()));
            }
            e.setLibName(null);
            this.save(e);
        });
    }

    @Override
    public void mergeSameExerciseBooks() {
        //所有重复的数据
        List<KmtExerciseBook> list = kmtExerciseMapper.findSameExerciseBookList();
        Map<String, KmtExerciseBook> data = new HashMap<>(16);
        //重复数据存入缓存，以便后面查询
        list.forEach(e -> {
//            mongoTemplate.save(e);
            String key = e.getBookName() + e.getCourseName() + e.getGrade() + e.getVersionName() + e.getSemester() + e.getBookType() + e.getBookYear();
            if (data.get(key) != null) {
                //后台导入
                //url1	url2	出版社	印刷年份	使用年份（同前面book_year）关联机构数 被识别次数	编辑人id	编辑人	更新时间 优先级	多年级综合识别率
                if (e.getPartFlag() == 3) {
                    KmtExerciseBook book = data.get(key);
                    book.setUrl1(e.getUrl1());
                    book.setUrl2(e.getUrl2());
                    book.setPress(e.getPress());
                    book.setPrintYear(e.getPrintYear());
                    book.setBookYear(e.getBookYear());
                    book.setOrgNums(e.getOrgNums());
                    book.setIdentifiedNums(e.getIdentifiedNums());
                    book.setUserId(e.getUserId());
                    book.setUserName(e.getUserName());
                    book.setUpdatedTime(e.getUpdatedTime());
                    book.setTotalGradePriority(e.getTotalGradePriority());
                    book.setExerciseRelevancyNum(e.getExerciseRelevancyNum());
                    List<KmtExerciseBookLib> libList = kmtExerciseBookLibService.findByExerciseBookId(e.getId());
                    libList.forEach(lib->{
                        KmtExerciseBookLib newLib = new KmtExerciseBookLib();
                        newLib.setExerciseBookId(book.getId());
                        newLib.setIsDelete(lib.getIsDelete());
                        newLib.setLibId(lib.getLibId());
                        kmtExerciseBookLibService.save(newLib);
                    });
                }
                this.delete(e);
                System.out.println(e.getId());
            } else {
                //因为经过了排序，如果有页面录入的，首个则为页面录入数据
                data.put(key, e);
            }
        });
        for (KmtExerciseBook kmtExerciseBook : data.values()) {
            this.save(kmtExerciseBook);
        }
    }

    @Override
    public void updateKmtExerciseBookByKmtExerciseModify(){
        List<Map<String, String>> list = kmtExerciseMapper.findUpdateExerciseBookList();
        Date now = new Date();
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i=0;i<500;i++){
                    Map<String, String> e=list.get(i);
                    KmtExerciseBook book = getById(list.get(i).get("id"));
                    book.setMongodbComment("更新时间："+now+";更新练习册的出版社、印刷年份、关联机构数据（此数据为更新前的备份数据）");
                    //mongoTemplate.save(book);
                    book.setPress(e.get("press"));
                    book.setPrintYear(e.get("print_year"));
                    book.setLibName(e.get("lib_name"));
                    save(book);
                }
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i=500;i<list.size();i++){
                    Map<String, String> e=list.get(i);
                    KmtExerciseBook book = getById(list.get(i).get("id"));
                    book.setMongodbComment("更新时间："+now+";更新练习册的出版社、印刷年份、关联机构数据（此数据为更新前的备份数据）");
                    //mongoTemplate.save(book);
                    book.setPress(e.get("press"));
                    book.setPrintYear(e.get("print_year"));
                    book.setLibName(e.get("lib_name"));
                    save(book);
                }
            }
        });
        thread1.start();
        thread2.start();
        /*list.forEach(e->{
            KmtExerciseBook book = this.getById(e.get("id"));
            book.setMongodbComment("更新时间："+now+";更新练习册的出版社、印刷年份、关联机构数据（此数据为更新前的备份数据）");
            mongoTemplate.save(book);
            book.setPress(e.get("press"));
            book.setPrintYear(e.get("print_year"));
            book.setLibName(e.get("lib_name"));
            this.save(book);
        });*/
        //this.updateExerciseLib();
    }

    @Override
    public void updateExerciseBookStatus(String exerciseBookId, String status) {
        dao.updateExerciseBookStatus(exerciseBookId, status);
    }
}