package com.fjhx.victoriatourist.service.purchase.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.common.constant.SourceConstant;
import com.fjhx.common.utils.Assert;
import com.fjhx.purchase.entity.purchase.po.Purchase;
import com.fjhx.purchase.service.purchase.PurchaseService;
import com.fjhx.victoriatourist.entity.logistics.po.LogisticsDetails;
import com.fjhx.victoriatourist.entity.logistics.po.LogisticsInfos;
import com.fjhx.victoriatourist.entity.purchase.dto.PurchaseBackDto;
import com.fjhx.victoriatourist.entity.purchase.dto.PurchaseBackSelectDto;
import com.fjhx.victoriatourist.entity.purchase.po.PurchaseBack;
import com.fjhx.victoriatourist.entity.purchase.po.PurchaseBackDetails;
import com.fjhx.victoriatourist.entity.purchase.vo.PurchaseBackDetailsVo;
import com.fjhx.victoriatourist.entity.purchase.vo.PurchaseBackVo;
import com.fjhx.victoriatourist.mapper.purchase.PurchaseBackMapper;
import com.fjhx.victoriatourist.service.logistics.LogisticsDetailsService;
import com.fjhx.victoriatourist.service.logistics.LogisticsInfosService;
import com.fjhx.victoriatourist.service.purchase.PurchaseBackDetailsService;
import com.fjhx.victoriatourist.service.purchase.PurchaseBackService;
import com.fjhx.wms.entity.stock.dto.StockJournalDetailsDto;
import com.fjhx.wms.entity.stock.dto.StockWaitDetailsDto;
import com.fjhx.wms.entity.stock.dto.StockWaitDto;
import com.fjhx.wms.entity.stock.emums.JournalType;
import com.fjhx.wms.entity.stock.emums.StockWaitType;
import com.fjhx.wms.entity.stock.po.*;
import com.fjhx.wms.service.stock.*;
import com.fjhx.wms.utils.CodeEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.wrapper.IWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * <p>
 * 采购退货 服务实现类
 * </p>
 *
 * @author
 * @since 2023-05-19
 */
@Service
public class PurchaseBackServiceImpl extends ServiceImpl<PurchaseBackMapper, PurchaseBack> implements PurchaseBackService {
    @Autowired
    private PurchaseBackDetailsService purchaseBackDetailsService;
    @Autowired
    private StockWaitService stockWaitService;
    @Autowired
    private StockWaitDetailsService stockWaitDetailsService;
    @Autowired
    private StockJournalService stockJournalService;
    @Autowired
    private StockJournalDetailsService stockJournalDetailsService;
    @Autowired
    private StockService stockService;
    @Autowired
    private PurchaseService purchaseService;
    @Autowired
    private LogisticsInfosService logisticsInfosService;
    @Autowired
    private LogisticsDetailsService logisticsDetailsService;

    @Override
    public Page<PurchaseBackVo> getPage(PurchaseBackSelectDto dto) {
        IWrapper<PurchaseBack> wrapper = getWrapper();
        wrapper.orderByDesc("pb", PurchaseBack::getId);
        Page<PurchaseBackVo> page = this.baseMapper.getPage(dto.getPage(), wrapper);
        return page;
    }

    @Override
    public PurchaseBackVo detail(Long id) {
        PurchaseBack PurchaseBack = this.getById(id);
        PurchaseBackVo result = BeanUtil.toBean(PurchaseBack, PurchaseBackVo.class);
        List<PurchaseBackDetails> purchaseBackDetails = purchaseBackDetailsService.list(q -> q.eq(PurchaseBackDetails::getPurchaseBackId, result.getId()));
        List<PurchaseBackDetailsVo> purchaseBackDetailsVos = BeanUtil.copyToList(purchaseBackDetails, PurchaseBackDetailsVo.class);
        result.setPurchaseBackDetailsList(purchaseBackDetailsVos);
        return result;
    }

    @DSTransactional
    @Override
    public void add(PurchaseBackDto purchaseBackDto) {
        this.save(purchaseBackDto);
        List<PurchaseBackDetails> purchaseBackDetailsList = purchaseBackDto.getPurchaseBackDetailsList();
        purchaseBackDetailsList.forEach(purchaseBackDetails -> purchaseBackDetails.setPurchaseBackId(purchaseBackDto.getId()));
        purchaseBackDetailsService.saveBatch(purchaseBackDetailsList);

        Purchase purchase = purchaseService.getById(purchaseBackDto.getPurchaseId());
        if (ObjectUtil.isEmpty(purchase)) {
            throw new ServiceException("无法查询到采购信息");
        }
        String victoriatouristJson = purchase.getVictoriatouristJson();
        JSONObject json = ObjectUtil.isEmpty(victoriatouristJson) ? new JSONObject() : JSONObject.parseObject(victoriatouristJson);

        //创建待出库记录
        StockWait stockWait = new StockWait();
        stockWait.setBusinessId(purchaseBackDto.getId());
        stockWait.setBusinessCode(json.getString("contractCode"));
        stockWait.setType(2);//出库
        stockWait.setStatus(0);//待出库
        stockWait.setBusinessType(StockWaitType.BACK_OUT.getDetailType());//已采购退货出库
        stockWaitService.save(stockWait);
        List<StockWaitDetails> stockWaitDetailsList = new ArrayList<>();
        for (PurchaseBackDetails purchaseBackDetails : purchaseBackDetailsList) {
            //忽略数量为0的退货记录
            if (BigDecimal.ZERO.compareTo(purchaseBackDetails.getQuantity()) == 0) {
                continue;
            }
            StockWaitDetails stockWaitDetails = new StockWaitDetails();
            stockWaitDetails.setStockWaitId(stockWait.getId());
            stockWaitDetails.setProductId(purchaseBackDetails.getProductId());
            stockWaitDetails.setBusinessDetailsId(purchaseBackDetails.getId());//采购退货明细id
            stockWaitDetails.setQuantity(purchaseBackDetails.getQuantity());
            stockWaitDetailsList.add(stockWaitDetails);
        }
        stockWaitDetailsService.saveBatch(stockWaitDetailsList);
    }

