package com.zd.chemical.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.LongAdder;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import com.zd.chemical.domain.vo.*;
import com.zd.chemical.mapper.HxpChemicalJoinCabinetMapper;
import com.zd.chemical.mapper.HxpClassifyConfigMapper;
import com.zd.common.core.exception.ServiceException;
import com.zd.common.security.utils.DictUtils;
import com.zd.common.security.utils.SaveUtil;

import com.zd.system.api.domain.SysDictData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zd.chemical.domain.HxpChemicalJoinCabinet;
import com.zd.chemical.service.IHxpChemicalJoinCabinetService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletException;

/**
 * 化学品和机柜关联Service业务层处理
 *
 * @author liubo
 * @date 2022-06-16
 */
@Service
public class HxpChemicalJoinCabinetServiceImpl implements IHxpChemicalJoinCabinetService {
    @Autowired
    private HxpChemicalJoinCabinetMapper hxpChemicalJoinCabinetMapper;
    @Autowired
    private HxpClassifyConfigMapper hxpClassifyConfigMapper;

    /**
     * 查询化学品和机柜关联
     *
     * @param id 化学品和机柜关联主键
     * @return 化学品和机柜关联
     */
    @Override
    public HxpChemicalJoinCabinet selectHxpChemicalJoinCabinetById(Long id) {
        return hxpChemicalJoinCabinetMapper.selectHxpChemicalJoinCabinetById(id);
    }

    /**
     * 查询化学品和机柜关联
     *
     * @param id 化学品和机柜关联主键
     * @return 化学品和机柜关联
     */
    @Override
    public HxpChemicalJoinCabinetVo selByChemical(Long id) {
        List<HxpChemicalJoinCabinet> hxpChemicalJoinCabinetList = hxpChemicalJoinCabinetMapper.selByChemical(id);
        HxpChemicalJoinCabinetVo hxpChemicalJoinCabinetVo = new HxpChemicalJoinCabinetVo();
        hxpChemicalJoinCabinetVo.setChemicalId(id);

        Map <Long, List<HxpChemicalJoinCabinet>> collect = Optional.ofNullable(hxpChemicalJoinCabinetList)
                .filter(a -> a.size() > 0)
                .orElseGet(Collections::emptyList)
                .stream()
                .map(a->{
                    hxpChemicalJoinCabinetVo.setSubId(a.getSubId());
                    return a;
                })
                .collect(Collectors.groupingBy(HxpChemicalJoinCabinet::getCabinetId));

        collect.forEach((key, value) -> {
            HxpChemicalJoinCabinetSon hxpChemicalJoinCabinetSon = new HxpChemicalJoinCabinetSon();
            hxpChemicalJoinCabinetSon.setCabinetId(key);
            hxpChemicalJoinCabinetVo.getChemicalJoinCabinetSonList().add(hxpChemicalJoinCabinetSon);

            Map <BigDecimal, List<HxpChemicalJoinCabinet>> collect2 = Optional.ofNullable(value)
                    .filter(a->a.size()>0)
                    .orElseGet(Collections::emptyList)
                    .stream()
                    .collect(Collectors.groupingBy(HxpChemicalJoinCabinet::getChemicalAmount));

            List<HxpChemicalJoinCabinetGrandSon> hxpChemicalJoinCabinetGrandSonList = new ArrayList<>();
            LongAdder num = new LongAdder();
            collect2.forEach((key2, value2) -> {
                HxpChemicalJoinCabinetGrandSon hxpChemicalJoinCabinetGrandSon = new HxpChemicalJoinCabinetGrandSon();
                hxpChemicalJoinCabinetGrandSon.setChemicalAmount(key2);
                hxpChemicalJoinCabinetVo.getChemicalJoinCabinetSonList().get(hxpChemicalJoinCabinetVo.getChemicalJoinCabinetSonList().size()-1).getHxpChemicalJoinCabinetGrandSonList().add(hxpChemicalJoinCabinetGrandSon);


                Optional.ofNullable(value2)
                        .filter(a->a.size()>0)
                        .orElseGet(Collections::emptyList)
                        .stream()
                        .forEach(v2->{
                            hxpChemicalJoinCabinetGrandSon.setChemicalAmountUnit(v2.getChemicalAmountUnit());

                            HxpChemicalJoinCabinet hxpChemicalJoinCabinet = new HxpChemicalJoinCabinet();
                            hxpChemicalJoinCabinet.setExpireTime(v2.getExpireTime());
                            hxpChemicalJoinCabinetVo.getChemicalJoinCabinetSonList()
                                    .get(hxpChemicalJoinCabinetVo.getChemicalJoinCabinetSonList().size()-1)
                                    .getHxpChemicalJoinCabinetGrandSonList()
                                    .get(num.intValue())
                                    .getChemicalJoinCabinetList().add(hxpChemicalJoinCabinet);

                        });
                num.increment();


            });
        });
        return hxpChemicalJoinCabinetVo;
    }


