package com.hxhq.business.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONArray;
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.*;
import com.hxhq.business.dto.study.StudyFormFillCc;
import com.hxhq.business.dto.study.StudyFormFillListDto;
import com.hxhq.business.dto.study.StudyFormFillResource;
import com.hxhq.business.enums.NormalEnum;
import com.hxhq.business.enums.SnTypeEnum;
import com.hxhq.business.enums.study.StudyFormFillBdztEnum;
import com.hxhq.business.enums.study.StudyFormFillResourceTypeEnum;
import com.hxhq.business.enums.study.StudyTypeEnum;
import com.hxhq.business.enums.template.ProductEnum;
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.StudyFormFillSearchForm;
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.StudyFormFillMapper;
import com.hxhq.business.domain.StudyFormFill;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 试验-填报单Service业务层处理
 *
 * @author hxhq
 * @date 2025-12-29
 */
@Service
public class StudyFormFillServiceImpl extends ServiceImpl<StudyFormFillMapper, StudyFormFill> implements IStudyFormFillService {

    @Autowired
    private IStudyFormFillJcgjService studyFormFillJcgjService;
    @Autowired
    private IStudyFormFillQmxxService studyFormFillQmxxService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ITemplateService templateService;
    @Autowired
    private ISjService sjService;
    @Autowired
    private ISnGenService snGenService;
    @Autowired
    private IStudyService studyService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private INoticeService noticeService;
    @Autowired
    private IMjyService mjyService;
    @Autowired
    private IGyzjService gyzjService;
    @Autowired
    private IGspService gspService;
    @Autowired
    private IStudyFormPreService studyFormPreService;
    @Autowired
    private IStudySubjectService studySubjectService;


    /**
     * 开始配置
     * @param form
     * @return
     */
    @Override
    public void startConfiguration(StudyFormConfigurationForm form){
        StudyFormFill studyFormFill=this.getById(form.getStudyFormId());
        if(studyFormFill==null){
            throw  new ServiceException("填报不存在或已删除");
        }
        Template template = templateService.getById(studyFormFill.getTemplateId());
        // 试剂
        if(template.getProduct().equals(ProductEnum.Sj.getValue())){
            sjService.startConfiguration(form);
        }
        // 给药制剂
        if(template.getProduct().equals(ProductEnum.Gyzj.getValue())){
            gyzjService.startConfiguration(form);
        }
    }


    /**
     * 配置完成
     * @param form
     * @return
     */
    @Override
    public void configurationCompleted(StudyFormConfigurationForm form){
        StudyFormFill studyFormFill=this.getById(form.getStudyFormId());
        if(studyFormFill==null){
            throw  new ServiceException("填报不存在或已删除");
        }
        Template template = templateService.getById(studyFormFill.getTemplateId());
        // 试剂
        if(template.getProduct().equals(ProductEnum.Sj.getValue())){
            sjService.configurationCompleted(form);
        }
        // 给药制剂
        if(template.getProduct().equals(ProductEnum.Gyzj.getValue())){
            gyzjService.configurationCompleted(form);
        }
    }


    /**
     * 分装
     * @param form
     * @return
     */
    @Override
    public void subpackage(StudyFormFillSubpackageForm form){
        StudyFormFill studyFormFill=this.getById(form.getStudyFormId());
        if(studyFormFill==null){
            throw  new ServiceException("填报不存在或已删除");
        }
        Template template = templateService.getById(studyFormFill.getTemplateId());
        // 试剂
        if(template.getProduct().equals(ProductEnum.Sj.getValue())){
            sjService.subpackage(form);
        }
        // 给药制剂
        if(template.getProduct().equals(ProductEnum.Gyzj.getValue())){
            gyzjService.subpackage(form);
        }
    }


