package com.dk.mdm.service.ivt;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dk.common.infrastructure.annotaiton.Pagination;
import com.dk.common.infrastructure.constant.Constant;
import com.dk.common.infrastructure.enums.ErrorCodeEnum;
import com.dk.common.mapper.BaseMapper;
import com.dk.common.model.pojo.PageList;
import com.dk.common.response.ResponseCodeEnum;
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.common.CommonMapper;
import com.dk.mdm.mapper.ivt.InboundItemMapper;
import com.dk.mdm.mapper.ivt.InboundMapper;
import com.dk.mdm.mapper.pur.PurchaseItemMapper;
import com.dk.mdm.mapper.pur.PurchaseMapper;
import com.dk.mdm.model.pojo.ivt.Inbound;
import com.dk.mdm.model.pojo.ivt.InboundItem;
import com.dk.mdm.model.pojo.ivt.IntoReturn;
import com.dk.mdm.model.pojo.pur.Purchase;
import com.dk.mdm.model.pojo.pur.PurchaseItem;
import com.dk.mdm.model.query.ivt.InboundItemQuery;
import com.dk.mdm.model.query.ivt.InboundQuery;
import com.dk.mdm.model.query.ivt.IntoReturnItemQuery;
import com.dk.mdm.model.query.ivt.IntoReturnQuery;
import com.dk.mdm.model.response.ivt.InboundItemResponse;
import com.dk.mdm.model.response.ivt.InboundResponse;
import com.dk.mdm.model.response.ivt.IntoReturnItemResponse;
import com.dk.mdm.model.response.ivt.IntoReturnResponse;
import com.dk.mdm.model.response.pur.PurchaseItemResponse;
import com.dk.mdm.model.response.pur.PurchaseResponse;
import com.dk.mdm.model.vo.ivt.InboundItemVO;
import com.dk.mdm.model.vo.ivt.InboundVO;
import com.dk.mdm.model.vo.ivt.IntoReturnVO;
import com.dk.mdm.service.common.CommonService;
import com.dk.mdm.service.ivt.inbound.InboundPurchaseReturnService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Service("inboundReturn")
@Transactional
public class InboundReturnService extends BaseService<Inbound> {

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

    @Resource
    private InboundMapper inboundMapper;

    @Autowired
    private InboundItemMapper inboundItemMapper;

    @Autowired
    private PurchaseMapper purchaseMapper;

    @Autowired
    private PurchaseItemMapper purchaseItemMapper;

    @Autowired
    private CommonService commonService;

    @Autowired
    private InboundConvert inboundConvert;

    @Autowired
    private InboundItemConvert inboundItemConvert;
    @Autowired
    private InboundPurchaseReturnService inboundPurchaseReturnService;

    @Autowired
    private CommonMapper commonMapper;

    @Pagination
    public ResponseResultVO<PageList<InboundResponse>> selectByCond(InboundQuery inboundQuery) {
        return super.mergeListWithCount(inboundQuery, inboundMapper.selectByInboundReturnCond(inboundQuery), inboundMapper.countByInboundReturnCond(inboundQuery));
    }

    /**
     * @desc : 查看来源单据,总单加明细  采购退货用
     * @author : 于继渤
     * @date : 2024/3/6 10:36
     */
    public ResponseResultVO<?> selectInboundReturnById(String intoId) {
        //根据id查询
        InboundResponse inboundResponse = inboundMapper.selectInboundReturnById(intoId);
        //不存在
        if (inboundResponse == null) {
            return ResponseResultUtil.error(ErrorCodeEnum.INBOUND_CANNOT_BE_EMPTY.getCode(),
                    ErrorCodeEnum.INBOUND_CANNOT_BE_EMPTY.getMessage());
        }

        Map<String, Object> dataInfo = new HashMap<>();
        dataInfo.put("data", inboundResponse);
        //查询明细
        List<InboundItemResponse> inboundItemResponselist = inboundItemMapper.selectByInboundReturnCond(new InboundItemQuery().setIntoId(intoId).setFlgValid(true));
        dataInfo.put("dataItem", inboundItemResponselist);
        return ResponseResultUtil.success(dataInfo);
    }

