package com.dk.mdm.service.ivt.inbound;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dk.common.exception.BaseBusinessException;
import com.dk.common.infrastructure.constant.Constant;
import com.dk.common.infrastructure.enums.ErrorCodeEnum;
import com.dk.common.mapper.BaseMapper;
import com.dk.common.response.ResponseResultUtil;
import com.dk.common.response.ResponseResultVO;
import com.dk.common.service.BaseService;
import com.dk.mdm.infrastructure.convert.ivt.InboundConvert;
import com.dk.mdm.infrastructure.convert.ivt.InboundItemConvert;
import com.dk.mdm.mapper.ivt.InboundItemMapper;
import com.dk.mdm.mapper.ivt.InboundMapper;
import com.dk.mdm.model.pojo.ivt.Inbound;
import com.dk.mdm.model.pojo.ivt.InboundItem;
import com.dk.mdm.model.query.ivt.InboundItemQuery;
import com.dk.mdm.model.response.ivt.InboundItemResponse;
import com.dk.mdm.model.response.ivt.InboundResponse;
import com.dk.mdm.model.vo.ivt.InboundItemVO;
import com.dk.mdm.model.vo.ivt.InboundVO;
import com.dk.mdm.service.common.CommonService;
import com.dk.mdm.service.ivt.inventory.InventoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;


/**
 * @author : 寇珊珊
 * @desc : 盘盈入库业务层
 * @date : 2024/3/7 14:11
 */
@Service
public class InboundCheckService extends BaseService<Inbound> {

    @Override
    public BaseMapper<Inbound> getRepository() {
        return inboundMapper;
    }

    @Autowired
    private InboundMapper inboundMapper;

    @Autowired
    private InboundConvert inboundConvert;

    @Autowired
    private InboundItemMapper inboundItemMapper;

    @Autowired
    private InboundItemConvert inboundItemConvert;


    @Autowired
    private CommonService commonService;

    @Autowired
    private InventoryService inventoryService;


    /**
     * @desc : 盘盈入库新建、库存调整-入库
     * @date : 2024/3/7 14:13
     * 入库中数量/金额  已入库数量/金额  由调用方传入
     * @author : 寇珊珊
     */
    @Transactional(rollbackFor = {Exception.class})
    public InboundVO checkInboundInsert(Map<String, Object> map) {

        //region map转json
        JSONObject total = new JSONObject();
        JSONArray detail = new JSONArray();
        //总单
        if (map.get("total") != null) {
            total = (JSONObject) JSON.toJSON(map.get("total"));
        }
        //明细
        if (map.get("total") != null) {
            detail = (JSONArray) JSON.toJSON(map.get("detail"));
        }
        InboundVO inboundVO = new InboundVO();
        inboundVO = total.toJavaObject(InboundVO.class);
        List<InboundItemVO> inboundItemVOList = detail.toJavaList(InboundItemVO.class);
        inboundVO.setItemList(inboundItemVOList);
        //endregion

        //region  总单
        //获取 id/单号
        Map<String, Object> codeMap = new HashMap<>();
        // 盘盈入库
        if(Constant.IntoType.PROFIT.getName().equals(inboundVO.getIntoType())){
            codeMap = commonService.getUniqueNoteCode(Constant.docNameConstant.INVENTORYPROFITINBOUND.getName(), false);
        }
        //仓库调整
        else{
            codeMap =  commonService.getUniqueNoteCode(Constant.docNameConstant.MOVE.getName(), false);
        }
        inboundVO.setIntoId(codeMap.get("outId").toString()).
                setIntoNo(codeMap.get("outNote").toString());
        //todo  入库类型可能是盘盈可能是库位移动 调用的时候传
//		//入库类型
//		inboundVO.setIntoType(Constant.IntoType.PROFIT.getName());
        //已入库
        inboundVO.setIntoStatus(Constant.IntoStatus.YIRUKU.getName());
        //入库状态等于已入库 更新合计入库数量/金额 = 入库中数量/入库中金额
        inboundVO.setIntoQty(inboundVO.getIntoingQty())
                .setIntoAmt(inboundVO.getIntoingAmt())
                .setIntoingQty(BigDecimal.ZERO)
                .setIntoingAmt(BigDecimal.ZERO)
        ;
        //实体转换
        Inbound inbound = inboundConvert.convertToPo(inboundVO);
        inboundMapper.insert(inbound);
        //endregion

        //region 明细
        //校验明细
        if (inboundVO.getItemList().size() == 0) {
            throw new BaseBusinessException(ErrorCodeEnum.INBOUND_ITEM_NOT_EXIST.getCode(),
                    ErrorCodeEnum.INBOUND_ITEM_NOT_EXIST.getMessage());
        }
        for (InboundItemVO inboundItemVO : inboundVO.getItemList()) {
            //region 明细
            //总单id
            inboundItemVO.setIntoId(inboundVO.getIntoId());
            //入库类型
            inboundItemVO.setIntoType(inboundVO.getIntoType());
            //入库状态等于已入库 更新合计入库数量/金额 = 入库中数量/入库中金额
            inboundItemVO
                    .setIntoQty(inboundItemVO.getIntoingQty())
                    .setIntoAmt(inboundItemVO.getIntoingAmt())
                    .setIntoingQty(BigDecimal.ZERO)
                    .setIntoingAmt(BigDecimal.ZERO)
                    .setCostPrice(inboundItemVO.getPriceInto())
                    .setCostAmt(inboundItemVO.getIntoQty()
                            .multiply(inboundItemVO.getPriceInto()).setScale(2, BigDecimal.ROUND_HALF_UP))
            ;
            //入库状态
            inboundItemVO.setIntoStatus(inboundVO.getIntoStatus());
            //实体转换
            InboundItem inboundItem = inboundItemConvert.convertToPo(inboundItemVO);
            inboundItemMapper.insert(inboundItem);
            inboundItemVO.setItemId(inboundItem.getItemId());
            //endregion

            //region 将库存需要的参数赋值
            inboundItemVO.setInventoryType(Constant.InventoryType.INBOUND.getName());
            //盘盈入库
            if(Constant.IntoType.PROFIT.getName().equals(inboundVO.getIntoType())){
                inboundItemVO.setInventoryDocCode(Constant.InventoryDocCode.INVENTORY_PROFIT.getValue());
            }
            //仓库调整
            else{
                inboundItemVO.setInventoryDocCode(Constant.InventoryDocCode.MOVE.getValue());
            }
            inboundItemVO.setAddOrEditFlag(true);
            //endregion

        }
        //endregion

        //region 修改库存
		Map<String, Object> invMap = new HashMap<>();
		invMap.put("intoDetail", inboundVO.getItemList());
		inventoryService.operatingInventoryInformation(invMap);
        //endregion

        return inboundVO;
    }