    /**
     * 查询试验-填报单列表
     *
     * @param form 试验-填报单
     * @return 试验-填报单
     */
    @Override
    public List<StudyFormFillListDto> queryList(StudyFormFillSearchForm form) {
        QueryWrapper<StudyFormFill> queryWrapper = Wrappers.query();
        queryWrapper.eq("t.del_flag", "0");
        if (form.getUserId() != null && form.getUserId().longValue() > 0) {
            queryWrapper.eq("t.user_id", form.getUserId());
        }
        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 StudyFormFill queryInfo(Long id) {
        if (id == null || id.longValue() < 0) {
            throw new ServiceException("参数id不正确");
        }
        StudyFormFill studyFormFill = baseMapper.queryInfo(id);
        return studyFormFill;
    }

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

    }

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

    }


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

    }


    /**
     * 更换归属人
     *
     * @param studyFormFill
     */
    @Override
    public void ghgsr(StudyFormFill studyFormFill) {
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        //验证签名人密码
        checkPassword(qmr, studyFormFill.getQmrmm());
        if (studyFormFill.getId() == null || studyFormFill.getId().longValue() < 0) {
            throw new ServiceException("参数id不正确");
        }
        StudyFormFill studyFormFillOld = this.getById(studyFormFill.getId());
        if (studyFormFillOld == null) {
            throw new ServiceException("表单不存在或已删除");
        }
        if (studyFormFillOld.getBdzt().equals(StudyFormFillBdztEnum.dfz.getValue()) || studyFormFillOld.getBdzt().equals(StudyFormFillBdztEnum.yfz.getValue())) {
            throw new ServiceException("表单已废止或待废止，不能更换归属人");
        }
        //稽查轨迹
        Map<String, String> formData = new LinkedHashMap<>();
        formData.put("新归属人", studyFormFill.getUserMc());
        formData.put("原归属人", studyFormFillOld.getUserMc());
        formData.put("原因", studyFormFill.getRemark());

        //是否验证新的归属人，是否属于该实验？ todo
        studyFormFillOld.setUserId(studyFormFill.getUserId());
        studyFormFillOld.setUserMc(studyFormFill.getUserMc());
        this.updateById(studyFormFillOld);
        studyFormFillJcgjService.saveJcgj(studyFormFillOld.getId(), JcgjlxEnum.lc.getValue(), "更换归属人", JcmcysEnum.orange.getValue(), null, SecurityUtils.getLoginUser().getSysUser(), null, null);
        //签名信息
        studyFormFillQmxxService.saveQmxx(studyFormFillOld.getId(), "更换归属人", qmr, studyFormFill.getRemark());
        //发送通知
        Study study = studyService.getById(studyFormFillOld.getStudyId());
        String url = getUrlQz(study, "tbbd");
        String title = StudyTypeEnum.getEnumByValue(study.getType()).getText() + "【" + study.getName() + "】下填报表单【" + studyFormFillOld.getBdmc() + "】已更换您为归属人";
        noticeService.save(title, studyFormFillOld.getUserId(), url);
    }

    /**
     * 保存
     *
     * @param studyFormFill
     */
    @Override
    public StudyFormFill bc(StudyFormFill studyFormFill) {
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        //验证签名人密码
        checkPassword(SecurityUtils.getLoginUser().getSysUser(), studyFormFill.getQmrmm());
        StudyFormFill result = null;
        if (studyFormFill.getId() != null) {
            StudyFormFill studyFormFillOld = this.queryInfo(studyFormFill.getId());
            if (studyFormFillOld == null) {
                throw new ServiceException("信息不存在或已删除");
            }
            if (!SecurityUtils.getUserId().equals(studyFormFillOld.getUserId())) {
                throw new ServiceException("只能操作自己的表单");
            }
            studyFormFillOld.setBdmc(studyFormFill.getBdmc());
            studyFormFillOld.setBdnr(studyFormFill.getBdnr());
            studyFormFillOld.setBdzt(StudyFormFillBdztEnum.tbz.getValue());
            this.updateById(studyFormFillOld);
            result = studyFormFillOld;
            //签名信息
            studyFormFillQmxxService.saveQmxx(studyFormFill.getId(), "填写并保存记录", qmr, studyFormFill.getRemark());
            //稽查轨迹
            Map<String, String> formData = new LinkedHashMap<>();
            formData.put("备注", studyFormFill.getRemark());
            studyFormFillJcgjService.saveJcgj(studyFormFillOld.getId(), JcgjlxEnum.lc.getValue(), "填写并保存记录", JcmcysEnum.green.getValue(), formData, SecurityUtils.getLoginUser().getSysUser(), null, null);
        } else {
            studyFormFill.setBdzt(StudyFormFillBdztEnum.tbz.getValue());
            studyFormFill.setUserId(SecurityUtils.getUserId());
            studyFormFill.setBdbh(getSn(studyFormFill));
            studyFormFill.setStartDate(new Date());
            studyFormFill.setUserMc(SecurityUtils.getNickName());
            this.save(studyFormFill);
            result = studyFormFill;
            //签名信息
            studyFormFillQmxxService.saveQmxx(studyFormFill.getId(), "填写并保存记录", qmr, studyFormFill.getRemark());
            //稽查轨迹
            Map<String, String> formData = new LinkedHashMap<>();
            formData.put("备注", studyFormFill.getRemark());
            studyFormFillJcgjService.saveJcgj(studyFormFill.getId(), JcgjlxEnum.lc.getValue(), "创建记录", JcmcysEnum.green.getValue(), formData, SecurityUtils.getLoginUser().getSysUser(), null, null);
        }
        return baseMapper.queryInfo(result.getId());
    }

    /**
     * 保存
     *
     * @param studyFormFill
     */
    @Override
    public void bcAuto(StudyFormFill studyFormFill) {
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        studyFormFill.setBdzt(StudyFormFillBdztEnum.tbz.getValue());
        studyFormFill.setUserId(SecurityUtils.getUserId());
        studyFormFill.setBdbh(getSn(studyFormFill));
        studyFormFill.setStartDate(new Date());
        studyFormFill.setUserMc(SecurityUtils.getNickName());
        this.save(studyFormFill);
        //稽查轨迹
        studyFormFillJcgjService.saveJcgj(studyFormFill.getId(), JcgjlxEnum.lc.getValue(), "创建记录", JcmcysEnum.green.getValue(), null, qmr, studyFormFill.getRemark(), null);
        //签名信息
        studyFormFillQmxxService.saveQmxx(studyFormFill.getId(), "创建记录", qmr, studyFormFill.getRemark());
    }

    /**
     * 仅保存
     *
     * @param studyFormFill
     */
    @Override
    public StudyFormFill bcOnly(StudyFormFill studyFormFill) {
        StudyFormFill result = null;
        if (studyFormFill.getId() != null) {
            StudyFormFill studyFormFillOld = this.queryInfo(studyFormFill.getId());
            if (studyFormFillOld == null) {
                throw new ServiceException("信息不存在或已删除");
            }
            if (!SecurityUtils.getUserId().equals(studyFormFillOld.getUserId())) {
                throw new ServiceException("只能操作自己的表单");
            }
            studyFormFillOld.setBdmc(studyFormFill.getBdmc());
            studyFormFillOld.setBdnr(studyFormFill.getBdnr());
            studyFormFillOld.setBdzt(StudyFormFillBdztEnum.tbz.getValue());
            this.updateById(studyFormFillOld);
            result = studyFormFillOld;
        } else {
            studyFormFill.setBdzt(StudyFormFillBdztEnum.tbz.getValue());
            studyFormFill.setUserId(SecurityUtils.getUserId());
            studyFormFill.setBdbh(getSn(studyFormFill));
            studyFormFill.setStartDate(new Date());
            studyFormFill.setUserMc(SecurityUtils.getNickName());
            this.save(studyFormFill);
            result = studyFormFill;
        }
        return baseMapper.queryInfo(result.getId());
    }

    /**
     * 药剂存储
     *
     * @param studyFormFill
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void yjcc(StudyFormFill studyFormFill) {
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        //验证签名人密码
        checkPassword(qmr, studyFormFill.getQmrmm());
        if (studyFormFill.getId() != null) {
            StudyFormFill studyFormFillOld = this.queryInfo(studyFormFill.getId());
            Template template = templateService.getById(studyFormFillOld.getTemplateId());
            //只有列表有 开始配置 配置完成的时候，并且点了配置完成后 ，药剂存储才能选到配置出来的药剂，其余都只能选择使用的
            mjyService.storageResource(studyFormFillOld,template,studyFormFill.getRemark());
            gyzjService.storageResource(studyFormFillOld,template,studyFormFill.getRemark());
            gspService.storageResource(studyFormFillOld,template,studyFormFill.getRemark());
            //更新 Resource
            this.updateById(studyFormFillOld);
            String cclist = studyFormFill.getCclist();
            String empty = "[]";
            if (StringUtils.isNotEmpty(cclist) && !StringUtils.equals(empty, cclist)) {
                List<StudyFormFillJcgj> studyFormFillJcgjList=new ArrayList<>();
                List<StudyFormFillCc> studyFormFillCcList = JSONUtil.toList(cclist, StudyFormFillCc.class);
                for (StudyFormFillCc studyFormFillCc : studyFormFillCcList) {
                    //稽查轨迹
                    Map<String, String> formData = new LinkedHashMap<>();
                    formData.put("存储位置", studyFormFillCc.getCcwz());
                    formData.put("存储条件", studyFormFillCc.getCctj());
                    formData.put("存储药剂", String.join(",",studyFormFillCc.getList()));
                    studyFormFillJcgjList.add(studyFormFillJcgjService.getJcgj(studyFormFillOld.getId(), JcgjlxEnum.lc.getValue(), "存储", JcmcysEnum.green.getValue(), formData, qmr, null));
                }
                if(studyFormFillJcgjList.size()>0){
                    studyFormFillJcgjService.saveBatch(studyFormFillJcgjList);
                }
            }
        }
    }

    /**
     * 药剂存储过滤
     *
     * @param studyFormFill
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String yjccFilter(StudyFormFill studyFormFill) {
        List<StudyFormFillResource> result=new ArrayList<>();
        if (studyFormFill.getId() != null) {
            StudyFormFill studyFormFillOld = this.queryInfo(studyFormFill.getId());
            Template template = templateService.getById(studyFormFillOld.getTemplateId());
            String empty = "[]";
            if (StringUtils.isNotEmpty(studyFormFill.getResource()) && !StringUtils.equals(empty, studyFormFill.getResource())) {
                List<StudyFormFillResource> studyFormFillResourceList = JSONUtil.toList(studyFormFill.getResource(), StudyFormFillResource.class);
                result = studyFormFillResourceList.stream().filter(
                        p -> (p.getType() != null)).collect(Collectors.toList());
                List<StudyFormFillResource> tmp = studyFormFillResourceList.stream().filter(
                        p -> (p.getType() == null)).collect(Collectors.toList());
                if (tmp.size() > 0) {
                    List<String> bhList = tmp.stream().map(StudyFormFillResource::getBh).collect(Collectors.toList());
                    if(template.getProduct().equals(StudyFormFillResourceTypeEnum.mjy.getValue())){
                        LambdaQueryWrapper<Mjy> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.in(Mjy::getBh, bhList);
                        List<Mjy> mjyList = mjyService.list(queryWrapper);
                        Map<String, Mjy> mjyMap = new HashMap<>(10);
                        for (Mjy mjy : mjyList) {
                            mjyMap.put(mjy.getBh(), mjy);
                        }
                        for (StudyFormFillResource studyFormFillResource : studyFormFillResourceList) {
                            Mjy mjy = mjyMap.get(studyFormFillResource.getBh());
                            if(mjy!=null){
                                result.add(studyFormFillResource);
                            }
                        }
                    }
                    if(template.getProduct().equals(StudyFormFillResourceTypeEnum.gyzj.getValue())){
                        LambdaQueryWrapper<Gyzj> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.in(Gyzj::getBh, bhList);
                        List<Gyzj> gyzjList = gyzjService.list(queryWrapper);
                        Map<String, Gyzj> gyzjMap = new HashMap<>(10);
                        for (Gyzj gyzj : gyzjList) {
                            gyzjMap.put(gyzj.getBh(), gyzj);
                        }
                        for (StudyFormFillResource studyFormFillResource : studyFormFillResourceList) {
                            Gyzj gyzj = gyzjMap.get(studyFormFillResource.getBh());
                            if(gyzj!=null){
                                result.add(studyFormFillResource);
                            }
                        }
                    }
                }
            }
        }
        return  JSONObject.toJSONString(result);
    }

    /**
     * 提交
     *
     * @param studyFormFill
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void tj(StudyFormFill studyFormFill) {
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        //验证签名人密码
        checkPassword(qmr, studyFormFill.getQmrmm());
        if (studyFormFill.getId() != null) {
            StudyFormFill studyFormFillOld = this.queryInfo(studyFormFill.getId());
            studyFormFillOld.setBdmc(studyFormFill.getBdmc());
            studyFormFillOld.setBdnr(studyFormFill.getBdnr());
            studyFormFillOld.setResource(studyFormFill.getResource());
            studyFormFillOld.setYqResource(studyFormFill.getYqResource());
            studyFormFillOld.setBdzt(StudyFormFillBdztEnum.ytj.getValue());
            studyFormFillOld.setTjsj(new Date());
            if (studyFormFillOld.getSftb().equals(NormalEnum.no.getValue())) {
                studyFormFillOld.setEndDate(new Date());
                studyFormFillOld.setCclist(studyFormFill.getCclist());
                studyFormFillOld.setCzlist(studyFormFill.getCzlist());
            }
            //生成物资
            genResource(studyFormFillOld, studyFormFill.getRemark());
            studyFormFillOld.setSftb(NormalEnum.yes.getValue());
            this.updateById(studyFormFillOld);
            List<ObjectCompareUtil.FieldChange> fieldChanges = ObjectCompareUtil.compareObjectsNotNull(studyFormFillOld, studyFormFill);
            if (fieldChanges.size() > 0) {
                //稽查轨迹
                List<StudyFormFillJcgj> studyFormFillJcgjs = new ArrayList<>();
                for (ObjectCompareUtil.FieldChange fieldChange : fieldChanges) {
                    studyFormFillJcgjs.add(studyFormFillJcgjService.getJcgj(studyFormFillOld.getId(), JcgjlxEnum.xg.getValue(), "修改", JcmcysEnum.orange.getValue(), fieldChange.toString(), fieldChange.toEnString(), qmr, studyFormFill.getRemark()));
                }
                studyFormFillJcgjService.saveBatch(studyFormFillJcgjs);
            }
            //稽查轨迹
            Map<String, String> formData = new LinkedHashMap<>();
            formData.put("备注", studyFormFill.getRemark());
            studyFormFillJcgjService.saveJcgj(studyFormFillOld.getId(), JcgjlxEnum.lc.getValue(), "填写并提交记录", JcmcysEnum.green.getValue(), formData, qmr, null, null);
        } else {
            studyFormFill.setBdzt(StudyFormFillBdztEnum.ytj.getValue());
            studyFormFill.setUserId(SecurityUtils.getUserId());
            studyFormFill.setUserMc(SecurityUtils.getNickName());
            studyFormFill.setSftb(NormalEnum.yes.getValue());
            studyFormFill.setBdbh(getSn(studyFormFill));
            studyFormFill.setTjsj(new Date());
            this.save(studyFormFill);
            //生成物资
            genResource(studyFormFill, studyFormFill.getRemark());
            //稽查轨迹
            Map<String, String> formData = new LinkedHashMap<>();
            formData.put("备注", studyFormFill.getRemark());
            studyFormFillJcgjService.saveJcgj(studyFormFill.getId(), JcgjlxEnum.lc.getValue(), "填写并提交记录", JcmcysEnum.green.getValue(), formData, qmr, null, null);
        }
        //签名信息
        studyFormFillQmxxService.saveQmxx(studyFormFill.getId(), "填写并提交记录", qmr, studyFormFill.getRemark());

    }

    /**
     * 生成物资
     *
     * @param studyFormFill
     * @param remark
     */
    public void genResource(StudyFormFill studyFormFill, String remark) {
        Template template = templateService.getById(studyFormFill.getTemplateId());
        // 处置，存放，用量
        sjService.genResource(studyFormFill, template);
        gyzjService.genResource(studyFormFill, template, remark);
        mjyService.genResource(studyFormFill, template, remark);
        //更新 Resource
        this.updateById(studyFormFill);
    }

    /**
     * 观察
     *
     * @param form
     */
    @Override
    public void gc(StudyFormFillGcForm form) {
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        //验证签名人密码
        checkPassword(qmr, form.getQmrmm());
        if (form.getId() == null || form.getId().longValue() < 0) {
            throw new ServiceException("参数id不正确");
        }
        StudyFormFill studyFormFillOld = this.getById(form.getId());
        if (studyFormFillOld == null) {
            throw new ServiceException("表单不存在或已删除");
        }
        if (!studyFormFillOld.getBdzt().equals(StudyFormFillBdztEnum.tbz.getValue())) {
            throw new ServiceException("表单不是填报状态，不能观察");
        }
        //稽查轨迹
        Map<String, String> formData = new LinkedHashMap<>();
        formData.put("生长情况", form.getQmyy());
        studyFormFillJcgjService.saveJcgj(studyFormFillOld.getId(), JcgjlxEnum.lc.getValue(), form.getQmyy(), JcmcysEnum.orange.getValue(), formData, SecurityUtils.getLoginUser().getSysUser(), form.getRemark(), null);
        //签名信息
        studyFormFillQmxxService.saveQmxx(studyFormFillOld.getId(), form.getQmyy(), qmr, form.getRemark());

    }


    /**
     * 复核通过
     *
     * @param studyFormFill
     */
    @Override
    public void fhtg(StudyFormFill studyFormFill) {
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        //验证签名人密码
        checkPassword(qmr, studyFormFill.getQmrmm());
        if (studyFormFill.getId() == null || studyFormFill.getId().longValue() < 0) {
            throw new ServiceException("参数id不正确");
        }
        StudyFormFill studyFormFillOld = this.getById(studyFormFill.getId());
        if (studyFormFillOld == null) {
            throw new ServiceException("表单不存在或已删除");
        }
        if (!studyFormFillOld.getBdzt().equals(StudyFormFillBdztEnum.ytj.getValue())) {
            throw new ServiceException("表单不是已提交状态，不能复核");
        }
        studyFormFillOld.setBdzt(StudyFormFillBdztEnum.ywcfh.getValue());
        studyFormFillOld.setBdnr(studyFormFill.getBdnr());
        this.updateById(studyFormFillOld);
        //稽查轨迹
        Map<String, String> formData = new LinkedHashMap<>();
        formData.put("原因", studyFormFill.getRemark());
        studyFormFillJcgjService.saveJcgj(studyFormFillOld.getId(), JcgjlxEnum.lc.getValue(), "复核通过", JcmcysEnum.green.getValue(), formData, SecurityUtils.getLoginUser().getSysUser(), null, null);
        //签名信息
        studyFormFillQmxxService.saveQmxx(studyFormFillOld.getId(), "复核通过", qmr, studyFormFill.getRemark());
        //发送通知
        Study study = studyService.getById(studyFormFillOld.getStudyId());
        String url = getUrlQz(study, "tbbd");
        String title = StudyTypeEnum.getEnumByValue(study.getType()).getText() + "【" + study.getName() + "】下填报表单【" + studyFormFillOld.getBdmc() + "】复核通过";
        noticeService.save(title, studyFormFillOld.getUserId(), url);
    }


    /**
     * 复核拒绝
     *
     * @param studyFormFill
     */
    @Override
    public void fhjj(StudyFormFill studyFormFill) {
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        //验证签名人密码
        checkPassword(qmr, studyFormFill.getQmrmm());
        if (studyFormFill.getId() == null || studyFormFill.getId().longValue() < 0) {
            throw new ServiceException("参数id不正确");
        }
        StudyFormFill studyFormFillOld = this.getById(studyFormFill.getId());
        if (studyFormFillOld == null) {
            throw new ServiceException("表单不存在或已删除");
        }
        if (!studyFormFillOld.getBdzt().equals(StudyFormFillBdztEnum.ytj.getValue())) {
            throw new ServiceException("表单不是已提交状态，不能复核");
        }
        studyFormFillOld.setBdzt(StudyFormFillBdztEnum.tbz.getValue());
        studyFormFillOld.setBdnr(studyFormFill.getBdnr());
        this.updateById(studyFormFillOld);
        //稽查轨迹
        Map<String, String> formData = new LinkedHashMap<>();
        formData.put("原因", studyFormFill.getRemark());
        studyFormFillJcgjService.saveJcgj(studyFormFillOld.getId(), JcgjlxEnum.lc.getValue(), "复核拒绝", JcmcysEnum.red.getValue(), formData, SecurityUtils.getLoginUser().getSysUser(), null, null);

        //签名信息
        studyFormFillQmxxService.saveQmxx(studyFormFillOld.getId(), "复核拒绝", qmr, studyFormFill.getRemark());
        //发送通知
        Study study = studyService.getById(studyFormFillOld.getStudyId());
        String url = getUrlQz(study, "tbbd");
        String title = StudyTypeEnum.getEnumByValue(study.getType()).getText() + "【" + study.getName() + "】下填报表单【" + studyFormFillOld.getBdmc() + "】复核拒绝";
        noticeService.save(title, studyFormFillOld.getUserId(), url);

    }

    /**
     * 通过
     *
     * @param studyFormFill
     */
    @Override
    public void tg(StudyFormFill studyFormFill) {
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        //验证签名人密码
        checkPassword(qmr, studyFormFill.getQmrmm());
        if (studyFormFill.getId() == null || studyFormFill.getId().longValue() < 0) {
            throw new ServiceException("参数id不正确");
        }
        StudyFormFill studyFormFillOld = this.getById(studyFormFill.getId());
        if (studyFormFillOld == null) {
            throw new ServiceException("表单不存在或已删除");
        }
        if (!studyFormFillOld.getBdzt().equals(StudyFormFillBdztEnum.ytj.getValue())) {
            throw new ServiceException("表单不是已提交状态，不能复核");
        }
        studyFormFillOld.setBdzt(StudyFormFillBdztEnum.ywc.getValue());
        studyFormFillOld.setBdnr(studyFormFill.getBdnr());
        this.updateById(studyFormFillOld);
        //稽查轨迹
        Map<String, String> formData = new LinkedHashMap<>();
        formData.put("原因", studyFormFill.getRemark());
        studyFormFillJcgjService.saveJcgj(studyFormFillOld.getId(), JcgjlxEnum.lc.getValue(), "免复核通过", JcmcysEnum.green.getValue(), null, SecurityUtils.getLoginUser().getSysUser(), null, null);

        //签名信息
        studyFormFillQmxxService.saveQmxx(studyFormFillOld.getId(), "免复核通过", qmr, studyFormFill.getRemark());
        //发送通知
        Study study = studyService.getById(studyFormFillOld.getStudyId());
        String url = getUrlQz(study, "tbbd");
        String title = StudyTypeEnum.getEnumByValue(study.getType()).getText() + "【" + study.getName() + "】下填报表单【" + studyFormFillOld.getBdmc() + "】免复核通过";
        noticeService.save(title, studyFormFillOld.getUserId(), url);
    }

    /**
     * 审阅
     *
     * @param studyFormFill
     */
    @Override
    public void sy(StudyFormFill studyFormFill) {
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        //验证签名人密码
        checkPassword(qmr, studyFormFill.getQmrmm());
        if (studyFormFill.getId() == null || studyFormFill.getId().longValue() < 0) {
            throw new ServiceException("参数id不正确");
        }
        StudyFormFill studyFormFillOld = this.getById(studyFormFill.getId());
        if (studyFormFillOld == null) {
            throw new ServiceException("表单不存在或已删除");
        }
        if (!(studyFormFillOld.getBdzt().equals(StudyFormFillBdztEnum.ywcfh.getValue()) || studyFormFillOld.getBdzt().equals(StudyFormFillBdztEnum.ywc.getValue()))) {
            throw new ServiceException("表单不是已完成状态，不能审阅");
        }
        studyFormFillOld.setBdnr(studyFormFill.getBdnr());
        this.updateById(studyFormFillOld);
        //稽查轨迹
        Map<String, String> formData = new LinkedHashMap<>();
        formData.put("备注", studyFormFill.getRemark());
        studyFormFillJcgjService.saveJcgj(studyFormFillOld.getId(), JcgjlxEnum.lc.getValue(), "已审阅", JcmcysEnum.green.getValue(), formData, SecurityUtils.getLoginUser().getSysUser(), null, null);
        //签名信息
        studyFormFillQmxxService.saveQmxx(studyFormFillOld.getId(), "已审阅", qmr, studyFormFill.getRemark());
        //发送通知
        Study study = studyService.getById(studyFormFillOld.getStudyId());
        String url = getUrlQz(study, "tbbd");
        String title = StudyTypeEnum.getEnumByValue(study.getType()).getText() + "【" + study.getName() + "】下填报表单【" + studyFormFillOld.getBdmc() + "】已审阅";
        noticeService.save(title, studyFormFillOld.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();
        if(StringUtils.isNoneBlank(form.getZdxgjl())){
            baseMapper.updateBdnrZdxgjl(form.getId(), form.getBdnr(), form.getZdxgjl());
        }else{
            baseMapper.updateBdnr(form.getId(), form.getBdnr());
        }
        //稽查轨迹
        if (StringUtils.isNoneBlank(form.getFiledValue())) {
            JSONArray jsonArray = JSONArray.parseArray(form.getFiledValue());
            List<StudyFormFillJcgj> studyFormFillJcgjs = new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                Map<String, String> formData = new LinkedHashMap<>();
                Map<String, String> formDataEn = new LinkedHashMap<>();
                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"));
                    studyFormFillJcgjs.add(studyFormFillJcgjService.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());
                    studyFormFillJcgjs.add(studyFormFillJcgjService.getJcgj(form.getId(), JcgjlxEnum.bj.getValue(), "填写", JcmcysEnum.green.getValue(), JctUtil.formatStr(formData), StudyFormUtil.getJcnrEn(formDataEn), null, null));
                }

            }
            studyFormFillJcgjService.saveBatch(studyFormFillJcgjs);
        }
    }

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

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

    /**
     * 生成编号
     *
     * @param studyFormFill
     * @return
     */
    public String getSn(StudyFormFill studyFormFill) {
        Study study = studyService.getById(studyFormFill.getStudyId());
        if (study == null) {
            throw new ServiceException("试验不存在或已删除");
        }
        Template template = templateService.getById(studyFormFill.getTemplateId());
        if (template == null) {
            throw new ServiceException("模板不存在或已删除");
        }
        //学科缩写:新增配制计划表：学科简称SD；非试验表单：学科简称GG；麻精药表单：学科简称GSP
        String abbr = "";
        if(studyFormFill.getStudyFormPreId()==null){
            if(study.getType().equals(StudyTypeEnum.sy.getValue())){
                SysDept dep = sysDeptService.selectDeptById(studySubjectService.getById(studyFormFill.getStudySubjectId()).getDeptId());
                if (dep == null) {
                    throw new ServiceException("学科不存在或已删除");
                }
                abbr = dep.getAbbr();
            }
            if(study.getType().equals(StudyTypeEnum.fsy.getValue())){
                abbr = "GG";
            }
            if(study.getType().equals(StudyTypeEnum.mjy.getValue())){
                abbr = "GSP";
            }
        }
        // 有预填的=预填编号+流水号，没有得=模板编号+试验编号+学科缩写+01+流水号
        String pre = studyFormFill.getStudyFormPreId()==null?
                (template.getShowSn() + "-" + study.getSn() + "-" + abbr+"-01")
                :studyFormPreService.getById(studyFormFill.getStudyFormPreId()).getBdbh();
        return pre + snGenService.getNewSn(pre,SnTypeEnum.noDate.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) : "";
    }

}
