package com.zfire.mall.manager.logic.k3;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zfire.mall.manager.bean.ExcelData;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.k3.*;
import com.zfire.mall.manager.bean.pick.PickManagerBean;
import com.zfire.mall.manager.commonmapper.manage.TransferMapper;
import com.zfire.mall.manager.constant.KingDeeCons;
import com.zfire.mall.manager.enums.ExamineStatusEnum;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.logic.stock.StockCommonLogic;
import com.zfire.mall.manager.plus.entity.*;
import com.zfire.mall.manager.plus.service.*;
import lombok.extern.slf4j.Slf4j;
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.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class K3TransferLogic {


    @Autowired
    K3Logic k3Logic;

    @Autowired
    KingDeeTransferService kingDeeTransferService;

    @Autowired
    KingDeeTransferItemService kingDeeTransferItemService;

    @Autowired
    TransferMapper transferMapper;

    @Autowired
    StockService stockService;

    @Autowired
    StockCommonLogic stockCommonLogic;

    @Autowired
    StockCorrespondService stockCorrespondService;

    @Autowired
    CommonLogic commonLogic;


//    public void allSync(String orgId, String orgNumber, String startTime, String endTime) throws Exception {
//        // 调用调拨单接口
//        RequestApiBean request = k3Logic.getInstance(orgId, orgNumber, KingDeeCons.STOCK_TRANSFER, startTime, endTime);
//        String filterStr = "FDocumentStatus = 'C' "+ k3Logic.supplySql("FApproveDate", request.getStartTime(), request.getEndTime());
//        request.setFieldKeys("FID,FBillNo,FStockOrgId.FName,FStockOutOrgId.FName,FTransferBizType,FNote,FApproverId.FName,FCancellerId.FName,FBillTypeID.FName,FDocumentStatus,FDate,FApproveDate,FCancelDate");
//        request.setFilterString(String.format(filterStr, orgNumber));
//        request.setOrderString("FID ASC");
//
//        String[] fields = new String[]{"id","billNo","stockOrgId","stockOutOrgId","transferBizType","note","approverId","cancellerId","billType","documentStatus","forDate","approveDate","cancelDate"};
//        List<KingDeeTransfer> objects = k3Logic.allSync(request, fields, KingDeeTransfer.class);
//        syncTransferItem(orgId,orgNumber,startTime,endTime);
//        if (CollectionUtils.isNotEmpty(objects)) {
//            kingDeeTransferService.saveOrUpdateBatch(objects);
//        }
//
//    }

//    public void syncTransferItem(String orgId, String orgNumber, String startTime, String endTime) throws Exception {
//        // 调用调拨单物料接口
//        RequestApiBean request = k3Logic.getInstance(orgId, orgNumber, KingDeeCons.STOCK_TRANSFER, startTime, endTime);
//        String filterStr = "FDocumentStatus = 'C' "+ k3Logic.supplySql("FApproveDate", request.getStartTime(), request.getEndTime());
//        request.setFieldKeys("FBillEntry_FEntryID,FID,FBillNo,FMaterialId,FMaterialId.FNumber,FMaterialName,FSrcStockId.FName,FDestStockId.FName,FQty,FOwnerId,FOwnerOutId,FModel,FBaseUnitId.FName,FConsignAmount,FConsignPrice,FSrcStockLocId,FDestStockLocId,FAuxPropId");
//        request.setFilterString(String.format(filterStr, orgNumber));
//        request.setOrderString("FID ASC");
//
//        String[] fields = new String[]{"id","fId","billNo","materialId","materialNumber","materialName","srcStockId","destStockId","qty","ownerId","ownerOutId","model","baseUnitId","consignAmount","consignPrice","srcStockLocId","destStockLocId","auxPropId"};
//        List<KingDeeTransferItem> objects = k3Logic.allSync(request, fields, KingDeeTransferItem.class);
//        if (Objects.nonNull(objects)) {
//            kingDeeTransferItemService.saveOrUpdateBatch(objects);
//        }
//    }

    /**
     * 调拨单列表
     * @param billNo
     * @param materialName
     * @param startTime
     * @param endTime
     * @param pageNum
     * @param pageSize
     * @return
     */
    public IPage<KingTransfer> list(String billNo, String materialName, String startTime, String endTime, Integer pageNum, Integer pageSize) {
        return transferMapper.list(new Page<>(pageNum,pageSize),billNo,materialName,startTime,endTime);
    }

    /**
     * 调拨单详情
     * @param id
     * @return
     */
    public KingTransferBean detail(String id) {
        return transferMapper.detail(id);
    }

    /**
     * 调拨单导出
     * @param kingTransferList
     * @return
     */
    public ExcelData export(List<KingTransfer> kingTransferList){
        String[] titles = new String[]{"单据编号","单据类型","调拨类型","申请日期","单据状态",
                "关闭状态","物料编码","物料名称","规格型号","辅助属性","单位",
                "申请数量","调出仓库","调入仓库"};
        List<List<Object>> rows = new ArrayList<>();
        for (KingTransfer kingTransfer: kingTransferList) {
            List<Object> row = new ArrayList<>();
            row.add(kingTransfer.getBillNo());
            row.add(kingTransfer.getBillType());
            row.add(kingTransfer.getTransferBizType());
            row.add(kingTransfer.getForDate());
            row.add(kingTransfer.getDocumentStatus());
            row.add(kingTransfer.getCancelStatus());
            row.add(kingTransfer.getMaterialNumber());
            row.add(kingTransfer.getMaterialName());
            row.add(kingTransfer.getModel());
            //row.add(kingTransfer.getAuxPropId());
            row.add(kingTransfer.getBaseUnitId());
            row.add(kingTransfer.getSrcStockName());
            row.add(kingTransfer.getDestStockName());
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        return excelData;
    }

    public void add(KingTransferAddOrUp kingTransferAdd) {
        kingTransferAdd.setId(IdWorker.getIdStr());
        kingTransferAdd.setBillNo(kingTransferAdd.getId());
        kingTransferAdd.setForDate(new Date());
        kingTransferAdd.setCancelStatus(ExamineStatusEnum.WAIT.getKey());
        kingTransferAdd.insert();

        List<StockCorrespond> list = stockCorrespondService.lambdaQuery().list();
        for (KingDeeTransferItem kingDeeTransferItem : kingTransferAdd.getKingDeeTransferItems()) {
            kingDeeTransferItem.setBillNo(kingTransferAdd.getId());



            List<StockCorrespond> collect = list.stream().filter(item -> item.getId().equals(kingDeeTransferItem.getSrcStockId())).collect(Collectors.toList());
            List<StockCorrespond> destStock = list.stream().filter(item -> item.getId().equals(kingDeeTransferItem.getDestStockId())).collect(Collectors.toList());

            if (CollectionUtils.isEmpty(collect))
                throw new RemoteServiceException("未找到对应仓库");


            StockCorrespond stockCorrespond = collect.get(0);
            StockCorrespond stockDestCorrespond = destStock.get(0);
            kingDeeTransferItem.setSrcStockName(stockCorrespond.getName());
            kingDeeTransferItem.setDestStockName(stockDestCorrespond.getName());
        }

        kingDeeTransferItemService.saveBatch(kingTransferAdd.getKingDeeTransferItems());
    }

    public void update(KingTransferAddOrUp kingTransferAdd) {
        kingTransferAdd.updateById();

        kingDeeTransferItemService.lambdaUpdate().eq(KingDeeTransferItem::getBillNo,kingTransferAdd.getId()).remove();
        for (KingDeeTransferItem kingDeeTransferItem : kingTransferAdd.getKingDeeTransferItems()) {
            kingDeeTransferItem.setBillNo(kingTransferAdd.getId());
        }

        kingDeeTransferItemService.saveBatch(kingTransferAdd.getKingDeeTransferItems());

    }

    @Transactional(rollbackFor = Exception.class)
    public void examine(String billNo, String cancelStatus) {

        AdminUserCom adminUser = commonLogic.getAdminUser();

        KingDeeTransfer kingDeeTransfer = kingDeeTransferService.getById(billNo);
        kingDeeTransfer.setCancelStatus(cancelStatus);
        kingDeeTransfer.setApproveDate(new Date());
        kingDeeTransfer.setApproverId(adminUser.getNickName());
        kingDeeTransfer.updateById();

        if (cancelStatus.equals(ExamineStatusEnum.OK.getKey())) {
            List<KingDeeTransferItem> kingDeeTransferItems = kingDeeTransferItemService.lambdaQuery()
                    .eq(KingDeeTransferItem::getBillNo, billNo).list();

            for (KingDeeTransferItem kingDeeTransferItem : kingDeeTransferItems) {
                this.stockSub(kingDeeTransfer,kingDeeTransferItem);
                this.stockAdd(kingDeeTransfer,kingDeeTransferItem);
            }



        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void stockSub(KingDeeTransfer kingDeeTransfer, KingDeeTransferItem kingDeeTransferItem) {

        Stock stock = stockService.lambdaQuery().eq(Stock::getStockId, kingDeeTransferItem.getSrcStockId())
                .eq(Stock::getMaterialId, kingDeeTransferItem.getMaterialId()).last("limit 1").one();

        if (stock == null)
            throw new RemoteServiceException(kingDeeTransferItem.getMaterialName()+"该物料没有库存，不能退库");


        stockCommonLogic.stockAccLog("调拨调出减少库存",stock,kingDeeTransferItem.getQty(),kingDeeTransferItem.getBillNo(),false,"调拨单");

        stock.setStockQty(stock.getStockQty().subtract(kingDeeTransferItem.getQty()));

        if (stock.getStockQty().doubleValue() < 1)
            throw new RemoteServiceException(kingDeeTransferItem.getMaterialName()+"该物料没有库存，不能退库");

        stock.updateById();

    }

    @Transactional(rollbackFor = Exception.class)
    public void stockAdd(KingDeeTransfer kingDeeTransfer, KingDeeTransferItem kingDeeTransferItem) {

        Stock stock = stockService.lambdaQuery().eq(Stock::getStockId, kingDeeTransferItem.getDestStockId())
                .eq(Stock::getMaterialId, kingDeeTransferItem.getMaterialId()).last("limit 1").one();

        if (stock == null){
            stock = new Stock();

            stock.setStockQty(BigDecimal.ZERO);
            stock.setSyncTime(new Date());
            stock.setStockId(kingDeeTransferItem.getDestStockId());
            stock.setMaterialId(kingDeeTransferItem.getMaterialId());
            stock.setSupplyOrgId(kingDeeTransferItem.getSupplyOrgId());



            stockCommonLogic.stockAccLog("调拨调入增加库存",stock,kingDeeTransferItem.getQty(),kingDeeTransferItem.getBillNo(),true,"调拨单");

            stock.setStockQty(kingDeeTransferItem.getQty());
            stock.insert();

            return;
        }

        stockCommonLogic.stockAccLog("调拨调入增加库存",stock,kingDeeTransferItem.getQty(),kingDeeTransferItem.getBillNo(),true,"调拨单");

        stock.setStockQty(kingDeeTransferItem.getQty().add(stock.getStockQty()));
        stock.updateById();

    }

}