    @Override
    @DSTransactional
    public void backOut(StockWaitDetailsDto stockWaitDetailsDto) {
        //优化
        StockWaitDetails stockWaitDetails = stockWaitDetailsService.getById(stockWaitDetailsDto.getId());
        Assert.notEmpty(stockWaitDetails, "查询不到待出库明细信息");
        StockWaitDto stockWaitDto = BeanUtil.copyProperties(stockWaitDetailsDto, StockWaitDto.class);
        stockWaitDto.setId(stockWaitDetails.getStockWaitId());
        stockWaitDto.setStockWaitDetailsList(Collections.singletonList(BeanUtil.copyProperties(stockWaitDetailsDto, StockWaitDetails.class)));
        backOuts(stockWaitDto);
    }

    @DSTransactional
    @Override
    public void backOuts(StockWaitDto stockWaitDto) {
        StockWait byId = stockWaitService.getById(stockWaitDto.getId());
        Assert.notEmpty(byId,"无法查询到待出库信息");
        //创建物流数据
        LogisticsInfos logisticsInfos = new LogisticsInfos();
        logisticsInfos.setBusinessId(byId.getId());
        logisticsInfos.setBusinessCode(byId.getBusinessCode());
        logisticsInfos.setBusinessType(5);//采购退货
        logisticsInfos.setLogisticsCompanyCode(stockWaitDto.getLogisticsCompanyCode());
        logisticsInfos.setCode(stockWaitDto.getLogisticsCode());
        logisticsInfos.setWarehouseId(stockWaitDto.getWarehouseId());
        logisticsInfos.setIsKd100(0);

        logisticsInfos.setCountryId(stockWaitDto.getCountryId());//国家id
        logisticsInfos.setCityId(stockWaitDto.getCityId());//省id
        logisticsInfos.setProvinceId(stockWaitDto.getProvinceId());//市id
        logisticsInfos.setAddress(stockWaitDto.getAddress());

        logisticsInfosService.save(logisticsInfos);

        List<StockWaitDetails> stockWaitDetailsList = stockWaitDto.getStockWaitDetailsList();

        List<Stock> stockList = new ArrayList<>();

        stockWaitDetailsService.changeStockWaitStatus(stockWaitDto);

        //创建出入库记录
        StockJournal stockJournal = new StockJournal();
        stockJournal.setOpType(byId.getType());
        //退货出库
        stockJournal.setType(JournalType.BACK_OUT.getDetailType());

//        DynamicDataSourceContextHolder.push(SourceConstant.WMS);
        stockJournal.setCode(CodeEnum.SOUT_CODE.getCode());
//        DynamicDataSourceContextHolder.poll();

        stockJournal.setWarehouseId(stockWaitDto.getWarehouseId());
        stockJournal.setBusinessId(byId.getId());
        //保存出入库记录
        stockJournalService.save(stockJournal);

        List<StockJournalDetails> stockJournalDetailsList = new ArrayList<>();

        for (StockWaitDetails stockWaitDetails0 : stockWaitDetailsList) {
            //修改待出入库状态
            StockWaitDetailsDto stockWaitDetailsDto = BeanUtil.copyProperties(stockWaitDetails0, StockWaitDetailsDto.class);
//            stockWaitDetailsService.changeStockWaitStatus(stockWaitDetailsDto);
            StockWaitDetails stockWaitDetails = stockWaitDetailsService.getById(stockWaitDetailsDto.getId());

            //操作库存
            Stock stock = new Stock();
            stock.setQuantity(stockWaitDetailsDto.getQuantity());
            stock.setProductId(stockWaitDetails.getProductId());
            stockList.add(stock);

            //创建出入库明细
            StockJournalDetails stockJournalDetails = new StockJournalDetailsDto();
            stockJournalDetails.setStockJournalId(stockJournal.getId());
            stockJournalDetails.setProductId(stock.getProductId());
            stockJournalDetails.setQuantity(stock.getQuantity());
            stockJournalDetails.setBusinessDetailsId(stockWaitDetails0.getId());
            stockJournalDetailsList.add(stockJournalDetails);


            LogisticsDetails logisticsDetails = new LogisticsDetails();
            logisticsDetails.setLogisticsInfoId(logisticsInfos.getId());
            logisticsDetails.setLogisticsInfoCode(logisticsInfos.getCode());
            logisticsDetails.setBusinessDetailsId(stockWaitDetailsDto.getId());
            logisticsDetails.setReceiptQuantity(stockWaitDetailsDto.getQuantity());
            logisticsDetailsService.save(logisticsDetails);
        }



        //退货出库出次品库存
        stockService.ModifyInventory(4, stockList, stockWaitDto.getWarehouseId());
        //保存出入库明细
        stockJournalDetailsService.saveBatch(stockJournalDetailsList);
    }


}
