package com.hxhq.business.service.impl;

import java.util.*;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hxhq.business.domain.*;
import com.hxhq.business.dto.study.StudyFormApplyListDto;
import com.hxhq.business.enums.NormalEnum;
import com.hxhq.business.enums.SnTypeEnum;
import com.hxhq.business.enums.study.StudyFormApplyBdztEnum;
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.*;
import com.hxhq.business.form.study.StudyFormApplySearchForm;
import com.hxhq.business.service.*;
import com.hxhq.business.utils.JctUtil;
import com.hxhq.business.utils.ObjectCompareUtil;
import com.hxhq.business.utils.lang.StudyFormUtil;
import com.hxhq.common.core.exception.ServiceException;
import com.hxhq.common.core.utils.StringUtils;
import com.hxhq.common.security.utils.SecurityUtils;
import com.hxhq.system.api.domain.SysDept;
import com.hxhq.system.api.domain.SysUser;
import com.hxhq.system.service.ISysDeptService;
import com.hxhq.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hxhq.business.mapper.StudyFormApplyMapper;
import com.hxhq.business.domain.StudyFormApply;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 试验-申请单Service业务层处理
 *
 * @author hxhq
 * @date 2025-12-29
 */
@Service
public class StudyFormApplyServiceImpl extends ServiceImpl<StudyFormApplyMapper, StudyFormApply> implements IStudyFormApplyService {

    @Autowired
    private IStudyFormApplyJcgjService studyFormApplyJcgjService;
    @Autowired
    private IStudyFormApplyQmxxService studyFormApplyQmxxService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISnGenService snGenService;
    @Autowired
    private ITemplateService templateService;
    @Autowired
    private IStudyService studyService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private INoticeService noticeService;

    /**
     * 查询试验-申请单列表
     *
     * @param form 试验-申请单
     * @return 试验-申请单
     */
    @Override
    public List<StudyFormApplyListDto> queryList(StudyFormApplySearchForm form) {
        QueryWrapper<StudyFormApply> queryWrapper = Wrappers.query();
        queryWrapper.eq("t.del_flag", "0");
        if (form.getUserId() != null && form.getUserId().longValue() > 0) {
            queryWrapper.eq("t.user_id", form.getUserId());
        }
        if (form.getStudyId() != null && form.getStudyId().longValue() > 0) {
            queryWrapper.eq("t.study_id", form.getStudyId());
        }
        if (form.getStudySubjectId() != null && form.getStudySubjectId().longValue() > 0) {
            queryWrapper.eq("t.study_subject_id", form.getStudySubjectId());
        }
        if (StringUtils.isNoneBlank(form.getSfbl())) {
            queryWrapper.eq("t.sfbl", form.getSfbl());
        }
        if (StringUtils.isNoneBlank(form.getBdbh())) {
            queryWrapper.and(p -> p.like("t.`bdbh`", form.getBdbh()));
        }
        if (StringUtils.isNoneBlank(form.getBdmc())) {
            queryWrapper.and(p -> p.like("t.`bdmc`", form.getBdmc()));
        }
        if (StringUtils.isNoneBlank(form.getTemplateMc())) {
            queryWrapper.and(p -> p.like("tm.`name`", form.getTemplateMc()));
        }
        if (StringUtils.isNoneBlank(form.getTjsjks())) {
            queryWrapper.apply("t.tjsj>={0}", form.getTjsjks());
        }
        if (StringUtils.isNoneBlank(form.getTjsjjs())) {
            queryWrapper.apply("t.tjsj<{0}", form.getTjsjjs());
        }
        if (StringUtils.isNoneBlank(form.getCjsjks())) {
            queryWrapper.apply("t.create_time>={0}", form.getCjsjks());
        }
        if (StringUtils.isNoneBlank(form.getCjsjjs())) {
            queryWrapper.apply("t.create_time<{0}", form.getCjsjjs());
        }
        queryWrapper.orderByDesc("t.create_time");
        return baseMapper.queryList(queryWrapper);
    }

    /**
     * 详情
     *
     * @param id
     * @return 详情
     */
    @Override
    public StudyFormApply queryInfo(Long id) {
        if (id == null || id.longValue() < 0) {
            throw new ServiceException("参数id不正确");
        }
        return baseMapper.queryInfo(id);
    }

