package com.hxhq.business.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hxhq.business.domain.Study;
import com.hxhq.business.domain.StudyMethodRead;
import com.hxhq.business.dto.select.DeptUserTreeDto;
import com.hxhq.business.enums.study.StudyMethodStatusEnum;
import com.hxhq.business.enums.study.StudyTypeEnum;
import com.hxhq.business.form.study.StudyMethodForm;
import com.hxhq.business.form.study.StudyMethodReadForm;
import com.hxhq.business.form.study.StudyMethodSearchForm;
import com.hxhq.business.service.INoticeService;
import com.hxhq.business.service.IStudyMethodReadService;
import com.hxhq.business.service.IStudyService;
import com.hxhq.common.core.exception.ServiceException;
import com.hxhq.common.core.web.domain.AjaxResult;
import com.hxhq.common.security.utils.SecurityUtils;
import com.hxhq.system.api.domain.SysUser;
import com.hxhq.system.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hxhq.business.mapper.StudyMethodMapper;
import com.hxhq.business.domain.StudyMethod;
import com.hxhq.business.service.IStudyMethodService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 试验-试验方法Service业务层处理
 *
 * @author hxhq
 * @date 2025-12-29
 */
@Service
public class StudyMethodServiceImpl extends ServiceImpl<StudyMethodMapper, StudyMethod> implements IStudyMethodService
{

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IStudyMethodReadService studyMethodReadService;
    @Autowired
    private INoticeService noticeService;
    @Autowired
    private IStudyService studyService;

    /**
     * 查询试验-试验方法列表
     *
     * @param form 试验-试验方法
     * @return 试验-试验方法
     */
    @Override
    public List<StudyMethod> queryList(StudyMethodSearchForm form) {
        QueryWrapper<StudyMethod> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("m.del_flag", 0);
        if(form.getStudyId() != null) {
            queryWrapper.eq("m.study_id", form.getStudyId());
        }
        if(form.getStudySubjectId() != null) {
            queryWrapper.eq("m.study_subject_id", form.getStudySubjectId());
        }
        if(StringUtils.isNotEmpty(form.getFfmc())) {
            queryWrapper.like("m.ffmc", form.getFfmc());
        }
        if(StringUtils.isNotEmpty(form.getCreateUser())) {
            queryWrapper.like("m.user_mc", form.getCreateUser());
        }
        if(StringUtils.isNotEmpty(form.getStartDate())) {
            queryWrapper.ge("m.create_time", form.getStartDate());
        }
        if(StringUtils.isNotEmpty(form.getEndDate())) {
            queryWrapper.le("m.create_time", form.getEndDate());
        }
        // 已读
        if(form.getZt() != null && form.getZt() == StudyMethodStatusEnum.yd.getValue()) {
            queryWrapper.and(p -> p.apply("(m.id IN (SELECT study_method_id FROM t_study_method_read WHERE del_flag = 0 AND qmr_id = {0} AND study_subject_id = {1}))"
                    , SecurityUtils.getUserId(), form.getStudySubjectId()));
        }
        // 未读
        if(form.getZt() != null && form.getZt() == StudyMethodStatusEnum.wd.getValue()) {
            queryWrapper.and(p -> p.apply("(m.id NOT IN (SELECT study_method_id FROM t_study_method_read WHERE del_flag = 0 AND qmr_id = {0} AND study_subject_id = {1}))"
                    , SecurityUtils.getUserId(), form.getStudySubjectId()));
        }
        queryWrapper.orderByDesc("m.create_time");
        return baseMapper.queryList(queryWrapper, SecurityUtils.getUserId());
    }

    @Override
    public void save(StudyMethodForm form) {
        SysUser qmr = sysUserService.selectUserById(form.getQmrId());
        sysUserService.checkPassword(qmr, form.getQmrmm(), false);
        StudyMethod studyMethod = new StudyMethod();
        BeanUtils.copyProperties(form, studyMethod);
        studyMethod.setUserId(qmr.getUserId());
        studyMethod.setUserMc(qmr.getNickName());
        this.save(studyMethod);

        StudyMethodRead studyMethodRead = new StudyMethodRead();
        studyMethodRead.setStudyId(studyMethod.getStudyId());
        studyMethodRead.setStudySubjectId(studyMethod.getStudySubjectId());
        studyMethodRead.setStudyMethodId(studyMethod.getId());
        studyMethodRead.setQmrId(qmr.getUserId());
        studyMethodRead.setQmrMc(qmr.getNickName());
        studyMethodRead.setRemark(form.getRemark());
        studyMethodRead.setQmyy("阅读");
        studyMethodReadService.save(studyMethodRead);

        //发送消息通知
        noticeService.saveStudyMethod(studyMethod.getStudyId(),studyMethod.getStudySubjectId(),studyMethod.getUserId());
    }