    /**
     * 查询化学品和机柜关联列表
     *
     * @param hxpChemicalJoinCabinetSearch 化学品和机柜关联
     * @return 化学品和机柜关联
     */
    @Override
    public List<HxpChemicalJoinCabinetListVo> selectHxpChemicalJoinCabinetList(HxpChemicalJoinCabinetSearch hxpChemicalJoinCabinetSearch) {
        return hxpChemicalJoinCabinetMapper.selectHxpChemicalJoinCabinetList(hxpChemicalJoinCabinetSearch);
    }

    /**
     * 新增化学品和机柜关联
     *
     * @param hxpChemicalJoinCabinetVo 化学品和机柜关联
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertHxpChemicalJoinCabinet(HxpChemicalJoinCabinetVo hxpChemicalJoinCabinetVo) {
        //删除化学品下的所有关联数据
//        Long[] ids = new Long[1];
//        ids[0] = hxpChemicalJoinCabinetVo.getChemicalId();
//        hxpChemicalJoinCabinetMapper.delByChemical(ids);
        Optional.ofNullable(hxpChemicalJoinCabinetVo.getChemicalJoinCabinetSonList()).orElseGet(Collections::emptyList)
                .stream().forEach(a-> IntStream.range(0,a.getStorageNum()).forEach(b->{
            HxpChemicalJoinCabinet chemicalJoinCabinet = new HxpChemicalJoinCabinet();
            String localTime =  new Date().getTime()+"";
            chemicalJoinCabinet.setJoinNum(localTime.substring(2));
            chemicalJoinCabinet.setChemicalId(hxpChemicalJoinCabinetVo.getChemicalId());
            chemicalJoinCabinet.setSubId(hxpChemicalJoinCabinetVo.getSubId());
            chemicalJoinCabinet.setCabinetId(a.getCabinetId());
            chemicalJoinCabinet.setChemicalAmount(a.getChemicalAmount());
            chemicalJoinCabinet.setChemicalAmountUnit(a.getChemicalAmountUnit());
//                    chemicalJoinCabinet.setExpireTime(b.getExpireTime());     过期时间作废，不存任何值
            chemicalJoinCabinet.setTare(a.getTare());
            chemicalJoinCabinet.setCabinetlockId(a.getCabinetlockId());
            //设置其他公共字段
            SaveUtil.setCommonAttr(chemicalJoinCabinet);
            hxpChemicalJoinCabinetMapper.insertHxpChemicalJoinCabinet(chemicalJoinCabinet);
        }));

//        Optional.ofNullable(hxpChemicalJoinCabinetVo.getChemicalJoinCabinetSonList()).orElseGet(Collections::emptyList)
//                .stream().forEach(a->{
//                    HxpChemicalJoinCabinet chemicalJoinCabinet = new HxpChemicalJoinCabinet();
//                    String localTime =  new Date().getTime()+"";
//                    chemicalJoinCabinet.setJoinNum(localTime.substring(2));
//                    chemicalJoinCabinet.setChemicalId(hxpChemicalJoinCabinetVo.getChemicalId());
//                    chemicalJoinCabinet.setSubId(hxpChemicalJoinCabinetVo.getSubId());
//                    chemicalJoinCabinet.setCabinetId(a.getCabinetId());
//                    chemicalJoinCabinet.setChemicalAmount(a.getChemicalAmount());
//                    chemicalJoinCabinet.setChemicalAmountUnit(a.getChemicalAmountUnit());
////                    chemicalJoinCabinet.setExpireTime(b.getExpireTime());     过期时间作废，不存任何值
//                    chemicalJoinCabinet.setTare(a.getTare());
//                    //设置其他公共字段
//                    SaveUtil.setCommonAttr(chemicalJoinCabinet);
//                    hxpChemicalJoinCabinetMapper.insertHxpChemicalJoinCabinet(chemicalJoinCabinet);
//        });
        return 1;
    }

    /**
     * 修改化学品和机柜关联
     *
     * @param hxpChemicalJoinCabinet 化学品和机柜关联
     * @return 结果
     */
    @Override
    public int updateHxpChemicalJoinCabinet(HxpChemicalJoinCabinet hxpChemicalJoinCabinet) {
        return hxpChemicalJoinCabinetMapper.updateHxpChemicalJoinCabinet(hxpChemicalJoinCabinet);
    }