    /**
     * 加签 ok
     *
     * @param studyFormApply
     */
    @Override
    public void jq(StudyFormApply studyFormApply) {
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        //验证签名人密码
        checkPassword(qmr, studyFormApply.getQmrmm());
        if (studyFormApply.getId() == null || studyFormApply.getId().longValue() < 0) {
            throw new ServiceException("参数id不正确");
        }
        StudyFormApply studyFormApplyOld = this.getById(studyFormApply.getId());
        if (studyFormApplyOld == null) {
            throw new ServiceException("表单不存在或已删除");
        }
        if (!studyFormApplyOld.getBdzt().equals(StudyFormApplyBdztEnum.tbz.getValue())) {
            throw new ServiceException("表单不是申请状态，不能加签");
        }
        //稽查轨迹
        studyFormApplyJcgjService.saveJcgj(studyFormApplyOld.getId(), JcgjlxEnum.bj.getValue(), studyFormApply.getQmyy(), JcmcysEnum.orange.getValue(), null, qmr, studyFormApply.getRemark(), null);
        //签名信息
        studyFormApplyQmxxService.saveQmxx(studyFormApply.getId(), studyFormApply.getQmyy(), qmr, studyFormApply.getRemark());

    }

    /**
     * 废止
     *
     * @param studyFormApply
     */
    @Override
    public void fz(StudyFormApply studyFormApply) {
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        //验证签名人密码
        checkPassword(qmr, studyFormApply.getQmrmm());
        if (studyFormApply.getId() == null || studyFormApply.getId().longValue() < 0) {
            throw new ServiceException("参数id不正确");
        }
        StudyFormApply studyFormApplyOld = this.getById(studyFormApply.getId());
        if (studyFormApplyOld == null) {
            throw new ServiceException("表单不存在或已删除");
        }
        if (!studyFormApplyOld.getBdzt().equals(StudyFormApplyBdztEnum.tbz.getValue())) {
            throw new ServiceException("表单不是申请状态，不能废止");
        }
        studyFormApplyOld.setBdzt(StudyFormApplyBdztEnum.dfz.getValue());
        this.updateById(studyFormApplyOld);
        //稽查轨迹
        studyFormApplyJcgjService.saveJcgj(studyFormApplyOld.getId(), JcgjlxEnum.lc.getValue(), "申请废止", JcmcysEnum.orange.getValue(), null, qmr, studyFormApply.getRemark(), null);
        //签名信息
        studyFormApplyQmxxService.saveQmxx(studyFormApply.getId(), "申请废止", qmr, studyFormApply.getRemark());

    }


    /**
     * 审核废止
     *
     * @param form
     */
    @Override
    public void qrfz(StudyFormApplyShfzForm form) {
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        //验证签名人密码
        checkPassword(qmr, form.getQmrmm());
        if (form.getId() == null || form.getId().longValue() < 0) {
            throw new ServiceException("参数id不正确");
        }
        StudyFormApply studyFormApplyOld = this.getById(form.getId());
        if (studyFormApplyOld == null) {
            throw new ServiceException("表单不存在或已删除");
        }
        if (!studyFormApplyOld.getBdzt().equals(StudyFormApplyBdztEnum.dfz.getValue())) {
            throw new ServiceException("表单不是申请状态，不能废止");
        }
        if (form.getQmyy().equals(NormalEnum.yes.getValue())) {
            studyFormApplyOld.setBdzt(StudyFormApplyBdztEnum.yfz.getValue());
            this.updateById(studyFormApplyOld);
            //稽查轨迹
            studyFormApplyJcgjService.saveJcgj(studyFormApplyOld.getId(), JcgjlxEnum.lc.getValue(), "废止通过", JcmcysEnum.green.getValue(), null, qmr, form.getRemark(), null);
            //签名信息
            studyFormApplyQmxxService.saveQmxx(studyFormApplyOld.getId(), "废止通过", qmr, form.getRemark());
            //发送通知
            Study study = studyService.getById(studyFormApplyOld.getStudyId());
            String url = getUrlQz(study,"sqbd");
            String title = StudyTypeEnum.getEnumByValue(study.getType()).getText()+"【"+study.getName()+"】下领取申请单【"+studyFormApplyOld.getBdmc()+"】废止拒绝";
            noticeService.save(title,studyFormApplyOld.getUserId(),url);
        } else {
            studyFormApplyOld.setBdzt(StudyFormApplyBdztEnum.tbz.getValue());
            this.updateById(studyFormApplyOld);
            //稽查轨迹
            studyFormApplyJcgjService.saveJcgj(studyFormApplyOld.getId(), JcgjlxEnum.lc.getValue(), "废止拒绝", JcmcysEnum.red.getValue(), null, qmr, form.getRemark(), null);
            //签名信息
            studyFormApplyQmxxService.saveQmxx(studyFormApplyOld.getId(), "废止拒绝", qmr, form.getRemark());
            //发送通知
            Study study = studyService.getById(studyFormApplyOld.getStudyId());
            String url = getUrlQz(study,"sqbd");
            String title = StudyTypeEnum.getEnumByValue(study.getType()).getText()+"【"+study.getName()+"】下领取申请单【"+studyFormApplyOld.getBdmc()+"】废止拒绝";
            noticeService.save(title,studyFormApplyOld.getUserId(),url);

        }

    }


