package com.hxhq.business.service.impl;

import java.util.*;
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.MjyJcgj;
import com.hxhq.business.domain.StudyJcgj;
import com.hxhq.business.dto.home.HomeCountDto;
import com.hxhq.business.dto.study.StudyListDto;
import com.hxhq.business.enums.archive.ArchiveLogTypeEnum;
import com.hxhq.business.enums.study.StudyBorrowStatusEnum;
import com.hxhq.business.enums.study.StudyStatusEnum;
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.StudySaveForm;
import com.hxhq.business.form.study.StudySearchForm;
import com.hxhq.business.service.IArchiveLogService;
import com.hxhq.business.service.INoticeService;
import com.hxhq.business.service.IStudyJcgjService;
import com.hxhq.business.utils.JctUtil;
import com.hxhq.business.utils.ObjectCompareUtil;
import com.hxhq.common.core.exception.ServiceException;
import com.hxhq.common.core.utils.DateUtils;
import com.hxhq.common.core.utils.PageUtils;
import com.hxhq.common.core.utils.StringUtils;
import com.hxhq.common.core.web.domain.AjaxResult;
import com.hxhq.common.security.auth.AuthUtil;
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.StudyMapper;
import com.hxhq.business.domain.Study;
import com.hxhq.business.service.IStudyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 试验Service业务层处理
 *
 * @author hxhq
 * @date 2025-12-24
 */
@Service
public class StudyServiceImpl extends ServiceImpl<StudyMapper, Study> implements IStudyService
{
    @Autowired
    private IStudyJcgjService studyJcgjService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private INoticeService noticeService;
    @Autowired
    private IArchiveLogService archiveLogService;

    private QueryWrapper<StudyListDto> getListBaseQuery(StudySearchForm form){
        QueryWrapper<StudyListDto> queryWrapper = new QueryWrapper();
        queryWrapper.eq("s.del_flag","0");
        if(form.getType()!=null && form.getType().intValue()>0){
            queryWrapper.eq("s.type",form.getType());
        }
        if(StringUtils.isNoneBlank(form.getName())){
            queryWrapper.like("s.name",form.getName());
        }
        if(StringUtils.isNoneBlank(form.getSn())){
            queryWrapper.like("s.sn",form.getSn());
        }
        if(StringUtils.isNoneBlank(form.getLeaderName())){
            queryWrapper.like("u.nick_name",form.getLeaderName());
        }
        if (StringUtils.isNoneBlank(form.getStartDate())) {
            queryWrapper.ge("s.create_time", form.getStartDate());
        }
        if (StringUtils.isNoneBlank(form.getEndDate())) {
            queryWrapper.lt("s.create_time", DateUtils.dateTime(DateUtils.addDays(DateUtils.parseDate(form.getEndDate()),1)));
        }
        if(form.getStatus()!=null && form.getStatus().intValue()>0){
            queryWrapper.eq("s.status",form.getStatus());
        }
        return queryWrapper;
    }

    /**
     * 查询试验列表
     *
     * @param form 试验
     * @return 试验
     */
    @Override
    public List<StudyListDto> queryList(StudySearchForm form)
    {
        QueryWrapper<StudyListDto> queryWrapper = getListBaseQuery(form);
        //试验管理
        //TFM看所有试验，其他只能看自己进入的试验
        String tmfRole = "TFM";
        if (!AuthUtil.hasRole(tmfRole))
        {
            queryWrapper.apply("(\n" +
                    "s.id IN (\n" +
                    "SELECT study_id FROM t_study_subject WHERE del_flag='0' AND leader={0}\n" +
                    ")\n" +
                    "OR \n" +
                    "s.id IN (\n" +
                    "SELECT study_id FROM `t_study_subject_user` WHERE del_flag='0' AND user_id={0}\n" +
                    ")\n" +
                    "OR s.leader={0}\n" +
                    ")",SecurityUtils.getUserId());
        }

        queryWrapper.orderByDesc("s.id");
        return baseMapper.queryList(queryWrapper);
    }

