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.domain.StudyFormPlan;
import com.hxhq.business.dto.study.StudyFormPlanListDto;
import com.hxhq.business.enums.SnTypeEnum;
import com.hxhq.business.enums.study.StudyFormPlanBdztEnum;
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.StudyFormPlanSearchForm;
import com.hxhq.business.form.study.StudyFormUpdateForm;
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.StudyFormPlanMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 试验-配置计划Service业务层处理
 *
 * @author hxhq
 * @date 2025-12-29
 */
@Service
public class StudyFormPlanServiceImpl extends ServiceImpl<StudyFormPlanMapper, StudyFormPlan> implements IStudyFormPlanService {
    @Autowired
    private IStudyFormPlanJcgjService studyFormPlanJcgjService;
    @Autowired
    private IStudyFormPlanQmxxService studyFormPlanQmxxService;
    @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<StudyFormPlanListDto> queryList(StudyFormPlanSearchForm form) {
        QueryWrapper<StudyFormPlan> 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 (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.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 StudyFormPlan queryInfo(Long id) {
        if (id == null || id.longValue() < 0) {
            throw new ServiceException("参数id不正确");
        }
        return baseMapper.queryInfo(id);
    }


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

        //稽查轨迹
        Map<String, String> formData = new LinkedHashMap<>();
        formData.put("新归属人", studyFormPlan.getUserMc());
        formData.put("原归属人", studyFormPlanOld.getUserMc());
        formData.put("原因", studyFormPlan.getRemark());
        studyFormPlanJcgjService.saveJcgj(studyFormPlanOld.getId(), JcgjlxEnum.lc.getValue(), "更换归属人", JcmcysEnum.orange.getValue(), formData, qmr, null, null);
        //签名信息
        studyFormPlanQmxxService.saveQmxx(studyFormPlanOld.getId(), "更换归属人", qmr, studyFormPlan.getRemark());
        //发送通知
        Study study = studyService.getById(studyFormPlanOld.getStudyId());
        String url = getUrlQz(study,"syxx");
        String title = StudyTypeEnum.getEnumByValue(study.getType()).getText()+"【"+study.getName()+"】下配置计划表【"+studyFormPlanOld.getBdmc()+"】已更换您为归属人";
        noticeService.save(title,studyFormPlanOld.getUserId(),url);

    }

    /**
     * 保存
     *
     * @param studyFormPlan
     */
    @Override
    public StudyFormPlan bc(StudyFormPlan studyFormPlan) {
        StudyFormPlan result = null;
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        if (studyFormPlan.getId() != null) {
            StudyFormPlan studyFormPlanOld = this.queryInfo(studyFormPlan.getId());
            if (studyFormPlanOld == null) {
                throw new ServiceException("信息不存在或已删除");
            }
            if (!qmr.getUserId().equals(studyFormPlanOld.getUserId())) {
                throw new ServiceException("只能操作自己的表单");
            }
            studyFormPlanOld.setBdmc(studyFormPlan.getBdmc());
            studyFormPlanOld.setTemplateId(studyFormPlan.getTemplateId());
            studyFormPlanOld.setBdnr(studyFormPlan.getBdnr());
            studyFormPlanOld.setBdzt(StudyFormPlanBdztEnum.tbz.getValue());
            this.updateById(studyFormPlanOld);
            List<ObjectCompareUtil.FieldChange> fieldChanges = ObjectCompareUtil.compareObjectsNotNULL(studyFormPlanOld, studyFormPlan);
            if (fieldChanges.size() == 0) {
                //稽查轨迹
                List<StudyFormPlanJcgj> studyFormPlanJcgjs = new ArrayList<>();
                for (ObjectCompareUtil.FieldChange fieldChange : fieldChanges) {
                    studyFormPlanJcgjs.add(studyFormPlanJcgjService.getJcgj(studyFormPlan.getId(), JcgjlxEnum.xg.getValue(), "修改", JcmcysEnum.orange.getValue(), fieldChange.toString(), fieldChange.toEnString(), SecurityUtils.getLoginUser().getSysUser(), studyFormPlan.getRemark()));
                }
                studyFormPlanJcgjService.saveBatch(studyFormPlanJcgjs);
            }
            result = studyFormPlanOld;
        } else {
            studyFormPlan.setBdzt(StudyFormPlanBdztEnum.tbz.getValue());
            studyFormPlan.setUserId(qmr.getUserId());
            studyFormPlan.setUserMc(qmr.getNickName());
            studyFormPlan.setBdbh(getSn(studyFormPlan));
            studyFormPlan.setUserMcEn(qmr.getUserName());
            this.save(studyFormPlan);
            //稽查轨迹
            Map<String, String> formData = new LinkedHashMap<>();
            formData.put("备注", studyFormPlan.getRemark());
            studyFormPlanJcgjService.saveJcgj(studyFormPlan.getId(), JcgjlxEnum.lc.getValue(), "填写并保存记录", JcmcysEnum.green.getValue(), null, qmr, studyFormPlan.getRemark(), null);
            result = studyFormPlan;
        }
        //签名信息
        studyFormPlanQmxxService.saveQmxx(studyFormPlan.getId(), "填写并保存记录", qmr, studyFormPlan.getRemark());
        return baseMapper.queryInfo(result.getId());
    }

    /**
     * 仅保存
     *
     * @param studyFormPlan
     */
    @Override
    public StudyFormPlan bcOnly(StudyFormPlan studyFormPlan) {
        StudyFormPlan result = null;
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        if (studyFormPlan.getId() != null) {
            StudyFormPlan studyFormPlanOld = this.queryInfo(studyFormPlan.getId());
            if (studyFormPlanOld == null) {
                throw new ServiceException("信息不存在或已删除");
            }
            if (!qmr.getUserId().equals(studyFormPlanOld.getUserId())) {
                throw new ServiceException("只能操作自己的表单");
            }
            studyFormPlanOld.setBdmc(studyFormPlan.getBdmc());
            studyFormPlanOld.setTemplateId(studyFormPlan.getTemplateId());
            studyFormPlanOld.setBdnr(studyFormPlan.getBdnr());
            studyFormPlanOld.setBdzt(StudyFormPlanBdztEnum.tbz.getValue());
            this.updateById(studyFormPlanOld);
            result = studyFormPlanOld;
        } else {
            studyFormPlan.setBdzt(StudyFormPlanBdztEnum.tbz.getValue());
            studyFormPlan.setUserId(qmr.getUserId());
            studyFormPlan.setUserMc(qmr.getNickName());
            studyFormPlan.setBdbh(getSn(studyFormPlan));
            studyFormPlan.setUserMcEn(qmr.getUserName());
            this.save(studyFormPlan);
            result = studyFormPlan;
        }
        return baseMapper.queryInfo(result.getId());
    }



    /**
     * 提交
     *
     * @param studyFormPlan
     */
    @Override
    public void tj(StudyFormPlan studyFormPlan) {
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        //验证签名人密码
        checkPassword(qmr, studyFormPlan.getQmrmm());
        if (studyFormPlan.getId() == null) {
            studyFormPlan.setUserId(SecurityUtils.getUserId());
            studyFormPlan.setUserMc(SecurityUtils.getNickName());
            studyFormPlan.setBdbh(getSn(studyFormPlan));
        }
        studyFormPlan.setBdzt(StudyFormPlanBdztEnum.ytj.getValue());
        studyFormPlan.setTjsj(new Date());
        this.saveOrUpdate(studyFormPlan);
        //通知 todo
        //稽查轨迹
        Map<String, String> formData = new LinkedHashMap<>();
        formData.put("备注", studyFormPlan.getRemark());
        studyFormPlanJcgjService.saveJcgj(studyFormPlan.getId(), JcgjlxEnum.lc.getValue(), "填写并提交记录", JcmcysEnum.green.getValue(), null, qmr, studyFormPlan.getRemark(), null);
        //签名信息
        studyFormPlanQmxxService.saveQmxx(studyFormPlan.getId(), "填写并提交记录", qmr, studyFormPlan.getRemark());

    }


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


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


    /**
     * 审阅
     *
     * @param studyFormPlan
     */
    @Override
    public void sy(StudyFormPlan studyFormPlan) {
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        //验证签名人密码
        checkPassword(qmr, studyFormPlan.getQmrmm());
        if (studyFormPlan.getId() == null || studyFormPlan.getId().longValue() < 0) {
            throw new ServiceException("参数id不正确");
        }
        StudyFormPlan studyFormPlanOld = this.getById(studyFormPlan.getId());
        if (studyFormPlanOld == null) {
            throw new ServiceException("表单不存在或已删除");
        }
        if (!studyFormPlanOld.getBdzt().equals(StudyFormPlanBdztEnum.ywcfh.getValue())) {
            throw new ServiceException("表单不是已完成（经复核）状态，不能审阅");
        }
        studyFormPlanOld.setBdnr(studyFormPlan.getBdnr());
        this.updateById(studyFormPlanOld);
        //稽查轨迹
        studyFormPlanJcgjService.saveJcgj(studyFormPlanOld.getId(), JcgjlxEnum.lc.getValue(), "已审阅", JcmcysEnum.green.getValue(), null, qmr, studyFormPlan.getRemark(), null);
        //签名信息
        studyFormPlanQmxxService.saveQmxx(studyFormPlanOld.getId(), "已审阅", qmr, studyFormPlan.getRemark());
        //发送通知
        Study study = studyService.getById(studyFormPlanOld.getStudyId());
        String url = getUrlQz(study,"syxx");
        String title = StudyTypeEnum.getEnumByValue(study.getType()).getText()+"【"+study.getName()+"】下配置计划表【"+studyFormPlanOld.getBdmc()+"】已审阅";
        noticeService.save(title,studyFormPlanOld.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();
        //更新表单内容
        baseMapper.updateBdnr(form.getId(), form.getBdnr(),form.getZdxgjl());
        //稽查轨迹
        if (StringUtils.isNoneBlank(form.getFiledValue())) {

            JSONObject jsonObject = JSONObject.parseObject(form.getFiledValue());
            Map<String, String> formData = new LinkedHashMap<>();
            Map<String, String> formDataEn = new LinkedHashMap<>();
            List<StudyFormPlanJcgj> studyFormPlanJcgjs = 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"));
                studyFormPlanJcgjs.add(studyFormPlanJcgjService.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());
                studyFormPlanJcgjs.add(studyFormPlanJcgjService.getJcgj(form.getId(), JcgjlxEnum.xg.getValue(), "填写", JcmcysEnum.green.getValue(), JctUtil.formatStr(formData), StudyFormUtil.getJcnrEn(formDataEn), null, null));
            }
            studyFormPlanJcgjService.saveBatch(studyFormPlanJcgjs);
        }

    }

    /**
     * 更新复核意见
     */
    @Override
    public void updateFhyjjl(StudyFormUpdateForm form) {
        SysUser qmr = SecurityUtils.getLoginUser().getSysUser();
        //更新复核意见
        baseMapper.updateFhyjjl(form.getId(), form.getFhyjjl());
        StudyFormPlan studyFormPlanOld = this.queryInfo(form.getId());
        studyFormPlanOld.setFhyjjl(form.getFhyjjl());
        this.updateById(studyFormPlanOld);
        Map<String, String> formData = new LinkedHashMap<>();
        Map<String, String> formDataEn = new LinkedHashMap<>();
        List<StudyFormPlanJcgj> studyFormPlanJcgjs = 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"));
            studyFormPlanJcgjs.add(studyFormPlanJcgjService.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"));
            studyFormPlanJcgjs.add(studyFormPlanJcgjService.getJcgj(form.getId(), JcgjlxEnum.lc.getValue(), "意见回复", JcmcysEnum.blue.getValue(), JctUtil.formatStr(formData), StudyFormUtil.getJcnrEn(formDataEn), qmr, null));
        }
        studyFormPlanJcgjService.saveBatch(studyFormPlanJcgjs);
    }

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

    /**
     * 生成编号
     * @param studyFormPlan
     * @return
     */
    public String getSn(StudyFormPlan studyFormPlan){
        Study study=studyService.getById(studyFormPlan.getStudyId());
        if(study==null){
            throw new ServiceException("试验不存在或已删除");
        }
        Template template=templateService.getById(studyFormPlan.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):"";
    }

}