    /**
     * 更换归属人
     *
     * @param studyFormApply
     */
    @Override
    public void ghgsr(StudyFormApply studyFormApply) {
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        //验证签名人密码
        checkPassword(qmr, studyFormApply.getQmrmm());
        if (studyFormApply.getId() == null || studyFormApply.getId().longValue() < 0) {
            throw new ServiceException("参数id不正确");
        }
        StudyFormApply studyFormApplyOld = this.getById(studyFormApply.getId());
        if (studyFormApplyOld == null) {
            throw new ServiceException("表单不存在或已删除");
        }
        if (studyFormApplyOld.getBdzt().equals(StudyFormApplyBdztEnum.dfz.getValue()) || studyFormApplyOld.getBdzt().equals(StudyFormApplyBdztEnum.yfz.getValue())) {
            throw new ServiceException("表单已废止或待废止，不能更换归属人");
        }
        //是否验证新的归属人，是否属于该实验？ todo
        studyFormApplyOld.setUserId(studyFormApply.getUserId());
        studyFormApplyOld.setUserMc(studyFormApply.getUserMc());
        this.updateById(studyFormApplyOld);

        //稽查轨迹
        Map<String, String> formData = new LinkedHashMap<>();
        formData.put("新归属人", studyFormApply.getUserMc());
        formData.put("原归属人", studyFormApplyOld.getUserMc());
        formData.put("原因", studyFormApply.getRemark());
        studyFormApplyJcgjService.saveJcgj(studyFormApplyOld.getId(), JcgjlxEnum.lc.getValue(), "更换归属人", JcmcysEnum.orange.getValue(), formData, qmr, null, null);
        //签名信息
        studyFormApplyQmxxService.saveQmxx(studyFormApplyOld.getId(), "更换归属人", qmr, studyFormApply.getRemark());
        //发送通知
        Study study = studyService.getById(studyFormApplyOld.getStudyId());
        String url = getUrlQz(study,"sqbd");
        String title = StudyTypeEnum.getEnumByValue(study.getType()).getText()+"【"+study.getName()+"】下领取申请单【"+studyFormApplyOld.getBdmc()+"】已更换您为归属人";
        noticeService.save(title,studyFormApplyOld.getUserId(),url);
    }