    /**
     * @desc : 新建采购退货
     * @author : 于继渤
     * @date : 2023/1/5 9:39
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public ResponseResultVO<?> insert(InboundVO inboundVO) {
        //校验明细长度
        List<InboundItemVO> itemList = inboundVO.getItemList();
        //明细不存在
        if (itemList == null || itemList.size() == 0) {
            //返回 采购退货明细不可为空，请重新操作
            return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.PURCHASE_RETURN_DETAIL_NOT_EXIST.getMessage());
        }

        //查询采购订单
        PurchaseResponse purchaseResponse = purchaseMapper.selectById(inboundVO.getSPurId());

        if (purchaseResponse != null) {
            //反写采购订单退货数量、金额
            purchaseMapper.updateAmount(new Purchase().setPurId(inboundVO.getSPurId())
                    .setReturnQty(purchaseResponse.getReturnQty().add(inboundVO.getIntoingQty().abs()))
                    .setReturnAmt(purchaseResponse.getReturnAmt().add(inboundVO.getIntoingAmt().abs()))
            );
        }

        //反写入库单退货数量金额
        InboundResponse inboundResponse = inboundMapper.selectById(inboundVO.getFromId());
        if (inboundResponse != null) {
            inboundMapper.updateAmount(new Inbound().setIntoId(inboundVO.getFromId())
                    .setReturnQty(inboundResponse.getReturnQty().add(inboundVO.getIntoingQty().abs()))
                    .setReturnAmt(inboundResponse.getReturnAmt().add(inboundVO.getIntoingAmt().abs())));
        }


        //反写入库订单明细、反写订单明细
        for (InboundItemVO inboundItemVO : itemList) {
            //查询采购订单明细数据
            PurchaseItemResponse purchaseItemResponse = purchaseItemMapper.selectById(inboundItemVO.getSPurItemId());
            if (purchaseItemResponse != null) {
                //反写订单明细退货数量和退货金额
                purchaseItemMapper.updateAmount(
                        new PurchaseItem()
                                .setItemId(inboundItemVO.getSPurItemId())
                                .setReturnQty(purchaseItemResponse.getReturnQty().add(inboundItemVO.getIntoingQty().abs().setScale(6, BigDecimal.ROUND_HALF_UP)))
                                .setReturnAmt(purchaseItemResponse.getReturnAmt().add(inboundItemVO.getIntoingAmt().abs().setScale(6, BigDecimal.ROUND_HALF_UP)))

                );
            }


            //根据退货明细中入库明细id查询入库明细数据
            InboundItemResponse inboundItemResponse = inboundItemMapper.selectById(inboundItemVO.getSIntoItemId());
            if (purchaseItemResponse != null) {
                inboundItemMapper.updateAmount(
                        new InboundItem()
                                .setItemId(inboundItemVO.getSIntoItemId())
                                .setReturnQty(inboundItemResponse.getReturnQty().add(inboundItemVO.getIntoingQty().abs().setScale(6, BigDecimal.ROUND_HALF_UP)))
                                .setReturnAmt(inboundItemResponse.getReturnAmt().add(inboundItemVO.getIntoingAmt().abs().setScale(6, BigDecimal.ROUND_HALF_UP)))
                );
            }

        }
        inboundPurchaseReturnService.purchaseReturnInboundInsert(inboundVO);
        return ResponseResultUtil.success();
    }

    /**
     * @desc : 编辑
     * @date : 2022/6/28 16:58
     * @author : 于继渤
     */
    @Transactional(rollbackFor = {Exception.class})
    public ResponseResultVO<String> update(InboundVO inboundVO) {

        //查询编辑之前的采退单
        InboundResponse inboundReturnResponse = inboundMapper.selectById(inboundVO.getIntoId());
        //原入库单
        if (inboundReturnResponse.getFromId() != null) {
            //反写上游入库单退货数量金额
            InboundResponse sInboundResponse = inboundMapper.selectById(inboundReturnResponse.getFromId());
            if (sInboundResponse != null) {
                inboundMapper.updateAmount(new Inbound()
                        .setIntoId(sInboundResponse.getIntoId())
                        .setReturnQty(sInboundResponse.getReturnQty().subtract(inboundReturnResponse.getIntoQty().abs()).add(inboundVO.getIntoingQty().abs()))
                        .setReturnAmt(sInboundResponse.getReturnAmt().subtract(inboundReturnResponse.getIntoAmt().abs()).add(inboundVO.getIntoingAmt().abs())));
            }
            //反写上游采购单退货数量金额
            if (sInboundResponse.getFromId() != null) {
                //查询采购单
                PurchaseResponse purchaseResponse = purchaseMapper.selectById(sInboundResponse.getFromId());
                purchaseMapper.updateAmount(
                        new Purchase()
                                .setPurId(purchaseResponse.getPurId())
                                .setReturnQty(sInboundResponse.getReturnQty().subtract(inboundReturnResponse.getIntoQty().abs()).add(inboundVO.getIntoingQty().abs()))
                                .setReturnAmt(sInboundResponse.getReturnAmt().subtract(inboundReturnResponse.getIntoAmt().abs()).add(inboundVO.getIntoingAmt().abs())));
            }
        }

        //校验明细
        if (inboundVO.getItemList() != null && inboundVO.getItemList().size() > 0) {
            for (InboundItemVO inboundItemVO : inboundVO.getItemList()) {   //查询原退货明细
                InboundItemResponse inboundItem = inboundItemMapper.selectById(inboundItemVO.getItemId());
                if (inboundItemVO.getSIntoItemId() != null) {

                    //查询上游入库明细
                    InboundItemResponse inboundItemReturnResponse = inboundItemMapper.selectById(inboundItemVO.getSIntoItemId());
                    if (inboundItemReturnResponse != null) {
                        //修改入库单明细 已入库退货数量/金额
                        inboundItemMapper.updateAmount(new InboundItem()
                                .setItemId(inboundItemReturnResponse.getItemId())
                                .setReturnQty(inboundItemReturnResponse.getReturnQty().subtract(inboundItem.getIntoQty().abs()).add(inboundItemVO.getIntoingQty().abs()))
                                .setReturnAmt(inboundItemReturnResponse.getReturnAmt().subtract(inboundItem.getIntoAmt().abs()).add(inboundItemVO.getIntoingAmt().abs())));
                    }

                }
                //修改上游采购明细
                if (inboundItemVO.getSPurItemId() != null) {
                    //查询上游采购订单明细
                    PurchaseItemResponse purchaseItemResponse = purchaseItemMapper.selectById(inboundItemVO.getSPurItemId());
                    purchaseItemMapper.updateAmount(
                            new PurchaseItem()
                                    .setItemId(purchaseItemResponse.getItemId())
                                    .setReturnQty(purchaseItemResponse.getReturnQty().subtract(inboundItem.getIntoQty().abs()).add(inboundItemVO.getIntoingQty().abs()))
                                    .setReturnAmt(purchaseItemResponse.getReturnAmt().subtract(inboundItem.getIntoAmt().abs()).add(inboundItemVO.getIntoingAmt().abs())));
                }
            }
        }

        //删除明细
        if (inboundVO.getDeleteItemList() != null && inboundVO.getDeleteItemList().size() > 0) {
            for (InboundItemVO inboundItemVO : inboundVO.getDeleteItemList()) {
                //查询原退货明细
                InboundItemResponse inboundItem = inboundItemMapper.selectById(inboundItemVO.getItemId());
                if (inboundItemVO.getSIntoItemId() != null) {
                    //查询上游入库明细
                    InboundItemResponse inboundItemReturnResponse = inboundItemMapper.selectById(inboundItemVO.getSIntoItemId());
                    if (inboundItemReturnResponse != null) {
                        //修改入库单明细 已入库退货数量/金额
                        inboundItemMapper.updateAmount(new InboundItem()
                                .setItemId(inboundItemReturnResponse.getItemId())
                                .setReturnQty(inboundItemReturnResponse.getReturnQty().subtract(inboundItem.getIntoQty().abs()))
                                .setReturnAmt(inboundItemReturnResponse.getReturnAmt().subtract(inboundItem.getIntoAmt().abs())));
                    }

                }
                if (inboundItemVO.getSPurItemId() != null) {
                    //查询上游采购订单明
                    PurchaseItemResponse purchaseItemResponse = purchaseItemMapper.selectById(inboundItemVO.getSPurItemId());
                    purchaseItemMapper.updateAmount(
                            new PurchaseItem()
                                    .setItemId(purchaseItemResponse.getItemId())
                                    .setReturnQty(purchaseItemResponse.getReturnQty().subtract(inboundItem.getIntoQty().abs()))
                                    .setReturnAmt(purchaseItemResponse.getReturnAmt().subtract(inboundItem.getIntoAmt().abs())));
                }
            }
        }


        inboundPurchaseReturnService.purchaseReturnInboundUpdate(inboundVO);
        return ResponseResultUtil.success();
    }