    /**
     * 批量删除化学品和机柜关联
     *
     * @param ids 需要删除的化学品和机柜关联主键
     * @return 结果
     */
    @Override
    public int deleteHxpChemicalJoinCabinetByIds(Long[] ids) {
        //这里校验如果关联库存表，提示不能删除。
        if(ids[0]!=null){
            HxpChemicalJoinCabinet hxpChemicalJoinCabinet = new HxpChemicalJoinCabinet();
            hxpChemicalJoinCabinet.setId(ids[0]);
            List<HxpChemicalJoinCabinet> chemicalJoinCabinetList = hxpChemicalJoinCabinetMapper.selectChemicalListById(hxpChemicalJoinCabinet);
            if(chemicalJoinCabinetList.size()>0){
                throw new ServiceException("删除失败，化学品已经绑定库存");
            }
        }

        return hxpChemicalJoinCabinetMapper.deleteHxpChemicalJoinCabinetByIds(ids);
    }

    /**
     * 删除化学品和机柜关联信息
     *
     * @param id 化学品和机柜关联主键
     * @return 结果
     */
    @Override
    public int deleteHxpChemicalJoinCabinetById(Long id) {
        return hxpChemicalJoinCabinetMapper.deleteHxpChemicalJoinCabinetById(id);
    }

    @Override
    public List<AioChemicalVo> selectChemicalVoList(AioChemicalVo aioChemicalVo) {
        List<AioChemicalVo> list = hxpChemicalJoinCabinetMapper.selectChemicalVoList(aioChemicalVo);

        List<SysDictData> proDictDatas = DictUtils.getDictCache("chemical_shape");
        list.forEach(a -> {
            if(StringUtils.isNotBlank(a.getSafeUserId())){
                a.setSafeUserName(hxpChemicalJoinCabinetMapper.queryUserNameBySafeUserId(a.getSafeUserId()));
            }
            if(a.getChemicalClassify() != null){
                a.setClassifyConfig(hxpClassifyConfigMapper.selectHxpClassifyConfigById(a.getChemicalClassify()));
                if(a.getClassifyConfig() != null){
                    a.setVerification(Optional.ofNullable(a.getClassifyConfig().getJoinStatus()).orElse(1));
                }
            }
            for(SysDictData dictData : proDictDatas){
                if(dictData.getDictValue().equals(a.getChemicalShape() + "")){
                    a.setChemicalShapeName(dictData.getDictLabel());
                    break;
                }
            }
        });
        return list;
    }

    /**
     * 批量删除化学品和机柜关联
     *
     * @param ids 需要删除的化学品和机柜关联主键
     * @return 结果
     */
    @Override
    public int delByChemical(Long[] ids) {
        return hxpChemicalJoinCabinetMapper.delByChemical(ids);
    }
}