    /**
     * @desc : 作废
     * @date : 2024/4/16 13:27
     * @author : 寇珊珊
     */
    @Transactional(rollbackFor = {Exception.class})
    public ResponseResultVO<?> inboundRepeal(String fromId) {
        //region  查询总单  查询明细
        //根据来源id查询 此条入库单的数据还未更改前的数据
        InboundResponse inboundResponse = inboundMapper.selectByFromId(fromId);
        //根据总单id查询
        List<InboundItemResponse> inboundItemResponseList = inboundItemMapper.selectByCond(new InboundItemQuery().setIntoId(inboundResponse.getIntoId()));
        //endregion

        //region 修改明细
        for (InboundItemResponse inboundItemResponse : inboundItemResponseList) {
            //region 将库存需要的参数赋值
            inboundItemResponse.setInventoryType(Constant.InventoryType.INBOUND.getName());
            //盘盈入库
            if(Constant.IntoType.PROFIT.getName().equals(inboundItemResponse.getIntoType())){
                inboundItemResponse.setInventoryDocCode(Constant.InventoryDocCode.INVENTORY_PROFIT.getValue());
            }
            //仓库调整
            else{
                inboundItemResponse.setInventoryDocCode(Constant.InventoryDocCode.MOVE.getValue());
            }
            inboundItemResponse.setIntoQty(inboundItemResponse.getIntoQty().negate());
            inboundItemResponse.setIntoAmt(inboundItemResponse.getIntoAmt().negate());
            //endregion

            //赋值
            InboundItem inboundItem = new InboundItem();
            inboundItem.setItemId(inboundItemResponse.getItemId());
            inboundItem.setFlgValid(false);
            //修改
            inboundItemMapper.update(inboundItem,
                    new UpdateWrapper<InboundItem>().lambda()
                            .eq(InboundItem::getItemId, UUID.fromString(inboundItem.getItemId()))
            );
        }
        //endregion

        //region  修改入库总单
        Inbound inbound = new Inbound();
        inbound.setIntoId(inboundResponse.getIntoId());
        inbound.setFlgValid(false);
        //修改
        inboundMapper.update(inbound,
                new UpdateWrapper<Inbound>().lambda().eq(Inbound::getIntoId, UUID.fromString(inbound.getIntoId()))
        );
        //endregion

        //region 库存
        Map<String, Object> map = new HashMap<>();
        map.put("delIntoDetail", inboundItemResponseList);
        inventoryService.operatingInventoryInformation(map);
        //endregion

        return ResponseResultUtil.success();
    }


}