    /**
     * 保存
     *
     * @param studyFormApply
     */
    @Override
    public StudyFormApply bc(StudyFormApply studyFormApply) {
        StudyFormApply result = null;
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        if (studyFormApply.getId() != null) {
            StudyFormApply studyFormApplyOld = this.queryInfo(studyFormApply.getId());
            if (studyFormApplyOld == null) {
                throw new ServiceException("信息不存在或已删除");
            }
            if (!qmr.getUserId().equals(studyFormApplyOld.getUserId())) {
                throw new ServiceException("只能操作自己的表单");
            }
            studyFormApplyOld.setBdmc(studyFormApply.getBdmc());
            studyFormApplyOld.setTemplateId(studyFormApply.getTemplateId());
            studyFormApplyOld.setBdnr(studyFormApply.getBdnr());
            studyFormApplyOld.setBdzt(StudyFormApplyBdztEnum.tbz.getValue());
            this.updateById(studyFormApplyOld);
            List<ObjectCompareUtil.FieldChange> fieldChanges = ObjectCompareUtil.compareObjectsNotNULL(studyFormApplyOld, studyFormApply);
            if (fieldChanges.size() == 0) {
                //稽查轨迹
                List<StudyFormApplyJcgj> studyFormApplyJcgjs = new ArrayList<>();
                for (ObjectCompareUtil.FieldChange fieldChange : fieldChanges) {
                    studyFormApplyJcgjs.add(studyFormApplyJcgjService.getJcgj(studyFormApply.getId(), JcgjlxEnum.xg.getValue(), "修改", JcmcysEnum.orange.getValue(), fieldChange.toString(), fieldChange.toEnString(), SecurityUtils.getLoginUser().getSysUser(), studyFormApply.getRemark()));
                }
                studyFormApplyJcgjService.saveBatch(studyFormApplyJcgjs);
            }
            result = studyFormApplyOld;
        } else {

            studyFormApply.setBdzt(StudyFormApplyBdztEnum.tbz.getValue());
            studyFormApply.setUserId(qmr.getUserId());
            studyFormApply.setBdbh(getSn(studyFormApply));
            studyFormApply.setUserMc(qmr.getNickName());
            studyFormApply.setUserMcEn(qmr.getUserName());
            this.save(studyFormApply);
            //稽查轨迹
            Map<String, String> formData = new LinkedHashMap<>();
            formData.put("备注", studyFormApply.getRemark());
            studyFormApplyJcgjService.saveJcgj(studyFormApply.getId(), JcgjlxEnum.lc.getValue(), "填写并保存记录", JcmcysEnum.green.getValue(), null, qmr, studyFormApply.getRemark(), null);
            result = studyFormApply;
        }
        //签名信息
        studyFormApplyQmxxService.saveQmxx(studyFormApply.getId(), "填写并保存记录", qmr, studyFormApply.getRemark());
        return baseMapper.queryInfo(result.getId());
    }

    /**
     * 仅保存
     *
     * @param studyFormApply
     */
    @Override
    public StudyFormApply bcOnly(StudyFormApply studyFormApply) {
        StudyFormApply result = null;
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        if (studyFormApply.getId() != null) {
            StudyFormApply studyFormApplyOld = this.queryInfo(studyFormApply.getId());
            if (studyFormApplyOld == null) {
                throw new ServiceException("信息不存在或已删除");
            }
            if (!qmr.getUserId().equals(studyFormApplyOld.getUserId())) {
                throw new ServiceException("只能操作自己的表单");
            }
            studyFormApplyOld.setBdmc(studyFormApply.getBdmc());
            studyFormApplyOld.setTemplateId(studyFormApply.getTemplateId());
            studyFormApplyOld.setBdnr(studyFormApply.getBdnr());
            studyFormApplyOld.setBdzt(StudyFormApplyBdztEnum.tbz.getValue());
            this.updateById(studyFormApplyOld);
            result = studyFormApplyOld;
        } else {

            studyFormApply.setBdzt(StudyFormApplyBdztEnum.tbz.getValue());
            studyFormApply.setUserId(qmr.getUserId());
            studyFormApply.setBdbh(getSn(studyFormApply));
            studyFormApply.setUserMc(qmr.getNickName());
            studyFormApply.setUserMcEn(qmr.getUserName());
            this.save(studyFormApply);
            result = studyFormApply;
        }
        return baseMapper.queryInfo(result.getId());
    }