    /**
     * @desc : 作废
     * @date : 2022/6/28 16:58
     * @author : 于继渤
     */
    @Transactional(rollbackFor = {Exception.class})
    public ResponseResultVO<String> cancel(InboundVO inboundVO) {
        //查询当前 采退入库单 负
        InboundResponse inboundResponse = inboundMapper.selectInboundReturnById(inboundVO.getIntoId());
        if (inboundResponse.getFromId() != null) {
            //反写上游入库单退货数量金额
            InboundResponse sInboundResponse = inboundMapper.selectById(inboundResponse.getFromId());
            if (sInboundResponse != null) {
                inboundMapper.updateAmount(new Inbound().setIntoId(sInboundResponse.getIntoId())
                        .setReturnQty(sInboundResponse.getReturnQty().subtract(inboundResponse.getIntoQty().abs()))
                        .setReturnAmt(sInboundResponse.getReturnAmt().subtract(inboundResponse.getIntoAmt().abs())));
            }
            //反写上游采购订单退货数量金额
            if (sInboundResponse.getFromId() != null) {
                //查询采购单
                PurchaseResponse purchaseResponse = purchaseMapper.selectById(sInboundResponse.getFromId());
                purchaseMapper.updateAmount(
                        new Purchase().setReturnQty(purchaseResponse.getReturnQty().subtract(inboundResponse.getIntoQty().abs()))
                                .setReturnAmt(purchaseResponse.getReturnAmt().subtract(inboundResponse.getIntoAmt().abs())).setPurId(purchaseResponse.getPurId())
                );
            }

        }
        //查询退货明细
        List<InboundItemResponse> inboundItemResponses = inboundItemMapper.selectByCond(new InboundItemQuery().setIntoId(inboundResponse.getIntoId()));
        for (InboundItemResponse inboundItemRespons : inboundItemResponses) {

            if (inboundItemRespons.getSIntoItemId() != null) {
                //查询源入库单明细
                InboundItemResponse inboundItem = inboundItemMapper.selectById(inboundItemRespons.getSIntoItemId());
                //修改入库单明细 已入库退货数量/金额
                inboundItemMapper.updateAmount(new InboundItem()
                        .setItemId(inboundItem.getItemId())
                        .setReturnQty(inboundItem.getReturnQty().subtract(inboundItemRespons.getIntoQty().abs()))
                        .setReturnAmt(inboundItem.getReturnAmt().subtract(inboundItemRespons.getIntoAmt().abs()))
                );
            }
            if (inboundItemRespons.getSPurItemId() != null) {
                //查询采购单明细
                PurchaseItemResponse purchaseItemResponse = purchaseItemMapper.selectById(inboundItemRespons.getSPurItemId());
                //修改采购单明细 已入库退货数量/金额
                purchaseItemMapper.updateAmount(
                        new PurchaseItem()
                                .setItemId(purchaseItemResponse.getItemId())
                                .setReturnQty(purchaseItemResponse.getReturnQty().subtract(inboundItemRespons.getIntoQty().abs()))
                                .setReturnAmt(purchaseItemResponse.getReturnAmt().subtract(inboundItemRespons.getIntoAmt().abs()))
                );
            }
        }
        inboundPurchaseReturnService.purchaseReturnInboundRepeal(inboundVO.getIntoId());
        return ResponseResultUtil.success();
    }


