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


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
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.direct.DirectTransferList;
import com.zfire.mall.manager.bean.k3.*;
import com.zfire.mall.manager.bean.stock.KingDeePurchaseStockInAdd;
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 K3PurchaseStockInLogic {

    @Autowired
    K3Logic k3Logic;

    @Autowired
    KingDeePurchaseStockInService kingDeePurchaseStockInService;

    @Autowired
    KingDeePurchaseStockInItemService kingDeePurchaseStockInItemService;

    @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.PURCHASE_IN_STOCK, startTime, endTime);
//        String filterStr = "FDocumentStatus = 'C' "+ k3Logic.supplySql("FApproveDate", request.getStartTime(), request.getEndTime());
//        request.setFieldKeys("FID,FBillNo,FDate,FStockOrgId,FDemandOrgId,FPurchaseOrgId,FSupplierId,FStockDeptId,FApproverId.FName,FApproveDate,FCancellerId,FCancelDate," +
//                "FSupplyId.FName");
//        request.setFilterString(String.format(filterStr, orgNumber));
//        request.setOrderString("FID ASC");
//
//        String[] fields = new String[]{"id","billNo","forDate","stockOrgId","demandOrgId","purchaseOrgId","supplierId","stockDeptId","approverId","approveDate","cancellerId","cancelDate",
//                "supplyName"};
//        List<KingDeePurchaseStockIn> objects = k3Logic.allSync(request, fields, KingDeePurchaseStockIn.class);
//        if (!CollectionUtils.isEmpty(objects)) {
//            kingDeePurchaseStockInService.saveOrUpdateBatch(objects);
//        }
//        allSyncOrder(orgId,orgNumber,startTime,endTime);
//    }
//
//
//    public void allSyncOrder(String orgId, String orgNumber, String startTime, String endTime) throws Exception {
//        // 调用入库单接口
//        RequestApiBean request = k3Logic.getInstance(orgId, orgNumber, KingDeeCons.PURCHASE_IN_STOCK, startTime, endTime);
//        String filterStr = "FDocumentStatus = 'C' "+ k3Logic.supplySql("FApproveDate", request.getStartTime(), request.getEndTime());
//        request.setFieldKeys("FInStockEntry_FEntryID,FID,FBillNo,FMaterialId,FMaterialId.FNumber,FMaterialId.FName,FStockId.FName,FNote,FMustQty,FRealQty,FUnitId.FName,FAuxUnitQty,FPrice,FEntryTaxRate" +
//                ",FAmount,FTaxPrice,FEntryTaxAmount,FAllAmount,FUOM");
//        request.setFilterString(String.format(filterStr, orgNumber));
//        request.setOrderString("FID ASC");
//
//        String[] fields = new String[]{"id","fId","billNo","materialId","materialNumber","materialName","stockId","note","mustQty","realQty","unit","auxUnitQty","price","entryTaxRate",
//                "amount","taxPrice","entryTaxAmount","allAmount","uom"};
//        List<KingDeePurchaseStockInItem> objects = k3Logic.allSync(request, fields, KingDeePurchaseStockInItem.class);
//        if (Objects.nonNull(objects)) {
//            kingDeePurchaseStockInItemService.saveOrUpdateBatch(objects);
//        }
//    }

    public IPage<KingDeePurchaseStockInBean> list(String materialCode,String billNo, String materialOldNumber,String materialName, String materialNumber, String supplyName, String startTime, String endTime, Integer pageNum, Integer pageSize) {
        return transferMapper.listStockIn(new Page<>(pageNum,pageSize),materialCode,billNo,materialName,materialNumber,supplyName,startTime,endTime,materialOldNumber);
    }

    public KingDeePurchaseStockInData detail(String id) {
        KingDeePurchaseStockIn kingDeePurchaseStockIn = kingDeePurchaseStockInService.getById(id);

        KingDeePurchaseStockInData kingDeePurchaseStockInData = BeanUtil.toBean(kingDeePurchaseStockIn, KingDeePurchaseStockInData.class);

        List<KingDeePurchaseStockInItem> kingDeePurchaseStockInItems = kingDeePurchaseStockInItemService.lambdaQuery().eq(KingDeePurchaseStockInItem::getBillNo, id).list();

        kingDeePurchaseStockInData.setKingDeePurchaseStockInItems(kingDeePurchaseStockInItems);
        return kingDeePurchaseStockInData;
    }

    /**
     * 采购入库单
     * @param kingDeePurchaseStockInBeanList
     * @return
     */
    public ExcelData export(List<KingDeePurchaseStockInBean> kingDeePurchaseStockInBeanList){
        String[] titles = new String[]{"入库单号","入库日期","仓库","供货单位","审核日期",
                "备注","存货编码","存货名称","规格型号","主计量","数量",
                "原币含税单价","原币金额","原币税额","原币价税合计","税率","制单人","审核人"};
        List<List<Object>> rows = new ArrayList<>();
        for (KingDeePurchaseStockInBean kingDeePurchaseStockInBean : kingDeePurchaseStockInBeanList) {
            List<Object> row = new ArrayList<>();
            row.add(kingDeePurchaseStockInBean.getBillNo());
            row.add(DateUtil.formatDate(kingDeePurchaseStockInBean.getForDate()));
            row.add(kingDeePurchaseStockInBean.getStockId());
            row.add(kingDeePurchaseStockInBean.getSupplyName());
            row.add(DateUtil.formatDate(kingDeePurchaseStockInBean.getApproveDate()));
            //备注
            row.add(kingDeePurchaseStockInBean.getNote());
            row.add(kingDeePurchaseStockInBean.getMaterialNumber());
            row.add(kingDeePurchaseStockInBean.getMaterialName());
            row.add(kingDeePurchaseStockInBean.getUom());
            row.add(kingDeePurchaseStockInBean.getUnit());
            row.add(kingDeePurchaseStockInBean.getAuxUnitQty());
            row.add(kingDeePurchaseStockInBean.getTaxPrice());
            row.add(kingDeePurchaseStockInBean.getAmount());
            row.add(kingDeePurchaseStockInBean.getEntryTaxAmount());
            row.add(kingDeePurchaseStockInBean.getAllAmount());
            row.add(kingDeePurchaseStockInBean.getEntryTaxRate());
            row.add(kingDeePurchaseStockInBean.getCreateBy());
            row.add(kingDeePurchaseStockInBean.getApproverId());
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        return excelData;
    }


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

        kingDeePurchaseStockInAdd.insert();

        List<StockCorrespond> list = stockCorrespondService.lambdaQuery().list();

        for (KingDeePurchaseStockInItem kingDeePurchaseStockInItem : kingDeePurchaseStockInAdd.getKingDeePurchaseStockInItems()) {
            kingDeePurchaseStockInItem.setBillNo(kingDeePurchaseStockInAdd.getBillNo());
            if (StringUtils.isEmpty(kingDeePurchaseStockInItem.getStockId()))
                throw new RemoteServiceException("仓库空了");


            List<StockCorrespond> collect = list.stream().filter(item -> item.getId().equals(kingDeePurchaseStockInItem.getStockId())).collect(Collectors.toList());

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


            StockCorrespond stockCorrespond = collect.get(0);
            kingDeePurchaseStockInItem.setStockName(stockCorrespond.getName());

        }

        kingDeePurchaseStockInItemService.saveBatch(kingDeePurchaseStockInAdd.getKingDeePurchaseStockInItems());
    }

    public void update(KingDeePurchaseStockInAdd kingDeePurchaseStockInAdd) {

        kingDeePurchaseStockInAdd.updateById();

        kingDeePurchaseStockInItemService.lambdaUpdate().eq(KingDeePurchaseStockInItem::getBillNo,kingDeePurchaseStockInAdd.getId())
                .remove();

        for (KingDeePurchaseStockInItem kingDeePurchaseStockInItem : kingDeePurchaseStockInAdd.getKingDeePurchaseStockInItems()) {
            kingDeePurchaseStockInItem.setBillNo(kingDeePurchaseStockInAdd.getBillNo());
        }

        kingDeePurchaseStockInItemService.saveBatch(kingDeePurchaseStockInAdd.getKingDeePurchaseStockInItems());
    }


    @Transactional(rollbackFor = Exception.class)
    public void examine(String billNo, String cancelStatus) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        KingDeePurchaseStockIn kingDeePurchaseStockIn = kingDeePurchaseStockInService.getById(billNo);

        kingDeePurchaseStockIn.setCancelStatus(cancelStatus);
        kingDeePurchaseStockIn.setApproveDate(new Date());
        kingDeePurchaseStockIn.setApproverId(adminUser.getNickName());
        kingDeePurchaseStockIn.updateById();


        if (cancelStatus.equals(ExamineStatusEnum.OK.getKey())) {

            List<KingDeePurchaseStockInItem> kingDeePurchaseStockInItems = kingDeePurchaseStockInItemService.lambdaQuery().eq(KingDeePurchaseStockInItem::getBillNo, billNo).list();

            for (KingDeePurchaseStockInItem kingDeePurchaseStockInItem : kingDeePurchaseStockInItems) {

                stockAdd(kingDeePurchaseStockIn, kingDeePurchaseStockInItem);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void stockAdd(KingDeePurchaseStockIn  kingDeePurchaseStockIn,KingDeePurchaseStockInItem kingDeePurchaseStockInItem) {

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

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

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



            stockCommonLogic.stockAccLog("采购入库单增加库存",stock,kingDeePurchaseStockInItem.getRealQty(),kingDeePurchaseStockIn.getBillNo(),true,"采购入库单");

            stock.setStockQty(kingDeePurchaseStockInItem.getRealQty());
            stock.insert();

            return;
        }

        stockCommonLogic.stockAccLog("采购入库单增加库存",stock,kingDeePurchaseStockInItem.getRealQty(),kingDeePurchaseStockIn.getBillNo(),true,"采购入库单");

        stock.setStockQty(kingDeePurchaseStockInItem.getRealQty().add(stock.getStockQty()));
        stock.updateById();

    }





}
