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.enums.zykgl.JyztEnum;
import com.hxhq.business.enums.zykgl.ZjztEnum;
import com.hxhq.business.form.gsp.CzForm;
import com.hxhq.business.form.study.StudyCellSearchForm;
import com.hxhq.business.service.ICellJcgjService;
import com.hxhq.business.service.IStudyCellService;
import com.hxhq.business.utils.JctUtil;
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.CellMapper;
import com.hxhq.business.service.ICellService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 细胞Service业务层处理
 *
 * @author hxhq
 * @date 2026-01-12
 */
@Service
public class CellServiceImpl extends ServiceImpl<CellMapper, Cell> implements ICellService {
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ICellJcgjService cellJcgjService;

    @Autowired
    private IStudyCellService studyCellService;

    @Override
    public List<Cell> queryStudyList(StudyCellSearchForm form) {
        QueryWrapper<Cell> queryWrapper = Wrappers.query();
        queryWrapper.eq("c.del_flag", 0);
        if (form.getStudyId() != null) {
            queryWrapper.eq("c.study_id", form.getStudyId());
        }
        if (StringUtils.isNotEmpty(form.getMc())) {
            queryWrapper.like("c.mc", form.getMc());
        }
        if (StringUtils.isNotEmpty(form.getBh())) {
            queryWrapper.like("c.bh", form.getBh());
        }
        if (StringUtils.isNotEmpty(form.getLy())) {
            queryWrapper.like("c.ly", form.getLy());
        }
        if (StringUtils.isNotEmpty(form.getStartDate())) {
            queryWrapper.ge("c.sxr", form.getStartDate());
        }
        if (StringUtils.isNotEmpty(form.getEndDate())) {
            queryWrapper.le("c.sxr", form.getEndDate());
        }
        if (StringUtils.isNotEmpty(form.getStudyName())) {
            queryWrapper.like("s.name", form.getStudyName());
        }
        queryWrapper.orderByDesc("c.bh");
        return baseMapper.queryStudyList(queryWrapper);
    }


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

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


        LinkedHashMap<String, String> jcnrMap = new LinkedHashMap<>();
        jcnrMap.put("处置方式", form.getCzfs());
        jcnrMap.put("处置量", form.getCzl());
        jcnrMap.put("原因", form.getRemark());

        LinkedHashMap<String, String> jcnrEnMap = new LinkedHashMap<>();
        jcnrEnMap.put("Dispose Method", form.getCzfs());
        jcnrEnMap.put("Amount", form.getCzl());
        jcnrEnMap.put("Reason", form.getRemark());
        cellJcgjService.saveJcgj(cell, 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.Cell.getValue()) ? true : false;
        SysUser qmr = sysUserService.selectUserById(SecurityUtils.getUserId());

        String empty = "[]";
        List<Cell> cellList = new ArrayList<>();
        Map<String, Cell> cellMap = new HashMap<>(16);

        LinkedList<CellJcgj> 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.Cell.getValue() == p.getType())).collect(Collectors.toList());
            if (tmp.size() > 0) {
                List<String> bhList = tmp.stream().map(StudyFormFillResource::getBh).collect(Collectors.toList());
                LambdaQueryWrapper<Cell> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.in(Cell::getBh, bhList);
                cellList = this.list(queryWrapper);
                for (Cell cell : cellList) {
                    cellMap.put(cell.getBh(), cell);
                }
                for (StudyFormFillResource studyFormFillResource : studyFormFillResourceList) {
                    Cell cell = cellMap.get(studyFormFillResource.getBh());
                    if (mark) {
                        if (studyFormFillResource.getType() == null) {
                            if (studyFormFill.getSftb().equals(NormalEnum.no.getValue())) {
                                Boolean isAdd = false;
                                if (cell == null) {
                                    cell = new Cell();
                                    isAdd = true;
                                }
                                cell.setStudyId(studyFormFill.getStudyId());
                                cell.setStudyFormId(studyFormFill.getId());
                                cell.setMc(studyFormFillResource.getMc());
                                cell.setBh(studyFormFillResource.getBh());
                                cell.setTj(studyFormFillResource.getKc());
                                cell.setTjdw(studyFormFillResource.getKcdw());
                                cell.setLy(studyFormFillResource.getLy());
                                cell.setSxr(DateUtils.parseDate(studyFormFillResource.getSxrq()));
                                this.saveOrUpdate(cell);
                                if (isAdd) {
                                    cellList.add(cell);
                                }
                                cellMap.put(cell.getBh(), cell);
                                jcgjList.add(cellJcgjService.genJcgj(cell.getId(), JcgjlxEnum.lc.getValue(), "配制完成", "Formulation Completed", JcmcysEnum.green.getValue(), null, null, qmr));
                            }
                            studyFormFillResource.setType(StudyFormFillResourceTypeEnum.sj.getValue());
                        }
                    }
                    if (cell != null) {
                        studyFormFillResource.setMc(cell.getMc());
                        studyFormFillResource.setBh(cell.getBh());
                        studyFormFillResource.setKc(cell.getTj());
                        studyFormFillResource.setKcdw(cell.getTjdw());
                        studyFormFillResource.setLy(cell.getLy());
                        studyFormFillResource.setSxrq(cell.getSxr() != null ? DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", cell.getSxr()) : "");
                        cellMap.put(cell.getBh(), cell);
                    }
                }
            }
            if (cellMap.size() > 0 && studyFormFill.getSftb().equals(NormalEnum.no.getValue())) {
                cz(studyFormFill, cellMap, jcgjList, qmr);
            }
        }
        if (jcgjList.size() > 0) {
            cellJcgjService.saveBatch(jcgjList);
        }
        if (cellList.size() > 0) {
            studyCellService.saveBatch(studyFormFill.getStudyId(), cellList);
        }
    }

    /**
     * 处置
     *
     * @param studyFormFill
     * @param cellMap
     * @param jcgjList
     * @param qmr
     */
    private void cz(StudyFormFill studyFormFill, Map<String, Cell> cellMap, List<CellJcgj> jcgjList, SysUser qmr) {
        String empty = "[]";
        // 处置，库存全变为0
        String czlist = studyFormFill.getCzlist();
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(czlist) && !org.apache.commons.lang3.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()) {
                    Cell cell = cellMap.get(bh);
                    if (cell != null) {
                        list.add(cell.getId());
                        // 稽查轨迹
                        LinkedHashMap<String, String> jcnrMap = new LinkedHashMap<>();
                        jcnrMap.put("处置方式", studyFormFillCz.getCzfs());
                        jcnrMap.put("处置量", cell.getTj() + cell.getTjdw());

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

                        CellJcgj jcgj = cellJcgjService.genJcgj(cell.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");
                }
            }
        }
    }
}