    @Override
    public List<StudyListDto> queryNonList(StudySearchForm form) {
        QueryWrapper<StudyListDto> queryWrapper = getListBaseQuery(form);
        // 非试验管理：
        // 特殊部门QA可以看所有列表+审核表单
        // 特殊角色：可以看部门级下级部门的所有非试验，操作非试验（锁定、解锁...），可以审核表单
        // 其他只能看所在部门级下级部门的所有非试验

        // 总结：有这个菜单，特殊部QA可以看所有+审核表单，其他只能看部门级下级部门的列表（部长可以操作+审核表单）
        Long deptId = sysUserService.selectUserById(SecurityUtils.getLoginUser().getUserid()).getDeptId();
        Long qaDeptId = 216L;
        if (!deptId.equals(qaDeptId))
        {
            queryWrapper.apply("(\n" +
                    "s.dept_id IN(\n" +
                    "SELECT dept_id FROM sys_dept WHERE del_flag = '0' AND FIND_IN_SET({0}, ancestors) \n" +
                    ")\n" +
                    "OR s.dept_id={0}\n" +
                    ")",deptId);
        }

        queryWrapper.orderByDesc("s.id");
        PageUtils.startPage();
        return baseMapper.queryList(queryWrapper);
    }

    @Override
    public List<StudyListDto> queryDrugList(StudySearchForm form) {
        QueryWrapper<StudyListDto> queryWrapper = getListBaseQuery(form);

        // 麻精药管理：
        // 特殊部门QA可以看所有列表+审核表单
        // 特殊角色：麻精药,角色下所有人都能看所有麻精药表单列表
        // （是部长角色的话能看所有麻精药列表+操作+可以审核表单）

        // 总结：只要有这个菜单就能看所有列表，特殊部门QA可以审核表单，部长角色的话能操作+可以审核表单
        queryWrapper.orderByDesc("s.id");
        return baseMapper.queryList(queryWrapper);
    }

    @Override
    public List<StudyListDto> queryFormCountList(List<Long> idList) {
        if(idList==null || idList.size()<1){
            return new ArrayList<>();
        }
        return baseMapper.queryFormCountList(idList);
    }

