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.StudySubject;
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.common.SignForm;
import com.hxhq.business.form.study.StudySubjectUserSaveForm;
import com.hxhq.business.service.IStudyJcgjService;
import com.hxhq.business.service.IStudyService;
import com.hxhq.business.service.IStudySubjectService;
import com.hxhq.business.utils.JctUtil;
import com.hxhq.common.core.exception.ServiceException;
import com.hxhq.common.core.utils.StringUtils;
import com.hxhq.common.core.web.domain.AjaxResult;
import com.hxhq.common.security.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hxhq.business.mapper.StudySubjectUserMapper;
import com.hxhq.business.domain.StudySubjectUser;
import com.hxhq.business.service.IStudySubjectUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 试验-学科-成员Service业务层处理
 *
 * @author hxhq
 * @date 2025-12-29
 */
@Service
public class StudySubjectUserServiceImpl extends ServiceImpl<StudySubjectUserMapper, StudySubjectUser> implements IStudySubjectUserService
{
    @Autowired
    private IStudySubjectService studySubjectService;
    @Autowired
    private IStudyService studyService;
    @Autowired
    private IStudyJcgjService studyJcgjService;

    @Override
    public List<StudySubjectUser> getListByStudySubjectId(Long studySubjectId) {
        QueryWrapper<StudySubjectUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("study_subject_id",studySubjectId);
        return list(queryWrapper);
    }

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

        //传入的成员信息
        List<StudySubjectUser> itemList = form.getSubjectUserList();
        //已经设置的学科信息
        List<StudySubjectUser> oldList = getListByStudySubjectId(form.getStudySubjectId());
        List<StudySubjectUser> deleteList = new ArrayList<>();
        List<StudySubjectUser> addList = new ArrayList<>();
        List<StudySubjectUser> modifyList = new ArrayList<>();

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

        for(StudySubjectUser item : itemList){
            List<StudySubjectUser> existsList = oldList.stream().filter(o->o.getUserId().equals(item.getUserId())).collect(Collectors.toList());
            if(existsList.size()==0){
                item.setStudySubjectId(form.getStudySubjectId());
                item.setStudyId(studySubject.getStudyId());
                addList.add(item);

                addNameList.add(item.getUserName());
                addNameEnList.add(item.getUserNameEn());
            }else{
                item.setId(existsList.get(0).getId());
                modifyList.add(item);

                if(!existsList.get(0).getUserName().equals(item.getUserName())){
                    addNameList.add(item.getUserName());
                    addNameEnList.add(item.getUserNameEn());
                    deleteNameList.add(existsList.get(0).getUserName());
                    deleteNameEnList.add(existsList.get(0).getUserNameEn());
                }
            }
        }

        for(StudySubjectUser old : oldList){
            if(itemList.stream().filter(o->o.getUserId().equals(old.getUserId())).collect(Collectors.toList()).size()==0){
                deleteList.add(old);
                deleteNameList.add(old.getUserName());
                deleteNameEnList.add(old.getUserNameEn());
            }
        }
        if(deleteList.size()>0){
            String name = baseMapper.getHasFormNameList(study.getId(),deleteList.stream().map(o->o.getUserId()).collect(Collectors.toList()));
            if(StringUtils.isNoneBlank(name)){
                throw new ServiceException(name+"已创建过表单，无法取消勾选");
            }
        }
        if(StringUtils.isBlank(form.getSign().getQmrmm())){
            return;
        }
        studyService.checkPassword(form.getSign());
        if(addList.size()>0){
            saveBatch(addList);
        }
        if(modifyList.size()>0){
            updateBatchById(modifyList);
        }
        if(deleteList.size()>0){
            removeBatchByIds(deleteList);
        }

        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(studySubject.getStudyId(), JcgjlxEnum.ry, JcmcysEnum.blue,JctUtil.formatStr(formData),JctUtil.formatStr(formDataEn),form.getSign());
        }
    }

    @Override
    public void deleteByStudySubjectId(Study study, Long studySubjectId, SignForm sign) {
        QueryWrapper<StudySubjectUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("study_subject_id",studySubjectId);
        List<StudySubjectUser> userList = list(queryWrapper);
        if(userList.size()>0){
            List<String> deleteNameList = userList.stream().map(o->o.getUserName()).collect(Collectors.toList());
            List<String> deleteNameEnList = userList.stream().map(o->o.getUserNameEn()).collect(Collectors.toList());
            if(deleteNameList.size()>0){
                Map<String, String> formData = new LinkedHashMap<>();
                Map<String, String> formDataEn = new LinkedHashMap<>();
                formData.put("删除人员", String.join("，",deleteNameList));
//                formDataEn.put("Remove Person", String.join("，",deleteNameEnList));
                formDataEn.put("Remove Person", String.join("，",deleteNameList));

                sign.setQmyy(study.getType().equals(StudyTypeEnum.sy.getValue())?"人员变更":study.getType().equals(StudyTypeEnum.fsy.getValue())?"人员变更":study.getType().equals(StudyTypeEnum.mjy.getValue())?"人员变更":"");
                sign.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),sign);
            }
        }
        remove(queryWrapper);
    }
}
