package com.hxhq.business.service.impl;

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

import cn.hutool.json.JSONUtil;
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.StudyFormFillCz;
import com.hxhq.business.dto.study.StudyFormFillResource;
import com.hxhq.business.enums.NormalEnum;
import com.hxhq.business.enums.study.StudyFormFillResourceTypeEnum;
import com.hxhq.business.enums.zykgl.JcgjlxEnum;
import com.hxhq.business.enums.zykgl.JcmcysEnum;
import com.hxhq.business.form.gsp.CzForm;
import com.hxhq.business.form.study.StudyCellSearchForm;
import com.hxhq.business.service.IBacteriaJcgjService;
import com.hxhq.business.service.IStudyBacteriaService;
import com.hxhq.business.utils.JctUtil;
import com.hxhq.business.utils.UnitTools;
import com.hxhq.common.core.exception.ServiceException;
import com.hxhq.common.core.utils.DateUtils;
import com.hxhq.common.core.utils.StringUtils;
import com.hxhq.common.security.utils.SecurityUtils;
import com.hxhq.system.api.domain.SysUser;
import com.hxhq.system.service.ISysUserService;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hxhq.business.mapper.BacteriaMapper;
import com.hxhq.business.service.IBacteriaService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 细菌Service业务层处理
 *
 * @author hxhq
 * @date 2026-01-12
 */
@Service
public class BacteriaServiceImpl extends ServiceImpl<BacteriaMapper, Bacteria> implements IBacteriaService
{

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IBacteriaJcgjService bacteriaJcgjService;

    @Autowired
    private IStudyBacteriaService studyBacteriaService;

    @Override
    public List<Bacteria> queryStudyList(StudyCellSearchForm form) {
        QueryWrapper<Bacteria> queryWrapper = Wrappers.query();
        queryWrapper.eq("b.del_flag", 0);

        if(StringUtils.isNotEmpty(form.getMc())) {
            queryWrapper.like("b.mc", form.getMc());
        }
        if(StringUtils.isNotEmpty(form.getBh())) {
            queryWrapper.like("b.bh", form.getBh());
        }
        if(StringUtils.isNotEmpty(form.getLy())) {
            queryWrapper.like("b.ly", form.getLy());
        }
        if(StringUtils.isNotEmpty(form.getStartDate())) {
            queryWrapper.ge("b.sxr", form.getStartDate());
        }
        if(StringUtils.isNotEmpty(form.getEndDate())) {
            queryWrapper.le("b.sxr", form.getEndDate());
        }
        if(StringUtils.isNotEmpty(form.getStudyName())) {
            queryWrapper.like("s.name", form.getStudyName());
        }
        if (StringUtils.isNotEmpty(form.getStudySn())) {
            queryWrapper.like("s.sn", form.getStudySn());
        }
        queryWrapper.orderByDesc("b.bh");
        if(form.getStudyId() != null) {
            queryWrapper.eq("b.study_id", form.getStudyId())
                    .eq("sb.study_id", form.getStudyId());
            return baseMapper.queryStudyList(queryWrapper);

        } else {
            return baseMapper.queryList(queryWrapper);
        }
    }