    /**
     * @desc : 办理
     * @date : 2022/6/28 16:58
     * @author : 于继渤
     */
    @Transactional(rollbackFor = {Exception.class})
    public ResponseResultVO<String> returnHandle(InboundVO inboundVO) {
        //校验明细长度
        List<InboundItemVO> itemList = inboundVO.getItemList();
        //明细不存在
        if (itemList == null || itemList.size() == 0) {
            //返回 采购退货明细不可为空，请重新操作
            return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.PURCHASE_RETURN_DETAIL_NOT_EXIST.getMessage());
        }
        inboundVO.setReturnQty(inboundVO.getReturnQty().abs());
        inboundVO.setReturnAmt(inboundVO.getReturnAmt().abs());
        if (inboundVO.getFromId() != null) {
            //查询采购订单
            PurchaseResponse purchaseResponse = purchaseMapper.selectById(inboundVO.getFromId()); //采购订单id

            //反写采购订单已入库退货数量、金额
            purchaseMapper.updateAmount(new Purchase().setPurId(inboundVO.getFromId())
                    .setReturnQty(purchaseResponse.getReturnQty().add(inboundVO.getReturnQty()))
                    .setReturnAmt(purchaseResponse.getReturnAmt().add(inboundVO.getReturnAmt()))
            );
        }