    /**
     * 提交
     *
     * @param studyFormApply
     */
    @Override
    public void tj(StudyFormApply studyFormApply) {
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        //验证签名人密码
        checkPassword(qmr, studyFormApply.getQmrmm());
        if (studyFormApply.getId() == null) {
            studyFormApply.setUserId(qmr.getUserId());
            studyFormApply.setUserMc(SecurityUtils.getNickName());
            studyFormApply.setBdbh(getSn(studyFormApply));
        }
        studyFormApply.setBdzt(StudyFormApplyBdztEnum.ytj.getValue());
        studyFormApply.setTjsj(new Date());
        this.saveOrUpdate(studyFormApply);
        //稽查轨迹
        studyFormApplyJcgjService.saveJcgj(studyFormApply.getId(), JcgjlxEnum.lc.getValue(), "填写并提交记录", JcmcysEnum.green.getValue(), null, qmr, studyFormApply.getRemark(), null);
        //签名信息
        studyFormApplyQmxxService.saveQmxx(studyFormApply.getId(), "填写并提交记录", qmr, studyFormApply.getRemark());
    }


    /**
     * 复核通过
     *
     * @param studyFormApply
     */
    @Override
    public void fhtg(StudyFormApply studyFormApply) {
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        //验证签名人密码
        checkPassword(qmr, studyFormApply.getQmrmm());
        if (studyFormApply.getId() == null || studyFormApply.getId().longValue() < 0) {
            throw new ServiceException("参数id不正确");
        }
        StudyFormApply studyFormApplyOld = this.getById(studyFormApply.getId());
        if (studyFormApplyOld == null) {
            throw new ServiceException("表单不存在或已删除");
        }
        if (!studyFormApplyOld.getBdzt().equals(StudyFormApplyBdztEnum.ytj.getValue())) {
            throw new ServiceException("表单不是已提交状态，不能复核");
        }
        studyFormApplyOld.setBdzt(StudyFormApplyBdztEnum.yfh.getValue());
        this.updateById(studyFormApplyOld);
        //稽查轨迹
        studyFormApplyJcgjService.saveJcgj(studyFormApplyOld.getId(), JcgjlxEnum.lc.getValue(), "复核通过", JcmcysEnum.green.getValue(), null, qmr, studyFormApply.getRemark(), null);
        //签名信息
        studyFormApplyQmxxService.saveQmxx(studyFormApplyOld.getId(), "复核通过", qmr, studyFormApply.getRemark());
        //发送通知
        Study study = studyService.getById(studyFormApplyOld.getStudyId());
        String url = getUrlQz(study,"sqbd");
        String title = StudyTypeEnum.getEnumByValue(study.getType()).getText()+"【"+study.getName()+"】下领取申请单【"+studyFormApplyOld.getBdmc()+"】复核通过";
        noticeService.save(title,studyFormApplyOld.getUserId(),url);
    }


    /**
     * 复核拒绝
     *
     * @param studyFormApply
     */
    @Override
    public void fhjj(StudyFormApply studyFormApply) {
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        //验证签名人密码
        checkPassword(qmr, studyFormApply.getQmrmm());
        if (studyFormApply.getId() == null || studyFormApply.getId().longValue() < 0) {
            throw new ServiceException("参数id不正确");
        }
        StudyFormApply studyFormApplyOld = this.getById(studyFormApply.getId());
        if (studyFormApplyOld == null) {
            throw new ServiceException("表单不存在或已删除");
        }
        if (!studyFormApplyOld.getBdzt().equals(StudyFormApplyBdztEnum.ytj.getValue())) {
            throw new ServiceException("表单不是已提交状态，不能复核");
        }
        studyFormApplyOld.setBdzt(StudyFormApplyBdztEnum.tbz.getValue());
        this.updateById(studyFormApplyOld);
        //稽查轨迹
        Map<String, String> formData = new LinkedHashMap<>();
        formData.put("原因", studyFormApply.getRemark());
        studyFormApplyJcgjService.saveJcgj(studyFormApplyOld.getId(), JcgjlxEnum.lc.getValue(), "复核拒绝", JcmcysEnum.red.getValue(), formData, qmr, null, null);
        //签名信息
        studyFormApplyQmxxService.saveQmxx(studyFormApplyOld.getId(), "复核拒绝", qmr, studyFormApply.getRemark());
        //发送通知
        Study study = studyService.getById(studyFormApplyOld.getStudyId());
        String url = getUrlQz(study,"sqbd");
        String title = StudyTypeEnum.getEnumByValue(study.getType()).getText()+"【"+study.getName()+"】下领取申请单【"+studyFormApplyOld.getBdmc()+"】复核拒绝";
        noticeService.save(title,studyFormApplyOld.getUserId(),url);
    }

