package com.xinelu.manage.service.questioninfo.impl;

import com.xinelu.common.annotation.DataScope;
import com.xinelu.common.core.domain.AjaxResult;
import com.xinelu.common.enums.ContentedAndRemarkableFlagEnum;
import com.xinelu.common.enums.QuestionnaireStatusEnum;
import com.xinelu.common.utils.SecurityUtils;
import com.xinelu.common.utils.bean.BeanUtils;
import com.xinelu.common.utils.uuid.IdUtils;
import com.xinelu.manage.domain.agency.Agency;
import com.xinelu.manage.domain.questioninfo.QuestionInfo;
import com.xinelu.manage.domain.questionsubject.QuestionSubject;
import com.xinelu.manage.domain.questionsubjectoption.QuestionSubjectOption;
import com.xinelu.manage.dto.department.DepartmentCount;
import com.xinelu.manage.dto.questioninfo.QuestionInfoDto;
import com.xinelu.manage.mapper.agency.AgencyMapper;
import com.xinelu.manage.mapper.questioninfo.QuestionInfoMapper;
import com.xinelu.manage.mapper.questionsubject.QuestionSubjectMapper;
import com.xinelu.manage.mapper.questionsubjectoption.QuestionSubjectOptionMapper;
import com.xinelu.manage.service.questioninfo.IQuestionInfoService;
import com.xinelu.manage.vo.department.DepartmentBaseVo;
import com.xinelu.manage.vo.department.DepartmentVO;
import com.xinelu.manage.vo.questionInfo.QuestionVO;
import com.xinelu.manage.vo.questionsubject.QuestionSubjectVO;
import com.xinelu.manage.vo.questionsubjectoption.QuestionSubjectOptionVO;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 问卷基本信息Service业务层处理
 *
 * @author xinelu
 * @date 2024-02-28
 */
@Slf4j
@Service
public class QuestionInfoServiceImpl implements IQuestionInfoService {
    @Resource
    private QuestionInfoMapper questionInfoMapper;
    @Resource
    private QuestionSubjectMapper questionSubjectMapper;
    @Resource
    private QuestionSubjectOptionMapper questionSubjectOptionMapper;
	@Resource
	private AgencyMapper agencyMapper;


    @Override
    public QuestionVO selectQuestionInfoById(Long id) {
        //查询问卷表
        QuestionInfo questionInfo = questionInfoMapper.selectQuestionInfoById(id);
        //if (Objects.isNull(questionInfo)) {
        //    throw new ServiceException("该问卷信息已不存在！");
        //}
        QuestionVO questionVO = new QuestionVO();
        // 查询题目表
        if (Objects.nonNull(questionInfo)) {
            BeanUtils.copyBeanProp(questionVO, questionInfo);
            List<QuestionSubjectVO> questionSubjects = questionSubjectMapper.selectQuestionSubjectBy(id);
            List<Long> questionSubjectIds = questionSubjects.stream().filter(Objects::nonNull).filter(item -> Objects.nonNull(item.getId())).map(QuestionSubject::getId).collect(Collectors.toList());
            if (questionSubjectIds.size() == 0) {
                questionVO.setQuestionSubjectList(questionSubjects);
                return questionVO;
            }
            // 选项表
            List<QuestionSubjectOptionVO> questionSubjectOptions = questionSubjectOptionMapper.selectQuestionSubjectOptions(questionSubjectIds);
            for (QuestionSubjectVO questionSubject : questionSubjects) {
                List<QuestionSubjectOptionVO> collect = questionSubjectOptions.stream().filter(Objects::nonNull).filter(item -> Objects.nonNull(item.getQuestionnaireSubjectId()) && questionSubject.getId().equals(item.getQuestionnaireSubjectId())).collect(Collectors.toList());
                questionSubject.setQuestionSubjectOptionList(collect);
            }
            questionVO.setQuestionSubjectList(questionSubjects);
        }

        return questionVO;
    }

    /**
     * 查询问卷基本信息列表
     *
     * @param questionInfo 问卷基本信息
     * @return 问卷基本信息
     */
    @DataScope(agencyAlias = "dt", deptAlias = "qi")
    @Override
    public List<QuestionInfo> selectQuestionInfoList(QuestionInfoDto questionInfo) {
        return questionInfoMapper.selectQuestionList(questionInfo);
    }

