package com.yh.saas.plugin.yiliangyiyun.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.yh.saas.common.support.util.IdGenerator;
import com.yh.saas.plugin.yiliangyiyun.constant.StatusEnum;
import com.yh.saas.plugin.yiliangyiyun.entity.*;
import com.yh.saas.plugin.yiliangyiyun.entity.view.WarehouseNumView;
import com.yh.saas.plugin.yiliangyiyun.mapper.TurnInfoMapper;
import com.yh.saas.plugin.yiliangyiyun.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * <p>
 * 记录折转信息 服务实现类
 * </p>
 *
 * @author Gdc
 * @since 2022-01-10
 */
@Service
public class TurnInfoServiceImpl extends ServiceImpl<TurnInfoMapper, TurnInfo> implements ITurnInfoService {
    @Autowired
    private IWarehousePositionInfoService warehousePositionInfoService;
    @Autowired
    IWarehousePositionStorageInfoService warehousePositionStorageInfoService;
    @Autowired
    IWarehouseInOutInfoService warehouseInOutInfoService;
    @Autowired
    IWarehouseInOutDetailService warehouseInOutDetailService;
    /**
     * 折转
     * @param  turnInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addTurn(TurnInfo turnInfo){
        String relationId=IdGenerator.generateUUID();
        turnInfo.setId(IdGenerator.generateUUID());
        turnInfo.setRelationId(relationId);
        turnInfo.setAfterType("折转出库");
        WarehousePositionStorageInfo warehousePositionStorageInfo = warehousePositionStorageInfoService.selectOne(new EntityWrapper<WarehousePositionStorageInfo>()
                .eq("position_id",turnInfo.getPositionId())
                .eq("goods_name_key",turnInfo.getBeforeGoodsNameKey()));
        if (warehousePositionStorageInfo!=null){
            warehousePositionStorageInfo.setStorage(warehousePositionStorageInfo.getStorage()-turnInfo.getBeforeWeight());
            warehousePositionStorageInfoService.updateById(warehousePositionStorageInfo);
        }
        WarehouseInOutInfo warehouseInOutInfo=new WarehouseInOutInfo();
        warehouseInOutInfo.setId(IdGenerator.generateUUID());
        warehouseInOutInfo.setBaseId(turnInfo.getBaseId());
        warehouseInOutInfo.setWarehouseName(turnInfo.getWarehouseName());
        warehouseInOutInfo.setPositionId(turnInfo.getPositionId());
        warehouseInOutInfo.setBinNumber(turnInfo.getBeforeBinNo());
        warehouseInOutInfo.setInOutFlag("1");
        warehouseInOutInfo.setGoodsName(turnInfo.getBeforeGoodsName());
        warehouseInOutInfo.setGoodsNameKey(turnInfo.getBeforeGoodsNameKey());
        warehouseInOutInfo.setNetWeight(Double.valueOf(turnInfo.getBeforeWeight()));
        warehouseInOutInfo.setAgent(turnInfo.getBackOffice());
        warehouseInOutInfo.setStatusFlag(StatusEnum.SUBMITTED.getFlag());
        warehouseInOutInfo.setStatus(StatusEnum.SUBMITTED.getName());
        warehouseInOutInfo.setInOutDate(new Date());
        warehouseInOutInfo.setInOutType("折转出库");
        warehouseInOutInfoService.insert(warehouseInOutInfo);
        WarehouseInOutDetail warehouseInOutDetail=new WarehouseInOutDetail();
        warehouseInOutDetail.setInfoId(warehouseInOutInfo.getId());
        warehouseInOutDetail.setId(IdGenerator.generateUUID());
        warehouseInOutDetailService.insert(warehouseInOutDetail);
        boolean one=this.insert(turnInfo);
        turnInfo.setId(IdGenerator.generateUUID());
        turnInfo.setAfterType("折转入库");
        turnInfo.setRelationId(relationId);
        WarehousePositionStorageInfo warehousePositionStorageInfo1 = warehousePositionStorageInfoService.selectOne(new EntityWrapper<WarehousePositionStorageInfo>()
                .eq("position_id",turnInfo.getAfterPositionId())
                .eq("goods_name_key",turnInfo.getAfterGoodsNameKey()));
        if (warehousePositionStorageInfo1!=null){
            warehousePositionStorageInfo1.setStorage(warehousePositionStorageInfo1.getStorage()+turnInfo.getAfterWeight());
            warehousePositionStorageInfoService.updateById(warehousePositionStorageInfo1);
        }
        else {
            if (turnInfo.getAfterPositionId()!=null) {
                WarehousePositionStorageInfo warehousePositionStorageInfo2 = new WarehousePositionStorageInfo();
                warehousePositionStorageInfo2.setId(IdGenerator.generateUUID());
                warehousePositionStorageInfo2.setPositionId(turnInfo.getAfterPositionId());
                warehousePositionStorageInfo2.setBinNumber(turnInfo.getAfterBinNo());
                warehousePositionStorageInfo2.setGoodsNameKey(turnInfo.getAfterGoodsNameKey());
                warehousePositionStorageInfo2.setGoodsName(turnInfo.getAfterGoodsName());
                warehousePositionStorageInfo2.setStorage(Double.valueOf(String.valueOf(turnInfo.getAfterWeight())));
                warehousePositionStorageInfoService.insert(warehousePositionStorageInfo2);
            }
        }
        WarehouseInOutInfo warehouseInOutInfo1=new WarehouseInOutInfo();
        warehouseInOutInfo1.setId(IdGenerator.generateUUID());
        warehouseInOutInfo1.setBaseId(turnInfo.getBaseId());
        warehouseInOutInfo1.setWarehouseName(turnInfo.getWarehouseName());
        warehouseInOutInfo1.setPositionId(turnInfo.getAfterPositionId());
        warehouseInOutInfo1.setBinNumber(turnInfo.getAfterBinNo());
        warehouseInOutInfo1.setInOutFlag("2");
        warehouseInOutInfo1.setGoodsName(turnInfo.getAfterGoodsName());
        warehouseInOutInfo1.setGoodsNameKey(turnInfo.getAfterGoodsNameKey());
        warehouseInOutInfo1.setNetWeight(Double.valueOf(turnInfo.getAfterWeight()));
        warehouseInOutInfo1.setAgent(turnInfo.getBackOffice());
        warehouseInOutInfo1.setStatusFlag(StatusEnum.SUBMITTED.getFlag());
        warehouseInOutInfo1.setStatus(StatusEnum.SUBMITTED.getName());
        warehouseInOutInfo1.setInOutDate(new Date());
        warehouseInOutInfo1.setInOutType("折转入库");
        warehouseInOutInfoService.insert(warehouseInOutInfo1);
        WarehouseInOutDetail warehouseInOutDetail1=new WarehouseInOutDetail();
        warehouseInOutDetail1.setInfoId(warehouseInOutInfo1.getId());
        warehouseInOutDetail1.setId(IdGenerator.generateUUID());
        warehouseInOutDetailService.insert(warehouseInOutDetail1);
        boolean two=this.insert(turnInfo);
        // 假如 都成功返回ok
        if (one && two) {
            return "OK";
        } else {
            return "NG";
        }
    }

    /**
     * 仓位货名下拉列表
     * @param id
     * @return
     */
    @Override
    public List<WarehouseNumView> getPositionAndGoodsName(String id){
        // 子集合
        List<WarehouseNumView> warehouseNumViewList = new ArrayList<>();
        WarehousePositionInfo warehousePositionInfo=warehousePositionInfoService.selectById(id);
        //常用库
        if (warehousePositionInfo!=null){
            List<WarehousePositionStorageInfo> warehousePositionStorageInfoList = warehousePositionStorageInfoService.selectList(new EntityWrapper<WarehousePositionStorageInfo>()
                    .eq("position_id", warehousePositionInfo.getId())
                    .groupBy("goods_name_key")
                    .eq("delete_flag", "0"));
            for (WarehousePositionStorageInfo warehousePositionStorageInfo : warehousePositionStorageInfoList) {
                WarehouseNumView warehouseNumView = new WarehouseNumView();
                warehouseNumView.setGoodsName(warehousePositionStorageInfo.getGoodsName());
                warehouseNumView.setGoodsNameKey(warehousePositionStorageInfo.getGoodsNameKey());
                warehouseNumView.setStorage(String.valueOf(warehousePositionStorageInfo.getStorage()));
                warehouseNumViewList.add(warehouseNumView);
            }
        }
        else {
            //定义入库
            String inNetWeight = "";
            // 查询入库数量
            List<WarehouseInOutInfo> warehouseInOutInfoList = warehouseInOutInfoService.selectList(new EntityWrapper<WarehouseInOutInfo>()
                    .eq("base_id", id).eq("delete_flag", "0")
                    .eq("status_flag", "3").eq("in_out_flag", "2").groupBy("goods_name_key").orderBy("goods_name_key"));
            if (!CollectionUtils.isEmpty(warehouseInOutInfoList)) {
                for (WarehouseInOutInfo warehouseInOutInfo : warehouseInOutInfoList) {
                    WarehouseNumView warehouseNumView = new WarehouseNumView();
                    // 查询入库数量
                    List<WarehouseInOutInfo> warehouseInOutInfoAllList = warehouseInOutInfoService.selectList(new EntityWrapper<WarehouseInOutInfo>()
                            .eq("base_id", id).eq("in_out_flag", "2").eq("delete_flag", "0")
                            .eq("status_flag", "3").eq("goods_name_key", warehouseInOutInfo.getGoodsNameKey()));

                    if (!CollectionUtils.isEmpty(warehouseInOutInfoAllList)) {
                        Float netWeight = 0f;
                        for (WarehouseInOutInfo warehouse : warehouseInOutInfoAllList) {
                            netWeight = Float.valueOf(netWeight) + Float.valueOf(String.valueOf(warehouse.getNetWeight()));
                        }
                        warehouseNumView.setGoodsName(warehouseInOutInfoAllList.get(0).getGoodsName());
                        warehouseNumView.setGoodsNameKey(warehouseInOutInfoAllList.get(0).getGoodsNameKey());
                        warehouseNumView.setInNetWeight(String.valueOf(netWeight));
                        warehouseNumView.setStorage(String.valueOf(netWeight));
                        if (StringUtils.isEmpty(inNetWeight)) {
                            inNetWeight = "0";
                        }
                        inNetWeight = String.valueOf(Float.valueOf(inNetWeight) + netWeight);
                    }
                    warehouseNumViewList.add(warehouseNumView);
                }
            }
            //定义出库
            String outNetWeight = "";
            // 查询出库数量
            List<WarehouseInOutInfo> warehouseInOutInfos = warehouseInOutInfoService.selectList(new EntityWrapper<WarehouseInOutInfo>()
                    .eq("base_id", id).eq("delete_flag", "0")
                    .eq("status_flag", "3").eq("in_out_flag", "1").groupBy("goods_name_key").orderBy("goods_name_key"));
            if (!CollectionUtils.isEmpty(warehouseInOutInfos)) {
                for (WarehouseInOutInfo warehouseInOutInfo : warehouseInOutInfos) {
                    Float netWeight = 0f;
                    outNetWeight = "0";
                    List<WarehouseInOutInfo> warehouseInOutInfoAllList = warehouseInOutInfoService.selectList(new EntityWrapper<WarehouseInOutInfo>()
                            .eq("status_flag", "3").eq("delete_flag", "0")
                            .eq("base_id", id).eq("in_out_flag", "1").eq("goods_name_key", warehouseInOutInfo.getGoodsNameKey()));
                    if (!CollectionUtils.isEmpty(warehouseInOutInfoAllList)) {
                        for (WarehouseInOutInfo warehouse : warehouseInOutInfoAllList) {
                            netWeight = Float.valueOf(netWeight) +Float.valueOf(String.valueOf(warehouse.getNetWeight()));
                        }
                        if (StringUtils.isEmpty(outNetWeight)) {
                            outNetWeight = "0";
                        }
                        outNetWeight = String.valueOf(Float.valueOf(outNetWeight) + netWeight);
                    }
                    List<WarehouseNumView> warehouseNumViewListNew = new ArrayList<>();
                    for (WarehouseNumView warehouseNumView : warehouseNumViewList) {
                        if (warehouseNumView.getGoodsName().equals(warehouseInOutInfo.getGoodsName())) {
                            warehouseNumView.setOutNetWeight(outNetWeight);
                            warehouseNumView.setStorage(String.valueOf(Double.valueOf(warehouseNumView.getInNetWeight()) - Double.valueOf(warehouseNumView.getOutNetWeight())));
                            if (Double.valueOf(warehouseNumView.getStorage()) <= 0) {
                                warehouseNumViewListNew.add(warehouseNumView);
                            }
                        }
                    }
                    warehouseNumViewList.removeAll(warehouseNumViewListNew);
                }
            }
        }
        return warehouseNumViewList;
    }

    /**
     * 折转列表
     * @param  turnInfo
     * @return
     */
    @Override
    public Page<TurnInfo> selectTurnInfo(TurnInfo turnInfo) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (turnInfo.getCurrentPage() - 1)
                * turnInfo.getPageSize());
        //公司id
//        pageView.put("compId",turnInfo.getCompId());
        pageView.put("baseId", turnInfo.getBaseId());
        pageView.put("pageSize", turnInfo.getPageSize());
        pageView.put("currentPage", turnInfo.getCurrentPage());
        // 查询折转记录总数
        Integer dataCount = baseMapper.getCountByCondition(pageView);
        List<TurnInfo> dataList = baseMapper.getListByCondition(pageView);
        Page<TurnInfo> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(turnInfo.getCurrentPage());
        page.setSize(turnInfo.getPageSize());
        return page;
    }
}