    @Override
    public void read(StudyMethodReadForm form) {
        SysUser qmr = sysUserService.selectUserById(form.getQmrId());
        sysUserService.checkPassword(qmr, form.getQmrmm(), false);


        StudyMethod studyMethod = this.getById(form.getStudyMethodId());
        if(studyMethod == null) {
            throw new ServiceException("试验方法不存在或已被删除");
        }

        LambdaQueryWrapper<StudyMethodRead> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StudyMethodRead::getStudyMethodId, form.getStudyMethodId())
                .eq(StudyMethodRead::getQmrId, form.getQmrId());
        long count = studyMethodReadService.count(queryWrapper);
        if(count > 0) {
            return;
        }
        StudyMethodRead studyMethodRead = new StudyMethodRead();
        studyMethodRead.setQmyy("阅读");
        studyMethodRead.setQmrMc(qmr.getNickName());
        studyMethodRead.setQmrId(qmr.getUserId());
        studyMethodRead.setRemark(form.getRemark());
        studyMethodRead.setStudyId(studyMethod.getStudyId());
        studyMethodRead.setStudySubjectId(studyMethod.getStudySubjectId());
        studyMethodRead.setStudyMethodId(studyMethod.getId());
        studyMethodReadService.save(studyMethodRead);
    }

    @Override
    public HashMap<String,Object> checkAllMethodReadStatus(Long userId, Long studyId, Long studySubjectId) {
        HashMap<String,Object> result=new HashMap<>();
        Study study = studyService.getById(studyId);
        if(study==null){
            throw new ServiceException("信息不存在");
        }
        //试验学科内部的人+非试验部门内的人
        List<DeptUserTreeDto> depts = sysUserService.selectStudyUser(study.getType().equals(StudyTypeEnum.sy.getValue())?studyId:null,study.getType().equals(StudyTypeEnum.sy.getValue())?studySubjectId:null,study.getType().equals(StudyTypeEnum.fsy.getValue())?study.getDeptId():null,null);
        if(depts.stream().map(o->o.getId()).collect(Collectors.toList()).contains(userId) && !study.getLeader().equals(userId)){
            //排除sd

            LambdaQueryWrapper<StudyMethodRead> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(StudyMethodRead::getQmrId, userId)
                    .eq(StudyMethodRead::getStudyId, studyId);
            if(studySubjectId != null) {
                queryWrapper.eq(StudyMethodRead::getStudySubjectId, studySubjectId);
            }
            long readCount = studyMethodReadService.count(queryWrapper);

            LambdaQueryWrapper<StudyMethod> studyMethodLambdaQueryWrapper = new LambdaQueryWrapper<>();
            studyMethodLambdaQueryWrapper.eq(StudyMethod::getStudyId, studyId);
            if(studySubjectId != null) {
                studyMethodLambdaQueryWrapper.eq(StudyMethod::getStudySubjectId, studySubjectId);
            }
            List<StudyMethod> list = this.list(studyMethodLambdaQueryWrapper);
            if(readCount != list.size()) {
                String toUrl=study.getType().equals(StudyTypeEnum.sy.getValue())?("/study/enter/"+study.getId()+"/syff"):study.getType().equals(StudyTypeEnum.fsy.getValue())?("/nonTrial/enter/"+study.getId()+"/syff"):study.getType().equals(StudyTypeEnum.mjy.getValue())?("/drug/enter/"+study.getId()+"/syff"):"";
                result.put("toUrl",toUrl);
                result.put("ffmc","【" + list.stream().map(StudyMethod::getFfmc).collect(Collectors.joining(",")) + "】方法还未阅读，请先阅读后再进行操作]");
            }
        }
        return result;
    }

}