    /**
     * 新增问卷基本信息
     *
     * @param question 问卷基本信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult insertQuestionInfo(QuestionVO question) {
        //新增问卷表
        QuestionInfo questionInfo = new QuestionInfo();
        BeanUtils.copyBeanProp(questionInfo, question);
        questionInfo.setCreateTime(LocalDateTime.now());
        questionInfo.setCreateBy(SecurityUtils.getUsername());
        questionInfo.setQuestionnaireId(IdUtils.fastUUID());
        int questionCount = questionInfoMapper.insertQuestionInfo(questionInfo);
        if (questionCount <= 0) {
            log.info("新增问卷表失败," + questionInfo);
            throw new SecurityException("新增问卷失败!请联系管理员！");
        }
        if (CollectionUtils.isEmpty(question.getQuestionSubjectList())) {
            throw new SecurityException("请添加问卷信息！");
        }
        //新增题目表
        List<QuestionSubjectVO> questionSubjectList = question.getQuestionSubjectList();
        List<QuestionSubject> questionSubjects = new ArrayList<>();
        List<QuestionSubjectOptionVO> questionSubjectOptions = new ArrayList<>();
        for (QuestionSubjectVO questionSubject : questionSubjectList) {
            if (StringUtils.isBlank(questionSubject.getQuestionName())) {
                throw new SecurityException("请添加完整问卷题目！");
            }
            QuestionSubject saveQuestionSubject = new QuestionSubject();
            BeanUtils.copyBeanProp(saveQuestionSubject, questionSubject);
            saveQuestionSubject.setQuestionInfoId(questionInfo.getId());
            saveQuestionSubject.setCreateTime(LocalDateTime.now());
            saveQuestionSubject.setCreateBy(SecurityUtils.getUsername());
            questionSubjects.add(saveQuestionSubject);
            if (CollectionUtils.isNotEmpty(questionSubject.getQuestionSubjectOptionList())) {
                questionSubjectOptions.addAll(questionSubject.getQuestionSubjectOptionList());
            }
        }
        int questionSubjectCount = questionSubjectMapper.insertQuestionSubjectList(questionSubjects);
        if (questionSubjectCount <= 0) {
            log.info("新增问卷题目表失败," + questionSubjects);
            throw new SecurityException("新增问卷失败!请联系管理员！");
        }
        if (CollectionUtils.isEmpty(questionSubjectOptions)) {
            return AjaxResult.success();
        }
        //新增选项表
        List<QuestionSubjectOption> saveQuestionSubjectOptions = new ArrayList<>();
        for (QuestionSubjectOptionVO questionSubjectOption : questionSubjectOptions) {
            QuestionSubjectOption saveQuestionSubjectOption = new QuestionSubjectOption();
            BeanUtils.copyBeanProp(saveQuestionSubjectOption, questionSubjectOption);
            QuestionSubject questionSubject = questionSubjects.stream().filter(Objects::nonNull).filter(item -> Objects.nonNull(item.getQuestionNumber()) && questionSubjectOption.getQuestionNumber().compareTo(item.getQuestionNumber()) == 0).findFirst().orElse(new QuestionSubject());
            if (StringUtils.isBlank(questionSubjectOption.getContentedFlag())){
                saveQuestionSubjectOption.setContentedFlag(ContentedAndRemarkableFlagEnum.CONTENTED.getInfo());
            }
            if (StringUtils.isBlank(questionSubjectOption.getRemarkableFlag())){
                saveQuestionSubjectOption.setRemarkableFlag(ContentedAndRemarkableFlagEnum.ROUTINE.getInfo());
            }
            saveQuestionSubjectOption.setQuestionnaireSubjectId(questionSubject.getId());
            saveQuestionSubjectOption.setCreateTime(LocalDateTime.now());
            saveQuestionSubjectOption.setCreateBy(SecurityUtils.getUsername());
            saveQuestionSubjectOptions.add(saveQuestionSubjectOption);
        }
        int subjectOptionCount = questionSubjectOptionMapper.insertQuestionSubjectOptionList(saveQuestionSubjectOptions);
        if (subjectOptionCount <= 0) {
            log.info("新增问卷答案表失败," + questionSubjects);
            throw new SecurityException("新增问卷失败!请联系管理员！");
        }
        return AjaxResult.success();
    }

    /**
     * 修改问卷基本信息
     *
     * @param question 问卷基本信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updateQuestionInfo(QuestionVO question) {
        //新增问卷表
        QuestionInfo questionInfo = new QuestionInfo();
        BeanUtils.copyBeanProp(questionInfo, question);
        //修改取消发布
        questionInfo.setQuestionnaireStatus(QuestionnaireStatusEnum.UNPUBLISHED.getInfo());
        questionInfo.setUpdateTime(LocalDateTime.now());
        questionInfo.setUpdateBy(SecurityUtils.getUsername());
        int questionCount = questionInfoMapper.updateQuestionInfo(questionInfo);
        if (questionCount <= 0) {
            log.info("修改问卷表失败," + questionInfo);
            throw new SecurityException("修改问卷失败!请联系管理员！");
        }
        //查询题目及选项表id 根据上级id删除
        List<QuestionSubjectVO> originalSubjectList = questionSubjectMapper.selectQuestionSubjectBy(question.getId());
        if (CollectionUtils.isNotEmpty(originalSubjectList)) {
            List<Long> originalSubjectIds = originalSubjectList.stream().filter(Objects::nonNull).filter(item -> Objects.nonNull(item.getId())).map(QuestionSubject::getId).collect(Collectors.toList());
            int deleteQuestionCount = questionSubjectMapper.deleteSubjectByQuestionInfoId(question.getId());
            if (deleteQuestionCount < 0) {
                log.info("删除问卷题目表失败");
                throw new SecurityException("修改问卷失败!请联系管理员！");
            }
            int deleteOptionIds = questionSubjectOptionMapper.deleteOptionByQuestionSubjectIds(originalSubjectIds);
            if (deleteOptionIds < 0) {
                log.info("删除问卷选项表失败");
                throw new SecurityException("修改问卷失败!请联系管理员！");
            }
        }
        //新增问卷表及题目表
        List<QuestionSubjectVO> questionSubjectList = question.getQuestionSubjectList();
        List<QuestionSubject> questionSubjects = new ArrayList<>();
        List<QuestionSubjectOptionVO> questionSubjectOptions = new ArrayList<>();
        for (QuestionSubjectVO questionSubject : questionSubjectList) {
            if (StringUtils.isBlank(questionSubject.getQuestionName())) {
                throw new SecurityException("请添加完整问卷题目！");
            }
            QuestionSubject saveQuestionSubject = new QuestionSubject();
            BeanUtils.copyBeanProp(saveQuestionSubject, questionSubject);
            saveQuestionSubject.setQuestionInfoId(questionInfo.getId());
            saveQuestionSubject.setCreateTime(LocalDateTime.now());
            saveQuestionSubject.setCreateBy(SecurityUtils.getUsername());
            questionSubjects.add(saveQuestionSubject);
            if (CollectionUtils.isNotEmpty(questionSubject.getQuestionSubjectOptionList())) {
                questionSubjectOptions.addAll(questionSubject.getQuestionSubjectOptionList());
            }
        }
        int questionSubjectCount = questionSubjectMapper.insertQuestionSubjectList(questionSubjects);
        if (questionSubjectCount <= 0) {
            log.info("修改问卷题目表失败," + questionSubjects);
            throw new SecurityException("修改问卷失败!请联系管理员！");
        }
        if (CollectionUtils.isEmpty(questionSubjectOptions)) {
            return AjaxResult.success();
        }
        List<QuestionSubjectOption> saveQuestionSubjectOptions = new ArrayList<>();
        for (QuestionSubjectOptionVO questionSubjectOption : questionSubjectOptions) {
            QuestionSubjectOption saveQuestionSubjectOption = new QuestionSubjectOption();
            BeanUtils.copyBeanProp(saveQuestionSubjectOption, questionSubjectOption);
            QuestionSubject questionSubject = questionSubjects.stream().filter(Objects::nonNull).filter(item -> Objects.nonNull(item.getQuestionNumber()) && questionSubjectOption.getQuestionNumber().compareTo(item.getQuestionNumber()) == 0).findFirst().orElse(new QuestionSubject());
            saveQuestionSubjectOption.setQuestionnaireSubjectId(questionSubject.getId());
            saveQuestionSubjectOption.setCreateTime(LocalDateTime.now());
            saveQuestionSubjectOption.setCreateBy(SecurityUtils.getUsername());
            saveQuestionSubjectOptions.add(saveQuestionSubjectOption);
        }
        int subjectOptionCount = questionSubjectOptionMapper.insertQuestionSubjectOptionList(saveQuestionSubjectOptions);
        if (subjectOptionCount <= 0) {
            log.info("修改问卷答案表失败," + questionSubjects);
            throw new SecurityException("修改问卷失败!请联系管理员！");
        }
        return AjaxResult.success();
    }

    /**
     * 批量删除问卷基本信息
     *
     * @param ids 需要删除的问卷基本信息主键
     * @return 结果
     */
    @Override
    public int deleteQuestionInfoByIds(Long[] ids) {
        return questionInfoMapper.deleteQuestionInfoByIds(ids);
    }

