package com.hxhq.business.service.impl;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hxhq.business.domain.Study;
import com.hxhq.business.domain.StudySubjectUser;
import com.hxhq.business.dto.study.StudyListDto;
import com.hxhq.business.enums.study.StudyTypeEnum;
import com.hxhq.business.enums.zykgl.JcgjlxEnum;
import com.hxhq.business.enums.zykgl.JcmcysEnum;
import com.hxhq.business.form.study.StudySubjectSaveForm;
import com.hxhq.business.service.IStudyJcgjService;
import com.hxhq.business.service.IStudyService;
import com.hxhq.business.service.IStudySubjectUserService;
import com.hxhq.business.utils.JctUtil;
import com.hxhq.common.core.exception.ServiceException;
import com.hxhq.common.core.utils.StringUtils;
import com.hxhq.common.security.utils.SecurityUtils;
import com.hxhq.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hxhq.business.mapper.StudySubjectMapper;
import com.hxhq.business.domain.StudySubject;
import com.hxhq.business.service.IStudySubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 试验-学科Service业务层处理
 *
 * @author hxhq
 * @date 2025-12-29
 */
@Service
public class StudySubjectServiceImpl extends ServiceImpl<StudySubjectMapper, StudySubject> implements IStudySubjectService
{
    @Autowired
    private IStudyService studyService;
    @Autowired
    private IStudySubjectUserService studySubjectUserService;
    @Autowired
    private IStudyJcgjService studyJcgjService;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 获取试验下的学科设置信息(含未设置的学科)
     * @param studyId
     * @return
     */
    @Override
    public List<StudySubject> getAllListByStudyId(Long studyId) {
        List<StudySubject> allSubject = baseMapper.selectAllSubject();
        List<StudySubject> existsList = getListByStudyId(studyId);

        List<StudySubject> allList = new ArrayList<>();
        for(StudySubject subject : allSubject){
            StudySubject info = new StudySubject();
            info.setDeptId(subject.getDeptId());
            info.setDeptName(subject.getDeptName());
            info.setDeptJc(subject.getDeptJc());


            List<StudySubject> exists = existsList.stream().filter(o->o.getDeptId().equals(subject.getDeptId())).collect(Collectors.toList());
            if(exists.size()>0){
                info.setId(exists.get(0).getId());
                info.setStudyId(exists.get(0).getStudyId());
                info.setLeader(exists.get(0).getLeader());
                info.setLeaderName(exists.get(0).getLeaderName());
                info.setLeaderNameEn(exists.get(0).getLeaderNameEn());
                info.setSelect(true);
            }else{
                info.setSelect(false);
            }
            allList.add(info);
        }
        return allList;
    }

    /**
     * 获取已经设置的学科信息
     * @param studyId
     * @return
     */
    @Override
    public List<StudySubject> getListByStudyId(Long studyId){
        QueryWrapper<StudySubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("study_id",studyId);
        return list(queryWrapper);
    }