    /**
     * 审阅
     *
     * @param studyFormApply
     */
    @Override
    public void sy(StudyFormApply studyFormApply) {
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        //验证签名人密码
        checkPassword(qmr, studyFormApply.getQmrmm());
        if (studyFormApply.getId() == null || studyFormApply.getId().longValue() < 0) {
            throw new ServiceException("参数id不正确");
        }
        StudyFormApply studyFormApplyOld = this.getById(studyFormApply.getId());
        if (studyFormApplyOld == null) {
            throw new ServiceException("表单不存在或已删除");
        }
        if (!studyFormApplyOld.getBdzt().equals(StudyFormApplyBdztEnum.ywc.getValue())) {
            throw new ServiceException("表单不是已完成状态，不能审阅");
        }
        studyFormApplyOld.setBdnr(studyFormApply.getBdnr());
        this.updateById(studyFormApplyOld);
        //稽查轨迹
        Map<String, String> formData = new LinkedHashMap<>();
        formData.put("备注", studyFormApply.getRemark());
        studyFormApplyJcgjService.saveJcgj(studyFormApplyOld.getId(), JcgjlxEnum.lc.getValue(), "已审阅", JcmcysEnum.green.getValue(), null, qmr, studyFormApply.getRemark(), null);
        //签名信息
        studyFormApplyQmxxService.saveQmxx(studyFormApplyOld.getId(), "已审阅", qmr, studyFormApply.getRemark());
        //发送通知
        Study study = studyService.getById(studyFormApplyOld.getStudyId());
        String url = getUrlQz(study,"sqbd");
        String title = StudyTypeEnum.getEnumByValue(study.getType()).getText()+"【"+study.getName()+"】下领取申请单【"+studyFormApplyOld.getBdmc()+"】已审阅";
        noticeService.save(title,studyFormApplyOld.getUserId(),url);
    }


    /**
     * 审核通过
     *
     * @param studyFormApply
     */
    @Override
    public void shtg(StudyFormApply studyFormApply) {
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        //验证签名人密码
        checkPassword(qmr, studyFormApply.getQmrmm());
        if (studyFormApply.getId() == null || studyFormApply.getId().longValue() < 0) {
            throw new ServiceException("参数id不正确");
        }
        StudyFormApply studyFormApplyOld = this.getById(studyFormApply.getId());
        if (studyFormApplyOld == null) {
            throw new ServiceException("表单不存在或已删除");
        }
        if (!studyFormApplyOld.getBdzt().equals(StudyFormApplyBdztEnum.yfh.getValue())) {
            throw new ServiceException("表单不是已复核状态，不能审核");
        }
        studyFormApplyOld.setBdzt(StudyFormApplyBdztEnum.ywc.getValue());
        this.updateById(studyFormApplyOld);
        //稽查轨迹
        studyFormApplyJcgjService.saveJcgj(studyFormApplyOld.getId(), JcgjlxEnum.lc.getValue(), "审核通过", JcmcysEnum.green.getValue(), null, qmr, studyFormApply.getRemark(), null);
        //签名信息
        studyFormApplyQmxxService.saveQmxx(studyFormApplyOld.getId(), "审核通过", qmr, studyFormApply.getRemark());
        //发送通知
        Study study = studyService.getById(studyFormApplyOld.getStudyId());
        String url = getUrlQz(study,"sqbd");
        String title = StudyTypeEnum.getEnumByValue(study.getType()).getText()+"【"+study.getName()+"】下领取申请单【"+studyFormApplyOld.getBdmc()+"】审核通过";
        noticeService.save(title,studyFormApplyOld.getUserId(),url);
    }