    @Override
    public void cz(CzForm form) {
        SysUser qmr = sysUserService.selectUserById(form.getQmrId());
        sysUserService.checkPassword(qmr, form.getQmrmm(), true);

        Bacteria bacteria = this.getById(form.getId());
        if(bacteria == null) {
            throw new ServiceException("细菌不存在或已删除");
        }
        if(!NumberUtils.isParsable(form.getCzl())) {
            throw new ServiceException("请输入正确的处置量");
        }
        BigDecimal tj = new BigDecimal(bacteria.getTj());
        BigDecimal czl = new BigDecimal(form.getCzl());
        tj = tj.subtract(czl);
        bacteria.setTj(tj.toString());
        this.updateById(bacteria);


        LinkedHashMap<String, String> jcnrMap = new LinkedHashMap<>();
        jcnrMap.put("处置方式", form.getCzfs());
        jcnrMap.put("处置量", bacteria.getTj() + bacteria.getTjdw());

        LinkedHashMap<String, String> jcnrEnMap = new LinkedHashMap<>();
        jcnrEnMap.put("Dispose Method", form.getCzfs());
        jcnrEnMap.put("Amount", bacteria.getTj() + bacteria.getTjdw());

        bacteriaJcgjService.saveJcgj(bacteria, JcgjlxEnum.lc.getValue(), "处置", "Dispose",
                JcmcysEnum.blue.getValue(), JctUtil.formatStr(jcnrMap), JctUtil.formatStr(jcnrEnMap), qmr);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void genResource(StudyFormFill studyFormFill, Template template) {
        Boolean mark = template.getProduct().equals(StudyFormFillResourceTypeEnum.Bacteria.getValue()) ? true : false;
        SysUser qmr = sysUserService.selectUserById(SecurityUtils.getUserId());

        String empty = "[]";
        List<Bacteria> bacteriaList = new ArrayList<>();
        Map<String, Bacteria> bacteriaMap = new HashMap<>(16);

        LinkedList<BacteriaJcgj> jcgjList = new LinkedList<>();

        String resource = studyFormFill.getResource();
        if (StringUtils.isNotEmpty(resource) && !StringUtils.equals(empty, resource)) {
            List<StudyFormFillResource> studyFormFillResourceList = JSONUtil.toList(resource, StudyFormFillResource.class);
            List<StudyFormFillResource> tmp = studyFormFillResourceList.stream().filter(p -> (p.getType() == null && mark) || (p.getType() != null && StudyFormFillResourceTypeEnum.Bacteria.getValue() == p.getType())).collect(Collectors.toList());
            if (tmp.size() > 0) {
                List<String> bhList = tmp.stream().map(StudyFormFillResource::getBh).collect(Collectors.toList());
                LambdaQueryWrapper<Bacteria> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.in(Bacteria::getBh, bhList);
                bacteriaList = this.list(queryWrapper);
                for (Bacteria bacteria : bacteriaList) {
                    bacteriaMap.put(bacteria.getBh(), bacteria);
                }
                for (StudyFormFillResource studyFormFillResource : studyFormFillResourceList) {
                    Bacteria bacteria = bacteriaMap.get(studyFormFillResource.getBh());
                    if (mark) {
                        if (studyFormFillResource.getType() == null) {
                            if (studyFormFill.getSftb().equals(NormalEnum.no.getValue())) {
                                Boolean isAdd = false;
                                if (bacteria == null) {
                                    bacteria = new Bacteria();
                                    isAdd = true;
                                }
                                bacteria.setStudyId(studyFormFill.getStudyId());
                                bacteria.setStudyFormId(studyFormFill.getId());
                                bacteria.setMc(studyFormFillResource.getMc());
                                bacteria.setBh(studyFormFillResource.getBh());
                                bacteria.setTj(studyFormFillResource.getKc());
                                bacteria.setTjdw(studyFormFillResource.getKcdw());
                                bacteria.setLy(studyFormFillResource.getLy());
                                bacteria.setSxr(DateUtils.parseDate(studyFormFillResource.getSxrq()));
                                this.saveOrUpdate(bacteria);
                                if (isAdd) {
                                    bacteriaList.add(bacteria);
                                }
                                bacteriaMap.put(bacteria.getBh(), bacteria);
                                jcgjList.add(bacteriaJcgjService.genJcgj(bacteria.getId(), JcgjlxEnum.lc.getValue(), "配制完成", "Formulation Completed", JcmcysEnum.green.getValue(), null, null, qmr));
                            }
                            studyFormFillResource.setType(StudyFormFillResourceTypeEnum.sj.getValue());
                        }
                    }
                    if (bacteria != null) {
                        studyFormFillResource.setMc(bacteria.getMc());
                        studyFormFillResource.setBh(bacteria.getBh());
                        studyFormFillResource.setKc(bacteria.getTj());
                        studyFormFillResource.setKcdw(bacteria.getTjdw());
                        studyFormFillResource.setLy(bacteria.getLy());
                        studyFormFillResource.setSxrq(bacteria.getSxr() != null ? DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", bacteria.getSxr()) : "");
                        bacteriaMap.put(bacteria.getBh(), bacteria);
                        syl(studyFormFillResource, bacteria, jcgjList, qmr);
                    }
                }
            }
            if (bacteriaMap.size() > 0 && studyFormFill.getSftb().equals(NormalEnum.no.getValue())) {
                cz(studyFormFill, bacteriaMap, jcgjList, qmr);
            }
        }
        if (jcgjList.size() > 0) {
            bacteriaJcgjService.saveBatch(jcgjList);
        }
        if (bacteriaList.size() > 0) {
            studyBacteriaService.saveBatch(studyFormFill.getStudyId(), bacteriaList);
        }
    }

    /**
     * 处置
     *
     * @param studyFormFill
     * @param bacteriaMap
     * @param jcgjList
     * @param qmr
     */
    private void cz(StudyFormFill studyFormFill, Map<String, Bacteria> bacteriaMap, List<BacteriaJcgj> jcgjList, SysUser qmr) {
        String empty = "[]";
        // 处置，库存全变为0
        String czlist = studyFormFill.getCzlist();
        if (StringUtils.isNotEmpty(czlist) && !StringUtils.equals(empty, czlist)) {
            List<StudyFormFillCz> studyFormFillCzList = JSONUtil.toList(czlist, StudyFormFillCz.class);
            for (StudyFormFillCz studyFormFillCz : studyFormFillCzList) {
                List<Long> list = new ArrayList<>();
                for (String bh : studyFormFillCz.getList()) {
                    Bacteria bacteria = bacteriaMap.get(bh);
                    if (bacteria != null) {
                        list.add(bacteria.getId());
                        // 稽查轨迹
                        LinkedHashMap<String, String> jcnrMap = new LinkedHashMap<>();
                        jcnrMap.put("处置方式", studyFormFillCz.getCzfs());
                        jcnrMap.put("处置量", bacteria.getTj() + bacteria.getTjdw());

                        LinkedHashMap<String, String> jcnrEnMap = new LinkedHashMap<>();
                        jcnrEnMap.put("Dispose Method", studyFormFillCz.getCzfs());
                        jcnrEnMap.put("Amount", bacteria.getTj() + bacteria.getTjdw());

                        BacteriaJcgj jcgj = bacteriaJcgjService.genJcgj(bacteria.getId(), JcgjlxEnum.lc.getValue(), "处置", "Dispose",
                                JcmcysEnum.green.getValue(), JctUtil.formatStr(jcnrMap), JctUtil.formatStr(jcnrEnMap), qmr);
                        jcgjList.add(jcgj);
                    }
                }
                if (list.size() > 0) {
                    baseMapper.updateKcBatch(list, "0");
                }
            }
        }
    }

    private void syl(StudyFormFillResource studyFormFillResource, Bacteria bacteria, List<BacteriaJcgj> jcgjList,  SysUser qmr) {
        // 使用
        String syl = studyFormFillResource.getSyl();
        if (StringUtils.isNotEmpty(syl) && NumberUtils.isParsable(syl)) {
            String kc = UnitTools.subTj(bacteria.getTj(), bacteria.getTjdw(), syl, studyFormFillResource.getSyldw());
            baseMapper.updateKc(bacteria.getId(), kc);

            // 使用稽查轨迹s
            Map<String, String> jcnrMap = new LinkedHashMap<>();
            jcnrMap.put("使用量", syl + studyFormFillResource.getSyldw());

            Map<String, String> jcnrEnMap = new LinkedHashMap<>();
            jcnrEnMap.put("Usage Amount", syl + studyFormFillResource.getSyldw());

            BacteriaJcgj jcgj = bacteriaJcgjService.genJcgj(bacteria.getId(), JcgjlxEnum.lc.getValue(), "使用", "Usage",
                    JcmcysEnum.green.getValue(), JctUtil.formatStr(jcnrMap), JctUtil.formatStr(jcnrEnMap), qmr);
            jcgjList.add(jcgj);
        }
    }
}
