package com.hxhq.business.service.impl;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
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.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hxhq.business.domain.Bacteria;
import com.hxhq.business.domain.Study;
import com.hxhq.business.domain.StudyMethodRead;
import com.hxhq.business.dto.select.DeptUserTreeDto;
import com.hxhq.business.enums.NormalEnum;
import com.hxhq.business.enums.study.StudyMethodStatusEnum;
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.StudyMethodForm;
import com.hxhq.business.form.study.StudyMethodReadForm;
import com.hxhq.business.form.study.StudyMethodSearchForm;
import com.hxhq.business.service.*;
import com.hxhq.business.utils.JctUtil;
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.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;
    @Autowired
    private ISystemLogService systemLogService;

    @Autowired
    private IStudyMethodJcgjService studyMethodJcgjService;

    /**
     * 查询试验-试验方法列表
     *
     * @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()) {
            if(form.getStudySubjectId() != null) {
                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()));
            } else if(form.getStudyId() != null){
                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_id = {1}))"
                        , SecurityUtils.getUserId(), form.getStudyId()));
            } else {
                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}))"
                        , SecurityUtils.getUserId()));
            }

        }
        // 未读
        if(form.getZt() != null && form.getZt() == StudyMethodStatusEnum.wd.getValue()) {
            if(form.getStudySubjectId() != null) {
                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()));
            } else if(form.getStudyId() != null){
                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_id = {1}))"
                        , SecurityUtils.getUserId(), form.getStudyId()));
            } else {
                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}))"
                        , SecurityUtils.getUserId()));
            }
        }
        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());
        studyMethod.setStatus(NormalEnum.yes.getValue());
        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());

        //稽查轨迹
        Map<String, String> formData = new LinkedHashMap<>();
        formData.put("备注", form.getRemark());

        Map<String, String> formDataEn = new LinkedHashMap<>();
        formDataEn.put("Comment", form.getRemark());
        studyMethodJcgjService.saveJcgj(studyMethod, JcgjlxEnum.lc.getValue(), "上传方法", "Upload Method", JcmcysEnum.blue.getValue(),
                JctUtil.formatStr(formData), JctUtil.formatStr(formDataEn), qmr);

    }

    @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);

        //稽查轨迹
        Map<String, String> formData = new LinkedHashMap<>();
        formData.put("备注", form.getRemark());

        Map<String, String> formDataEn = new LinkedHashMap<>();
        formDataEn.put("Comment", form.getRemark());
        studyMethodJcgjService.saveJcgj(studyMethod, JcgjlxEnum.lc.getValue(), "阅读方法", "Read Method", JcmcysEnum.blue.getValue(),
                JctUtil.formatStr(formData), JctUtil.formatStr(formDataEn), qmr);
    }

    @Override
    public HashMap<String,Object> checkAllMethodReadStatus(Long userId, Long studyId, Long studySubjectId) {
        HashMap<String,Object> result=new HashMap<>(16);
        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(String.valueOf(userId)) && !study.getLeader().equals(userId)){
            //排除sd

            QueryWrapper<StudyMethod> queryWrapper = Wrappers.query();
            queryWrapper.eq("del_flag", 0)
                    .eq("status", NormalEnum.yes.getValue())
                    .eq("study_id", studyId);
            if(studySubjectId != null) {
                queryWrapper.eq("study_subject_id", studySubjectId);
                queryWrapper.and(p -> p.apply("(id NOT IN (SELECT study_method_id FROM t_study_method_read WHERE del_flag = 0 AND qmr_id = {0} AND study_id = {1} AND study_subject_id = {2}))"
                        , SecurityUtils.getUserId(), studyId, studySubjectId));
            } else {
                queryWrapper.and(p -> p.apply("(id NOT IN (SELECT study_method_id FROM t_study_method_read WHERE del_flag = 0 AND qmr_id = {0} AND study_id = {1}))"
                        , SecurityUtils.getUserId(), studyId));
            }

            List<StudyMethod> list = baseMapper.queryUnreadList(queryWrapper);

            if(list.size() > 0) {
                // 获取未读方法

                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;
    }

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

        StudyMethod studyMethod = getById(form.getId());
        if(studyMethod == null || !studyMethod.getUserId().equals(form.getQmrId())) {
            throw new ServiceException("对象不存在");
        }
        studyMethod.setStatus(NormalEnum.no.getValue());
        updateById(studyMethod);

        //稽查轨迹
        Map<String, String> formData = new LinkedHashMap<>();
        formData.put("备注", form.getRemark());

        Map<String, String> formDataEn = new LinkedHashMap<>();
        formDataEn.put("Comment", form.getRemark());
        studyMethodJcgjService.saveJcgj(studyMethod, JcgjlxEnum.lc.getValue(), "关闭方法", "Close Method", JcmcysEnum.blue.getValue(),
                JctUtil.formatStr(formData), JctUtil.formatStr(formDataEn), qmr);
    }

}