    /**
     * 审核拒绝
     *
     * @param studyFormApply
     */
    @Override
    public void shjj(StudyFormApply studyFormApply) {
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        //验证签名人密码
        checkPassword(qmr, studyFormApply.getQmrmm());
        if (studyFormApply.getId() == null || studyFormApply.getId().longValue() < 0) {
            throw new ServiceException("参数id不正确");
        }
        StudyFormApply studyFormApplyOld = this.getById(studyFormApply.getId());
        if (studyFormApplyOld == null) {
            throw new ServiceException("表单不存在或已删除");
        }
        if (!studyFormApplyOld.getBdzt().equals(StudyFormApplyBdztEnum.yfh.getValue())) {
            throw new ServiceException("表单不是已复核状态，不能审核");
        }
        studyFormApplyOld.setBdzt(StudyFormApplyBdztEnum.wtg.getValue());
        this.updateById(studyFormApplyOld);
        //稽查轨迹
        Map<String, String> formData = new LinkedHashMap<>();
        formData.put("原因", studyFormApply.getRemark());
        studyFormApplyJcgjService.saveJcgj(studyFormApplyOld.getId(), JcgjlxEnum.lc.getValue(), "审核拒绝", JcmcysEnum.red.getValue(), formData, qmr, studyFormApply.getRemark(), null);
        //签名信息
        studyFormApplyQmxxService.saveQmxx(studyFormApplyOld.getId(), "审核拒绝", qmr, studyFormApply.getRemark());
        //发送通知
        Study study = studyService.getById(studyFormApplyOld.getStudyId());
        String url = getUrlQz(study,"sqbd");
        String title = StudyTypeEnum.getEnumByValue(study.getType()).getText()+"【"+study.getName()+"】下领取申请单【"+studyFormApplyOld.getBdmc()+"】审核拒绝";
        noticeService.save(title,studyFormApplyOld.getUserId(),url);

    }

    /**
     * 验证密码
     *
     * @param user
     * @param qmrmm
     */
    public void checkPassword(SysUser user, String qmrmm) {
        if (StringUtils.isBlank(qmrmm)) {
            throw new ServiceException("签名密码不能为空");
        }
        sysUserService.checkPassword(user, qmrmm, false);
    }

    /**
     * 更新表单内容
     */
    @Override
    public void updateBdnr(StudyFormUpdateForm form) {
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        JSONObject bdnr = JSONObject.parseObject(form.getBdnr());
        baseMapper.updateBdnr(form.getId(), form.getBdnr(),form.getZdxgjl(),bdnr.getLong("syId"),bdnr.getLong("bmId"),bdnr.getLong("sdId"));
        //稽查轨迹
        if (StringUtils.isNoneBlank(form.getFiledValue())) {
            JSONObject jsonObject = JSONObject.parseObject(form.getFiledValue());
            Map<String, String> formData = new LinkedHashMap<>();
            Map<String, String> formDataEn = new LinkedHashMap<>();
            List<StudyFormApplyJcgj> studyFormApplyJcgjs = new ArrayList<>();
            if (StringUtils.isNoneBlank(jsonObject.getString("oldValue"))) {
                //zh
                formData.put("字段名", jsonObject.getString("fieldCn"));
                formData.put("原值", jsonObject.getString("oldValue"));
                formData.put("新值", jsonObject.getString("value"));
                formData.put("原因", jsonObject.getString("reason"));
                //en
                formDataEn.put("字段名", jsonObject.getString("fieldEn"));
                formDataEn.put("原值", jsonObject.getString("oldValue"));
                formDataEn.put("新值", jsonObject.getString("value"));
                formDataEn.put("原因", jsonObject.getString("reason"));
                studyFormApplyJcgjs.add(studyFormApplyJcgjService.getJcgj(form.getId(), JcgjlxEnum.xg.getValue(), "修改记录", JcmcysEnum.orange.getValue(), JctUtil.formatStr(formData), StudyFormUtil.getJcnrEn(formDataEn), qmr, null));
            } else {
                //zh
                formData.put("字段名", jsonObject.getString("fieldCn"));
                formData.put("填入值", jsonObject.getString("value"));
                formData.put("填写人", qmr.getNickName());
                //en
                formDataEn.put("字段名", jsonObject.getString("fieldEn"));
                formDataEn.put("填入值", jsonObject.getString("value"));
                formDataEn.put("填写人", qmr.getNickName());
                studyFormApplyJcgjs.add(studyFormApplyJcgjService.getJcgj(form.getId(), JcgjlxEnum.xg.getValue(), "填写", JcmcysEnum.green.getValue(), JctUtil.formatStr(formData), StudyFormUtil.getJcnrEn(formDataEn), null, null));
            }
            studyFormApplyJcgjService.saveBatch(studyFormApplyJcgjs);
        }
    }