    @Override
    public List<StudySubject> initUserIdList(List<StudySubject> list) {
        if(list.size()>0){
            QueryWrapper<StudySubjectUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("study_subject_id",list.stream().map(o->o.getId()).collect(Collectors.toList()));
            queryWrapper.select("study_subject_id,user_id");
            List<StudySubjectUser> userList = studySubjectUserService.list(queryWrapper);
            for(StudySubject l : list){
                l.setUserIdList(userList.stream().filter(o->o.getStudySubjectId().equals(l.getId())).map(o->o.getUserId()).collect(Collectors.toList()));
            }
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveInfo(StudySubjectSaveForm form) {
        Study study = studyService.getById(form.getStudyId());
        if(study==null){
            throw new ServiceException("试验不存在");
        }

        //传入的学科信息
        List<StudySubject> itemList = form.getSubjectList();

        //已经设置的学科信息
        List<StudySubject> oldList = getListByStudyId(form.getStudyId());
        List<StudySubject> deleteList = new ArrayList<>();
        List<StudySubject> addList = new ArrayList<>();
        List<StudySubject> modifyList = new ArrayList<>();

        List<String> addNameList = new ArrayList<>();
        List<String> addNameEnList = new ArrayList<>();
        List<String> deleteNameList = new ArrayList<>();
        List<String> deleteNameEnList = new ArrayList<>();


        for(StudySubject item : itemList){
            List<StudySubject> exists = oldList.stream().filter(o->o.getDeptId().equals(item.getDeptId())).collect(Collectors.toList());
            if(exists.size()==0){
                item.setStudyId(form.getStudyId());
                addList.add(item);

                addNameList.add(item.getLeaderName());
                addNameEnList.add(item.getLeaderNameEn());
            }else{
                modifyList.add(item);
                if(!exists.get(0).getLeaderName().equals(item.getLeaderName())){
                    addNameList.add(item.getLeaderName());
                    addNameEnList.add(item.getLeaderNameEn());
                    deleteNameList.add(exists.get(0).getLeaderName());
                    deleteNameEnList.add(exists.get(0).getLeaderNameEn());
                }
            }
        }

        for(StudySubject old : oldList){
            if(itemList.stream().filter(o->o.getDeptId().equals(old.getDeptId())).collect(Collectors.toList()).size()==0){
                deleteList.add(old);
                deleteNameList.add(old.getLeaderName());
                deleteNameEnList.add(old.getLeaderNameEn());
            }
        }

        if(deleteList.size()>0){
            //已有表单的学科不能删除(预填+填报)
            List<StudyListDto> formCountList = baseMapper.queryFormCountList(deleteList.stream().map(o->o.getId()).collect(Collectors.toList()));
            List<StudyListDto> preFormCountList = baseMapper.queryPreFormCountList(deleteList.stream().map(o->o.getId()).collect(Collectors.toList()));
            for(StudySubject del : deleteList){
                if(formCountList.stream().filter(o->o.getId().equals(del.getId())).count()>0 || preFormCountList.stream().filter(o->o.getId().equals(del.getId())).count()>0){
                    throw new ServiceException(del.getDeptName()+"下已有表单，不能取消勾选");
                }
            }
        }
        if(StringUtils.isBlank(form.getSign().getQmrmm())){
            return;
        }

        studyService.checkPassword(form.getSign());
        if(deleteList.size()>0){
            removeBatchByIds(deleteList);
            for(StudySubject del : deleteList){
                studySubjectUserService.deleteByStudySubjectId(study,del.getId(),form.getSign());
            }
        }

        if(addList.size()>0){
            saveBatch(addList);
        }
        if(modifyList.size()>0){
            updateBatchById(modifyList);
        }
        if(deleteNameList.size()>0 || addNameList.size()>0){
            Map<String, String> formData = new LinkedHashMap<>();
            Map<String, String> formDataEn = new LinkedHashMap<>();
            if(addNameList.size()>0){
                formData.put("新增人员", String.join("，",addNameList));
//                formDataEn.put("Add Person", String.join("，",addNameEnList));
                formDataEn.put("Add Person", String.join("，",addNameList));
            }
            if(deleteNameList.size()>0){
                formData.put("删除人员", String.join("，",deleteNameList));
//                formDataEn.put("Remove Person", String.join("，",deleteNameEnList));
                formDataEn.put("Remove Person", String.join("，",deleteNameList));
            }
            form.getSign().setQmyy(study.getType().equals(StudyTypeEnum.sy.getValue())?"人员变更":study.getType().equals(StudyTypeEnum.fsy.getValue())?"人员变更":study.getType().equals(StudyTypeEnum.mjy.getValue())?"人员变更":"");
            form.getSign().setQmyyEn(study.getType().equals(StudyTypeEnum.sy.getValue())?"Change of Person":study.getType().equals(StudyTypeEnum.fsy.getValue())?"Change of Person":study.getType().equals(StudyTypeEnum.mjy.getValue())?"Change of Person":"");
            studyJcgjService.saveInfo(study.getId(), JcgjlxEnum.ry, JcmcysEnum.blue,JctUtil.formatStr(formData),JctUtil.formatStr(formDataEn),form.getSign());
        }
    }

    @Override
    public Boolean isMatchSubject(Long studySubjectId) {
        QueryWrapper<StudySubject> subjectQueryWrapper = new QueryWrapper<>();
        subjectQueryWrapper.eq("leader",SecurityUtils.getUserId());
        subjectQueryWrapper.eq("id",studySubjectId);
        if(count(subjectQueryWrapper)>0){
            return true;
        }else{
            QueryWrapper<StudySubjectUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",SecurityUtils.getUserId());
            queryWrapper.eq("study_subject_id",studySubjectId);
            return studySubjectUserService.count(queryWrapper)>0;
        }
    }

    @Override
    public Boolean isQA() {
        Long qaDeptId = 216L;
        return sysUserService.selectUserById(SecurityUtils.getUserId()).getDeptId().equals(qaDeptId);
    }
}