    @Override
    public List<StudyListDto> initFormCount(List<StudyListDto> list) {
        if(list.size()>0){
            List<StudyListDto> countList = queryFormCountList(list.stream().map(o->o.getId()).collect(Collectors.toList()));
            for(StudyListDto l : list){
                List<StudyListDto> matchList = countList.stream().filter(o->o.getId().equals(l.getId())).collect(Collectors.toList());
                if(matchList.size()>0){
                    l.setFormCount(matchList.get(0).getFormCount());
                    l.setFormFinishCount(matchList.get(0).getFormFinishCount());
                }else{
                    l.setFormCount(0);
                    l.setFormFinishCount(0);
                }

            }
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveInfo(StudySaveForm form) {
        Study study = form.getStudy();
        SignForm sign = form.getSign();
        //判断编号重复
        QueryWrapper<Study> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sn",study.getSn());
        if(study.getId()!=null){
            queryWrapper.ne("id",study.getId());
        }
        if(count(queryWrapper)>0){
            throw new ServiceException("编号已存在");
        }
        if(study.getId()==null){
            //新增
            save(study);
            if(study.getStatus().equals(StudyStatusEnum.cg.getValue())){
                Map<String, String> formData = new LinkedHashMap<>();
                Map<String, String> formDataEn = new LinkedHashMap<>();
                formData.put("暂存人", SecurityUtils.getNickName());
                formDataEn.put("Save User", SecurityUtils.getUsername());
                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())?"Save":study.getType().equals(StudyTypeEnum.fsy.getValue())?"Save":study.getType().equals(StudyTypeEnum.mjy.getValue())?"Save":"");
                studyJcgjService.saveInfo(study.getId(), JcgjlxEnum.lc, JcmcysEnum.blue,JctUtil.formatStr(formData),JctUtil.formatStr(formDataEn),sign);
            }else{
                checkPassword(sign);
                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())?"Create Study":study.getType().equals(StudyTypeEnum.fsy.getValue())?"Create":study.getType().equals(StudyTypeEnum.mjy.getValue())?"Create":"");
                studyJcgjService.saveInfo(study.getId(), JcgjlxEnum.lc, JcmcysEnum.blue,null,null,sign);
            }
        }else{
            //修改
            Study old = getById(study.getId());
            if(!old.getStatus().equals(StudyStatusEnum.cg.getValue()) && study.getStatus().equals(StudyStatusEnum.cg.getValue())){
                throw new ServiceException("当前状态不允许暂存");
            }
            if(!old.getStatus().equals(StudyStatusEnum.cg.getValue()) && !old.getStatus().equals(StudyStatusEnum.syz.getValue())){
                throw new ServiceException("当前状态不允许修改");
            }

            checkPermit(old);
            //获取修改的稽查轨迹
            List<StudyJcgj> jcgjList = getChangeJcgj(old,study,sign);
            studyJcgjService.saveBatch(jcgjList);

            if(!old.getLeaderName().equals(study.getLeaderName())){
                Map<String, String> formData = new LinkedHashMap<>();
                Map<String, String> formDataEn = new LinkedHashMap<>();
                formData.put("新增人员", study.getLeaderName());
                formDataEn.put("Add Person", study.getLeaderNameEn());
                formData.put("删除人员", old.getLeaderName());
                formDataEn.put("Remove Person", old.getLeaderNameEn());
                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":"");
                if(study.getStatus().equals(StudyStatusEnum.cg.getValue())){
                    studyJcgjService.saveInfo(study.getId(), JcgjlxEnum.ry, JcmcysEnum.blue,JctUtil.formatStr(formData), JctUtil.formatStr(formDataEn), sign);
                }else{
                    studyJcgjService.saveInfo(study.getId(), JcgjlxEnum.ry, JcmcysEnum.blue,JctUtil.formatStr(formData),JctUtil.formatStr(formDataEn), sign);
                }
            }
            if(study.getStatus().equals(StudyStatusEnum.cg.getValue())){
                Map<String, String> formData = new LinkedHashMap<>();
                Map<String, String> formDataEn = new LinkedHashMap<>();
                formData.put("暂存人", SecurityUtils.getNickName());
                formDataEn.put("Save User", SecurityUtils.getUsername());
                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())?"Save":study.getType().equals(StudyTypeEnum.fsy.getValue())?"Save":study.getType().equals(StudyTypeEnum.mjy.getValue())?"Save":"");
                studyJcgjService.saveInfo(study.getId(), JcgjlxEnum.lc, JcmcysEnum.blue,JctUtil.formatStr(formDataEn),JctUtil.formatStr(formDataEn),sign);
            }else {
                checkPassword(sign);
                if(old.getStatus().equals(StudyStatusEnum.cg.getValue())){
                    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())?"Create Study":study.getType().equals(StudyTypeEnum.fsy.getValue())?"Create":study.getType().equals(StudyTypeEnum.mjy.getValue())?"Create":"");
                    studyJcgjService.saveInfo(study.getId(), JcgjlxEnum.lc, JcmcysEnum.blue,null,null,sign);
                }
            }
            updateById(study);
        }
    }

    /**
     * 获取修改的稽查轨迹
     * @param old
     * @param study
     * @param sign
     * @return
     */
    private List<StudyJcgj> getChangeJcgj(Study old,Study study,SignForm sign){
        List<StudyJcgj> jcgjList = new ArrayList<>();
        List<ObjectCompareUtil.FieldChange> fieldChanges = ObjectCompareUtil.compareObjects(old, study);
        if (fieldChanges.size() > 0) {
            for (ObjectCompareUtil.FieldChange fieldChange : fieldChanges) {
                StudyJcgj jcgj = new StudyJcgj();
                jcgj.setStudyId(study.getId());
                jcgj.setJcgjlx(JcgjlxEnum.bj.getValue());
                jcgj.setJcmc("修改试验");
                jcgj.setJcmcEn("Change of Information");
                jcgj.setJcmcys(JcmcysEnum.orange.getValue());
                jcgj.setJcnr(fieldChange.toString());
                jcgj.setJcnrEn(fieldChange.toEnString());
                if(study.getStatus().equals(StudyStatusEnum.syz.getValue())){
                    jcgj.setQmrId(SecurityUtils.getUserId());
                    jcgj.setQmrMc(SecurityUtils.getNickName());
                    jcgj.setQmrMcEn(SecurityUtils.getUsername());
                    jcgj.setRemark(sign.getRemark());
                }
                jcgjList.add(jcgj);
            }
        }
        return jcgjList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void del(StudySaveForm form) {
        Study study = form.getStudy();
        SignForm sign = form.getSign();

        Study info = getById(study.getId());
        if(info==null){
            throw new ServiceException("信息不存在");
        }
        if(!info.getStatus().equals(StudyStatusEnum.cg.getValue())){
            throw new ServiceException("当前状态不能删除");
        }
        checkPermit(info);
        checkPassword(sign);
        sign.setQmyy(info.getType().equals(StudyTypeEnum.sy.getValue())?"删除试验":info.getType().equals(StudyTypeEnum.fsy.getValue())?"删除非试验":info.getType().equals(StudyTypeEnum.mjy.getValue())?"删除麻精药文件夹":"");
        sign.setQmyyEn(info.getType().equals(StudyTypeEnum.sy.getValue())?"Remove Study":info.getType().equals(StudyTypeEnum.fsy.getValue())?"Remove":info.getType().equals(StudyTypeEnum.mjy.getValue())?"Remove":"");
        studyJcgjService.saveInfo(study.getId(), JcgjlxEnum.lc, JcmcysEnum.red,null,null,sign);
        removeById(study.getId());
    }

    @Override
    public void checkSd(Study study) {
        if(study==null){
            throw new ServiceException("信息不存在");
        }
        if(study.getStatus().equals(StudyStatusEnum.ysd.getValue())){
            throw new ServiceException("该试验已锁定");
        }
        checkPermit(study);
        String name = baseMapper.queryNotFinishFormName(study.getId());
        if(StringUtils.isNoneBlank(name)){
            throw new ServiceException("该实验下"+name+"还未结束，请先完成该表单后再进行锁定试验");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sd(StudySaveForm form) {
        Study info = getById(form.getStudy().getId());
        checkSd(info);
        SignForm sign = form.getSign();
        checkPassword(sign);
        info.setStatus(StudyStatusEnum.ysd.getValue());
        updateById(info);
        sign.setQmyy(info.getType().equals(StudyTypeEnum.sy.getValue())?"锁定试验":info.getType().equals(StudyTypeEnum.fsy.getValue())?"锁定非试验":info.getType().equals(StudyTypeEnum.mjy.getValue())?"锁定麻精药文件夹":"");
        sign.setQmyyEn(info.getType().equals(StudyTypeEnum.sy.getValue())?"Lock Study":info.getType().equals(StudyTypeEnum.fsy.getValue())?"Lock Record":info.getType().equals(StudyTypeEnum.mjy.getValue())?"Lock Record":"");
        studyJcgjService.saveInfo(info.getId(), JcgjlxEnum.lc, JcmcysEnum.blue,null,null,sign);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void js(StudySaveForm form) {
        Study study = form.getStudy();
        SignForm sign = form.getSign();

        Study info = getById(study.getId());
        if(info==null){
            throw new ServiceException("信息不存在");
        }
        if(!info.getStatus().equals(StudyStatusEnum.ysd.getValue())){
            throw new ServiceException("当前状态不能解锁");
        }
        checkPermit(info);
        checkPassword(sign);
        info.setStatus(StudyStatusEnum.syz.getValue());
        updateById(info);
        sign.setQmyy(info.getType().equals(StudyTypeEnum.sy.getValue())?"解锁试验":info.getType().equals(StudyTypeEnum.fsy.getValue())?"解锁非试验":info.getType().equals(StudyTypeEnum.mjy.getValue())?"解锁麻精药文件夹":"");
        sign.setQmyyEn(info.getType().equals(StudyTypeEnum.sy.getValue())?"Unlock Study":info.getType().equals(StudyTypeEnum.fsy.getValue())?"Unlock Record":info.getType().equals(StudyTypeEnum.mjy.getValue())?"Unlock Record":"");
        studyJcgjService.saveInfo(study.getId(), JcgjlxEnum.lc, JcmcysEnum.blue,null,null,sign);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void gd(StudySaveForm form) {
        Study study = form.getStudy();
        SignForm sign = form.getSign();

        Study info = getById(study.getId());
        if(info==null){
            throw new ServiceException("信息不存在");
        }
        if(!info.getStatus().equals(StudyStatusEnum.ysd.getValue())){
            throw new ServiceException("当前状态不能申请归档");
        }
        checkPermit(info);
        checkPassword(sign);
        info.setStatus(StudyStatusEnum.dgd.getValue());
        info.setGdApplyTime(new Date());
        updateById(info);
        sign.setQmyy(info.getType().equals(StudyTypeEnum.sy.getValue())?"申请归档":info.getType().equals(StudyTypeEnum.fsy.getValue())?"申请归档":info.getType().equals(StudyTypeEnum.mjy.getValue())?"申请归档":"");
        sign.setQmyyEn(info.getType().equals(StudyTypeEnum.sy.getValue())?"Apply for Archiving":info.getType().equals(StudyTypeEnum.fsy.getValue())?"Apply for Archiving":info.getType().equals(StudyTypeEnum.mjy.getValue())?"Apply for Archiving":"");
        studyJcgjService.saveInfo(study.getId(), JcgjlxEnum.lc, JcmcysEnum.blue,null,null,sign);

        archiveLogService.saveInfo(ArchiveLogTypeEnum.sy,StudyTypeEnum.getEnumByValue(info.getType()),info.getId(),info.getName(),info.getSn(),info.getLeaderName(),"申请归档");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void jd(StudySaveForm form) {
        Study study = form.getStudy();
        SignForm sign = form.getSign();

        Study info = getById(study.getId());
        if(info==null){
            throw new ServiceException("信息不存在");
        }
        if(!(info.getStatus().equals(StudyStatusEnum.gd.getValue()) && info.getBorrowStatus().equals(StudyBorrowStatusEnum.wjy.getValue()))){
            throw new ServiceException("当前状态不能申请解档");
        }
        checkPermit(info);
        checkPassword(sign);
        info.setStatus(StudyStatusEnum.djd.getValue());
        updateById(info);
        sign.setQmyy(info.getType().equals(StudyTypeEnum.sy.getValue())?"申请解档":info.getType().equals(StudyTypeEnum.fsy.getValue())?"申请解档":info.getType().equals(StudyTypeEnum.mjy.getValue())?"申请解档":"");
        sign.setQmyyEn(info.getType().equals(StudyTypeEnum.sy.getValue())?"Apply for De-archiving":info.getType().equals(StudyTypeEnum.fsy.getValue())?"Apply for De-archiving":info.getType().equals(StudyTypeEnum.mjy.getValue())?"Apply for De-archiving":"");
        studyJcgjService.saveInfo(study.getId(), JcgjlxEnum.lc, JcmcysEnum.blue,null,null,sign);

        archiveLogService.saveInfo(ArchiveLogTypeEnum.sy,StudyTypeEnum.getEnumByValue(info.getType()),info.getId(),info.getName(),info.getSn(),info.getLeaderName(),"申请解档");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void jy(StudySaveForm form) {
        Study study = form.getStudy();
        SignForm sign = form.getSign();

        Study info = getById(study.getId());
        if(info==null){
            throw new ServiceException("信息不存在");
        }
        if(!(info.getStatus().equals(StudyStatusEnum.gd.getValue()) && info.getBorrowStatus().equals(StudyBorrowStatusEnum.wjy.getValue()))){
            throw new ServiceException("当前状态不能申请借阅");
        }
        checkPermit(info);
        checkPassword(sign);
        info.setBorrowStatus(StudyBorrowStatusEnum.djy.getValue());
        info.setBorrowStartDate(sign.getStartDate());
        info.setBorrowEndDate(sign.getEndDate());
        updateById(info);
        sign.setQmyy(info.getType().equals(StudyTypeEnum.sy.getValue())?"申请借阅":info.getType().equals(StudyTypeEnum.fsy.getValue())?"申请借阅":info.getType().equals(StudyTypeEnum.mjy.getValue())?"申请借阅":"");
        sign.setQmyyEn(info.getType().equals(StudyTypeEnum.sy.getValue())?"Apply for Check-out":info.getType().equals(StudyTypeEnum.fsy.getValue())?"Apply for Check-out":info.getType().equals(StudyTypeEnum.mjy.getValue())?"Apply for Check-out":"");
        studyJcgjService.saveInfo(study.getId(), JcgjlxEnum.lc, JcmcysEnum.blue,null,null,sign);

        archiveLogService.saveInfo(ArchiveLogTypeEnum.sy,StudyTypeEnum.getEnumByValue(info.getType()),info.getId(),info.getName(),info.getSn(),info.getLeaderName(),"申请借阅");
    }

    @Override
    public void checkPassword(SignForm sign){
        if(sign==null){
            throw new ServiceException("签名参数有误");
        }
        if(StringUtils.isBlank(sign.getQmrmm())){
            throw new ServiceException("签名密码不能为空");
        }
        sysUserService.checkPassword(SecurityUtils.getLoginUser().getSysUser(),sign.getQmrmm(),false);
    }

    private void checkPermit(Study study){
        if(study.getType().equals(StudyTypeEnum.sy.getValue())){
            //TFM和所属人可以操作
            String tfmRole = "TFM";
            if(!AuthUtil.hasRole(tfmRole) && !study.getLeader().equals(SecurityUtils.getUserId())){
                throw new ServiceException("没有该试验操作权限");
            }
        }
        if(study.getType().equals(StudyTypeEnum.fsy.getValue())){
            //部长和所属人可以操作
            String bz = "bz";
            if(!AuthUtil.hasRole(bz) && !study.getLeader().equals(SecurityUtils.getUserId())){
                throw new ServiceException("没有该非试验表单操作权限");
            }
        }
        if(study.getType().equals(StudyTypeEnum.mjy.getValue())){
            //部长和所属人可以操作
            String bz = "bz";
            if(!AuthUtil.hasRole(bz) && !study.getLeader().equals(SecurityUtils.getUserId())){
                throw new ServiceException("没有该麻精药表单操作权限");
            }
        }
    }

    @Override
    public HomeCountDto queryHomeCount() {
        HomeCountDto formCount = baseMapper.queryHomeFormCount(SecurityUtils.getUserId());
        HomeCountDto studyCount = baseMapper.queryHomeStudyCount(SecurityUtils.getUserId());

        formCount.setStudyWeekCount(studyCount.getStudyWeekCount());
        formCount.setStudyFinishCount(studyCount.getStudyFinishCount());
        return formCount;
    }

    // region 档案相关

    @Override
    public List<StudyListDto> queryArchiveList(StudySearchForm form) {
        QueryWrapper<StudyListDto> queryWrapper = new QueryWrapper();
        queryWrapper.eq("s.del_flag","0");
        queryWrapper.in("s.status",new Integer[]{StudyStatusEnum.dgd.getValue(),StudyStatusEnum.gd.getValue(),StudyStatusEnum.djd.getValue()});
        queryWrapper.eq("s.type",form.getType());
        if(StringUtils.isNoneBlank(form.getName())){
            queryWrapper.like("s.name",form.getName());
        }
        if(StringUtils.isNoneBlank(form.getSn())){
            queryWrapper.like("s.sn",form.getSn());
        }
        if(form.getStatus()!=null && form.getStatus().intValue()>0){
            queryWrapper.eq("s.status",form.getStatus());
        }
        queryWrapper.orderByDesc("s.gd_apply_time");
        queryWrapper.orderByDesc("s.id");
        return baseMapper.queryArchiveList(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doGd(StudySaveForm form) {
        Study study = form.getStudy();
        SignForm sign = form.getSign();

        Study info = getById(study.getId());
        if(info==null){
            throw new ServiceException("信息不存在");
        }
        if(!info.getStatus().equals(StudyStatusEnum.dgd.getValue())){
            throw new ServiceException("当前状态不能同意/拒绝归档");
        }
        checkPassword(sign);
        info.setStatus(study.getStatus());
        updateById(info);
        sign.setQmyy(study.getStatus().equals(StudyStatusEnum.ysd.getValue())?"拒绝归档":"同意归档");
        sign.setQmyyEn(study.getStatus().equals(StudyStatusEnum.ysd.getValue())?"Reject Archiving":"Approve Archiving");
        studyJcgjService.saveInfo(study.getId(), JcgjlxEnum.lc, study.getStatus().equals(StudyStatusEnum.ysd.getValue())?JcmcysEnum.red:JcmcysEnum.blue,null,null,sign);

        archiveLogService.saveInfo(ArchiveLogTypeEnum.sy,StudyTypeEnum.getEnumByValue(info.getType()),info.getId(),info.getName(),info.getSn(),info.getLeaderName(),study.getStatus().equals(StudyStatusEnum.ysd.getValue())?"拒绝归档":"同意归档");

        String title = StudyTypeEnum.getEnumByValue(info.getType()).getText()+"【"+info.getName()+"（"+info.getSn()+"）】提交的申请归档已"+sign.getQmyy()+(study.getStatus().equals(StudyStatusEnum.ysd.getValue())?("，原因："+sign.getRemark()):"");
        noticeService.save(title,study.getLeader(),getNoticeUrl(info));
    }

    private String getNoticeUrl(Study study){
        return  study.getType().equals(StudyTypeEnum.sy.getValue())?("/trial/list"):study.getType().equals(StudyTypeEnum.fsy.getValue())?("/form/nonTrial"):study.getType().equals(StudyTypeEnum.mjy.getValue())?("/form/drug"):"";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doJd(StudySaveForm form) {
        Study study = form.getStudy();
        SignForm sign = form.getSign();

        Study info = getById(study.getId());
        if(info==null){
            throw new ServiceException("信息不存在");
        }
        if(!info.getStatus().equals(StudyStatusEnum.djd.getValue())){
            throw new ServiceException("当前状态不能同意/拒绝解档");
        }
        checkPassword(sign);
        info.setStatus(study.getStatus());
        updateById(info);
        sign.setQmyy(study.getStatus().equals(StudyStatusEnum.gd.getValue())?"拒绝解档":"同意解档");
        sign.setQmyyEn(study.getStatus().equals(StudyStatusEnum.gd.getValue())?"Reject De-archiving":"Approve De-archiving");
        studyJcgjService.saveInfo(study.getId(), JcgjlxEnum.lc, study.getStatus().equals(StudyStatusEnum.gd.getValue())?JcmcysEnum.red:JcmcysEnum.blue,null,null,sign);

        archiveLogService.saveInfo(ArchiveLogTypeEnum.sy,StudyTypeEnum.getEnumByValue(info.getType()),info.getId(),info.getName(),info.getSn(),info.getLeaderName(),study.getStatus().equals(StudyStatusEnum.gd.getValue())?"拒绝解档":"同意解档");

        String title = StudyTypeEnum.getEnumByValue(info.getType()).getText()+"【"+info.getName()+"（"+info.getSn()+"）】提交的申请解档已"+sign.getQmyy()+(study.getStatus().equals(StudyStatusEnum.gd.getValue())?("，原因："+sign.getRemark()):"");
        noticeService.save(title,study.getLeader(),getNoticeUrl(info));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doJy(StudySaveForm form) {
        Study study = form.getStudy();
        SignForm sign = form.getSign();

        Study info = getById(study.getId());
        if(info==null){
            throw new ServiceException("信息不存在");
        }
        if(!(info.getStatus().equals(StudyStatusEnum.gd.getValue()) && info.getBorrowStatus().equals(StudyBorrowStatusEnum.djy.getValue()))){
            throw new ServiceException("当前状态不能同意/拒绝借阅");
        }
        info.setBorrowStatus(study.getBorrowStatus());
        info.setBorrowStartDate(sign.getStartDate());
        info.setBorrowEndDate(sign.getEndDate());
        updateById(info);
        sign.setQmyy(study.getBorrowStatus().equals(StudyBorrowStatusEnum.wjy.getValue())?"拒绝借阅":"同意借阅");
        sign.setQmyyEn(study.getBorrowStatus().equals(StudyBorrowStatusEnum.wjy.getValue())?"Reject Check-out":"Approve Check-out");
        studyJcgjService.saveInfo(study.getId(), JcgjlxEnum.lc, study.getBorrowStatus().equals(StudyBorrowStatusEnum.wjy.getValue())?JcmcysEnum.red:JcmcysEnum.blue,null,null,sign);

        archiveLogService.saveInfo(ArchiveLogTypeEnum.sy,StudyTypeEnum.getEnumByValue(info.getType()),info.getId(),info.getName(),info.getSn(),info.getLeaderName(),study.getBorrowStatus().equals(StudyBorrowStatusEnum.wjy.getValue())?"拒绝借阅":"同意借阅");

        String title = StudyTypeEnum.getEnumByValue(info.getType()).getText()+"【"+info.getName()+"（"+info.getSn()+"）】提交的申请借阅已"+sign.getQmyy()+(study.getBorrowStatus().equals(StudyBorrowStatusEnum.wjy.getValue())?("，原因："+sign.getRemark()):"");
        noticeService.save(title,study.getLeader(),getNoticeUrl(info));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void gh(StudySaveForm form) {
        Study study = form.getStudy();
        SignForm sign = form.getSign();

        Study info = getById(study.getId());
        if(info==null){
            throw new ServiceException("信息不存在");
        }
        if(!(info.getStatus().equals(StudyStatusEnum.gd.getValue()) && info.getBorrowStatus().equals(StudyBorrowStatusEnum.jyz.getValue()))){
            throw new ServiceException("当前状态不能确认归还");
        }
        checkPassword(sign);
        info.setBorrowStatus(StudyBorrowStatusEnum.wjy.getValue());
        updateById(info);
        sign.setQmyy("确认归还");
        sign.setQmyyEn("Confirm Check-in");
        studyJcgjService.saveInfo(study.getId(), JcgjlxEnum.lc, JcmcysEnum.blue,null,null,sign);

        archiveLogService.saveInfo(ArchiveLogTypeEnum.sy,StudyTypeEnum.getEnumByValue(info.getType()),info.getId(),info.getName(),info.getSn(),info.getLeaderName(),"确认归还");

        String title = StudyTypeEnum.getEnumByValue(info.getType()).getText()+"【"+info.getName()+"（"+info.getSn()+"）】提交的申请借阅已确认归还";
        noticeService.save(title,study.getLeader(),getNoticeUrl(info));
    }

    //endregion
}