    /**
     * 更新复核意见
     */
    @Override
    public void updateFhyjjl(StudyFormUpdateForm form) {
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        //更新复核意见
        baseMapper.updateFhyjjl(form.getId(), form.getFhyjjl());
        StudyFormApply studyFormApplyOld = this.queryInfo(form.getId());
        studyFormApplyOld.setFhyjjl(form.getFhyjjl());
        this.updateById(studyFormApplyOld);
        Map<String, String> formData = new LinkedHashMap<>();
        Map<String, String> formDataEn = new LinkedHashMap<>();
        List<StudyFormApplyJcgj> studyFormApplyJcgjs = new ArrayList<>();
        if (StringUtils.isNoneBlank(form.getContent())) {
            JSONObject jsonObject = JSONObject.parseObject(form.getContent());
            //zh
            formData.put("字段名", jsonObject.getString("fieldCn"));
            formData.put("复核意见", jsonObject.getString("content"));
            //en
            formDataEn.put("字段名", jsonObject.getString("fieldEn"));
            formDataEn.put("复核意见", jsonObject.getString("content"));
            studyFormApplyJcgjs.add(studyFormApplyJcgjService.getJcgj(form.getId(), JcgjlxEnum.lc.getValue(), "复核意见", JcmcysEnum.blue.getValue(), JctUtil.formatStr(formData), StudyFormUtil.getJcnrEn(formDataEn), qmr, null));
        } else {
            JSONObject jsonObject = JSONObject.parseObject(form.getReply());
            //zh
            formData.put("字段名", jsonObject.getString("fieldCn"));
            formData.put("意见回复", jsonObject.getString("reply"));
            //en
            formDataEn.put("字段名", jsonObject.getString("fieldEn"));
            formDataEn.put("意见回复", jsonObject.getString("reply"));
            studyFormApplyJcgjs.add(studyFormApplyJcgjService.getJcgj(form.getId(), JcgjlxEnum.lc.getValue(), "意见回复", JcmcysEnum.blue.getValue(), JctUtil.formatStr(formData), StudyFormUtil.getJcnrEn(formDataEn), qmr, null));
        }
        studyFormApplyJcgjService.saveBatch(studyFormApplyJcgjs);
    }

    /**
     * 更新字段勾选记录
     */
    @Override
    public void updateZdgxjl(StudyFormUpdateForm form) {
        baseMapper.updateZdgxjl(form.getId(), form.getZdgxjl());
    }

    /**
     * 生成编号
     *
     * @param studyFormApply
     * @return
     */
    public String getSn(StudyFormApply studyFormApply) {
        Study study = studyService.getById(studyFormApply.getStudyId());
        if (study == null) {
            throw new ServiceException("试验不存在或已删除");
        }
        Template template = templateService.getById(studyFormApply.getTemplateId());
        if (template == null) {
            throw new ServiceException("模板不存在或已删除");
        }
        SysDept dep = sysDeptService.selectDeptById(template.getDeptId());
        if (dep == null) {
            throw new ServiceException("学科不存在或已删除");
        }
        // MB+表单名缩写(底层模板名称)+版本号+试验编号+学科缩写+流水号
        return "MB" + template.getShowSn() + study.getSn() + dep.getAbbr() + snGenService.getNewSn(SnTypeEnum.ybbd.getValue());
    }


    /**
     * 获取通知的跳转url
     * @param study
     * @param tab
     * @return
     */
    private String getUrlQz(Study study,String tab){
        return  study.getType().equals(StudyTypeEnum.sy.getValue())?("/study/enter/"+study.getId()+"/"+tab):study.getType().equals(StudyTypeEnum.fsy.getValue())?("/nonTrial/enter/"+study.getId()+"/"+tab):study.getType().equals(StudyTypeEnum.mjy.getValue())?("/drug/enter/"+study.getId()+"/"+tab):"";
    }

}