        //反写入库订单明细、反写订单明细
        for (InboundItemVO inboundItemVO : itemList) {
            inboundItemVO.setReturnQty(inboundItemVO.getReturnQty().abs());
            inboundItemVO.setReturnAmt(inboundItemVO.getReturnAmt().abs());
            //根据退货明细中入库明细id查询入库明细数据
            if (inboundItemVO.getSIntoItemId() != null) {
                InboundItemResponse inboundItemResponse = inboundItemMapper.selectById(inboundItemVO.getSIntoItemId()); //原入库单明细id
                BigDecimal returnQty = inboundItemResponse.getReturnQty().add(inboundItemVO.getReturnQty().setScale(6, BigDecimal.ROUND_HALF_UP));
                BigDecimal returnAmt = inboundItemResponse.getReturnAmt().add(inboundItemVO.getReturnAmt().setScale(6, BigDecimal.ROUND_HALF_UP));

                //反写入库单退货数量金额
                InboundResponse inboundResponse = inboundMapper.selectById(inboundItemVO.getSIntoId()); //原入库单id
                inboundMapper.updateAmount(new Inbound().setIntoId(inboundItemVO.getSIntoId())
                        .setReturnQty(inboundResponse.getReturnQty().add(returnQty))
                        .setReturnAmt(inboundResponse.getReturnAmt().add(returnAmt)));
                inboundItemMapper.updateAmount(
                        new InboundItem()
                                .setItemId(inboundItemResponse.getSIntoItemId())
                                .setReturnQty(returnQty)
                                .setReturnAmt(returnAmt)
                );
            }
            if (inboundItemVO.getSPurItemId() != null) {
                //反写订单出库明细 退货数量和退货金额
                //查询采购订单明细数据
                PurchaseItemResponse purchaseItemResponse = purchaseItemMapper.selectById(inboundItemVO.getSPurItemId());
                //反写订单明细退货数量和退货金额
                purchaseItemMapper.updateAmount(
                        new PurchaseItem()
                                .setItemId(inboundItemVO.getSPurItemId())
                                .setReturnQty(purchaseItemResponse.getReturnQty().add(inboundItemVO.getReturnQty().setScale(6, BigDecimal.ROUND_HALF_UP)))
                                .setReturnAmt(purchaseItemResponse.getReturnAmt().add(inboundItemVO.getReturnAmt().setScale(6, BigDecimal.ROUND_HALF_UP)))
                );
            }


            inboundItemVO.setIntoingQty(inboundItemVO.getReturnQty().abs());
            inboundItemVO.setIntoingAmt(inboundItemVO.getReturnAmt().abs());
            inboundItemVO.setReturnQty(inboundItemVO.getReturnQty().multiply(new BigDecimal(-1)));
            inboundItemVO.setReturnAmt(inboundItemVO.getReturnAmt().multiply(new BigDecimal(-1)));
        }

        inboundVO.setReturnQty(inboundVO.getReturnQty().multiply(new BigDecimal(-1)));
        inboundVO.setReturnAmt(inboundVO.getReturnAmt().multiply(new BigDecimal(-1)));
        //调用办理
        inboundPurchaseReturnService.saleReturnHandleInbound(inboundVO);
        return ResponseResultUtil.success();
    }

    /**
     * @desc : 采购退货入库撤销
     * @date : 2022/6/28 16:58
     * @author : 于继渤
     */
    @Transactional(rollbackFor = {Exception.class})
    public ResponseResultVO<String> inboundReturnCancel(InboundVO inboundVO) {
        inboundPurchaseReturnService.saleReturnInboundCancel(inboundVO);
        return ResponseResultUtil.success();
    }

    public static void main(String[] args) {
        BigDecimal a = new BigDecimal(-1000);
        BigDecimal b = new BigDecimal(-990);
        System.out.println(a.subtract(b));
    }

}