    /**
     * 删除问卷基本信息信息
     *
     * @param id 问卷基本信息主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteQuestionInfoById(Long id) {
        List<QuestionSubjectVO> originalSubjectList = questionSubjectMapper.selectQuestionSubjectBy(id);
        if (CollectionUtils.isNotEmpty(originalSubjectList)) {
            List<Long> originalSubjectIds = originalSubjectList.stream().filter(Objects::nonNull).filter(item -> Objects.nonNull(item.getId())).map(QuestionSubject::getId).collect(Collectors.toList());
            int deleteQuestionCount = questionSubjectMapper.deleteSubjectByQuestionInfoId(id);
            if (deleteQuestionCount < 0) {
                log.info("删除问卷题目表失败");
                throw new SecurityException("删除问卷失败!请联系管理员！");
            }
            int deleteOptionIds = questionSubjectOptionMapper.deleteOptionByQuestionSubjectIds(originalSubjectIds);
            if (deleteOptionIds < 0) {
                log.info("删除问卷选项表失败");
                throw new SecurityException("删除问卷失败!请联系管理员！");
            }
        }
        return questionInfoMapper.deleteQuestionInfoById(id);
    }

    /**
     * 修改问卷基本信息
     *
     * @param questionInfo 问卷基本信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updateQuestionByDepartment(QuestionInfo questionInfo) {
        if (Objects.isNull(questionInfo) || Objects.isNull(questionInfo.getId())) {
            return AjaxResult.success();
        }
        if (Objects.nonNull(questionInfo.getQuestionnaireStatus()) && "PUBLISHED".equals(questionInfo.getQuestionnaireStatus())) {
            QuestionInfo dataBaseQuestion = questionInfoMapper.selectQuestionInfoById(questionInfo.getId());
            if (Objects.nonNull(dataBaseQuestion) && Objects.nonNull(dataBaseQuestion.getDepartmentId()) && Objects.nonNull(dataBaseQuestion.getDiseaseTypeId())) {
                int questionCount = questionInfoMapper.updateQuestionInfo(questionInfo);
                if (questionCount <= 0) {
                    return AjaxResult.error("修改问卷失败!请联系管理员！");
                }
            } else {
                return AjaxResult.error("请选择问卷所属的科室以及科室病种后发布！");
            }
        }
        if (Objects.nonNull(questionInfo.getQuestionnaireStatus()) && "UNPUBLISHED".equals(questionInfo.getQuestionnaireStatus())) {
            int questionCount = questionInfoMapper.updateQuestionInfo(questionInfo);
            if (questionCount <= 0) {
                return AjaxResult.error("修改问卷失败!请联系管理员！");
            }
        }
        if (Objects.isNull(questionInfo.getDepartmentId()) && Objects.isNull(questionInfo.getDiseaseTypeId())) {
            return AjaxResult.success();
        }
        int questionCount = questionInfoMapper.updateQuestionInfo(questionInfo);
        if (questionCount <= 0) {
            return AjaxResult.success("修改问卷失败!请联系管理员！");
        }
        return AjaxResult.success(questionCount);
    }

    /**
     * 科室问卷数量
     *
     * @param departmentCount 科室名称
     * @return AjaxResult
     */
    @DataScope(agencyAlias = "dt", deptAlias = "qi")
    @Override
    public DepartmentBaseVo departmentQuestionCount(DepartmentCount departmentCount) {
        DepartmentVO departmentVO = new DepartmentVO();
        List<DepartmentVO> department = new ArrayList<>();
        departmentVO.setDepartmentName("全部");
        departmentVO.setCountNum(0);
        List<DepartmentVO> departmentVOS = questionInfoMapper.departmentQuestionByDepartmentName(departmentCount);
        if (CollectionUtils.isNotEmpty(departmentVOS)) {
            Integer result = departmentVOS.stream().mapToInt(DepartmentVO::getCountNum).sum();
            if (StringUtils.isBlank(departmentCount.getQuestionnaireStatus())) {
                result = departmentVOS.get(0).getTotalNumber();
            }
            departmentVO.setCountNum(result);
            department.add(departmentVO);
            department.addAll(departmentVOS);
        } else {
            department.add(departmentVO);
        }
	    Agency agency = agencyMapper.selectAgencyById(departmentCount.getHospitalAgencyId());
	    return DepartmentBaseVo.builder().hospitalAgencyName(ObjectUtils.isEmpty(agency) ? "" : agency.getAgencyName())
		    .deptNumList(departmentVOS).build();
    }
}
