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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.EnumUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.bill.TransferOrderBean;
import com.zfire.mall.manager.bean.k3.bill.TransferOrderBeanStock;
import com.zfire.mall.manager.bean.k3.bill.result.BillItem;
import com.zfire.mall.manager.bean.k3.bill.result.ResultEntity;
import com.zfire.mall.manager.bean.requisition.RequisitionBean;
import com.zfire.mall.manager.bean.requisition.RequisitionDetail;
import com.zfire.mall.manager.commonmapper.RequisitionMapper;
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.k3.bill.SalesOrderLogic;
import com.zfire.mall.manager.logic.stock.StockCommonLogic;
import com.zfire.mall.manager.plus.entity.*;
import com.zfire.mall.manager.plus.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 零售单
 * @author changebuy
 */
@Service
public class RequisitionOrderLogic {


    @Autowired
    RequisitionMapper requisitionMapper;

    @Autowired
    RequisitionOrderService requisitionOrderService;

    @Autowired
    RequisitionOrderItemService requisitionOrderItemService;


    @Autowired
    RetailOrderService restOrderService;

    @Autowired
    RetailOrderItemService retailOrderItemService;

    @Autowired
    CommonLogic commonLogic;

    @Autowired
    EnginOrderService enginOrderService;

    @Autowired
    EnginOrderItemService enginOrderItemService;

    @Autowired
    SalesOrderLogic salesOrderLogic;

    @Autowired
    StockCorrespondPositionService stockCorrespondPositionService;

    @Autowired
    KingDeeStockService kingDeeStockService;

    @Autowired
    StockCommonLogic stockCommonLogic;


    public IPage<RequisitionBean> list(String id, String examineStatus, String customerName,
                                       String correspondName, String specification, String startTime, String endTime,
                                       String customerNumber, String materialCode, String materialName, Integer pageNum, Integer pageSize) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";
        return requisitionMapper.list(new Page<>(pageNum,pageSize),id, examineStatus, customerName,correspondName,specification,startTime,endTime,
                customerNumber,materialCode,materialName,customerId,adminUser.getServiceIds(),adminUser.getK3CategoryIds());
    }

    public RequisitionDetail detail(String id) {
        return requisitionMapper.detail(id);

    }

    public void update(String id, HttpServletRequest request) {
        RequisitionOrder byId = requisitionOrderService.getById(id);
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        if (byId.getExamineStatus().equals("OK"))
            throw new RemoteServiceException("审核通过无法关闭");
        byId.setExamineStatus("CLOSE");
        byId.setCloseName(adminUser.getNickName());
        byId.setCloseTime(new Date());
        requisitionOrderService.updateById(byId);
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(RequisitionOrder requisition, HttpServletRequest request) {

        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        if (requisitionOrderService.lambdaQuery().eq(RequisitionOrder::getOrderNo,requisition.getOrderNo()).count()>0)
            throw new RemoteServiceException("当前订单已经提前开票过");

        //添加工程订单的直接调拨单
        if (requisition.getOrderType().equals("HOME") || requisition.getOrderType().equals("TRADE")){
            EnginOrder enginOrder = enginOrderService.getById(requisition.getOrderNo());



            //给订单设置发货
            enginOrder.setRequisitionStatus(1);
            enginOrder.updateById();

            requisition.setCustomerId(enginOrder.getCustomerId());
            requisition.setCustomerName(enginOrder.getCustomerName());
            requisition.setCustomerNumber(enginOrder.getCustomerNumber());
            requisition.setOrderTime(new Date());
            requisition.setMainOrderId(enginOrder.getEnginOrderId());
            requisition.setAdminCompanyId(enginOrder.getAdminCompanyId());
            requisition.setExamineStatus(ExamineStatusEnum.WAIT.toString());
            requisition.setEnginOrderNo(enginOrder.getEnginOrderNo());
            requisition.setRefProjectName(enginOrder.getRefProjectName());
            requisition.setRefUseUnit(enginOrder.getRefUseUnit());
            requisition.setEnginOrderType(enginOrder.getEnginOrderType());
            requisition.setRefFactoryNo(enginOrder.getRefFactoryNo());
            requisition.setRefInstallAddress(enginOrder.getRefInstallAddress());
            requisition.setRefLinkman(enginOrder.getRefLinkman());
            requisition.setRefPhone(enginOrder.getRefPhone());
            requisition.setRefTel(enginOrder.getRefTel());
            requisition.setRefEnginRecordNo(enginOrder.getRefEnginRecordNo());
            requisition.insert();

            List<EnginOrderItem> list = enginOrderItemService.lambdaQuery().eq(EnginOrderItem::getParentId, enginOrder.getEnginOrderId()).list();
            List<RequisitionOrderItem> requisitionItems = new ArrayList<>();
            for (EnginOrderItem enginOrderItem : list) {
                RequisitionOrderItem requisitionOrder = BeanUtil.toBean(enginOrderItem, RequisitionOrderItem.class);
                if (requisitionOrder.getIsDirectTransfer() == true){
                    throw new RemoteServiceException("已直调无法提前开票");

                }

                if (enginOrderItem.getRefundableQty() <= 0)
                    throw new RemoteServiceException("订单数量0，无法提前开票");

                //校验库存是否充足
                Integer integer = stockCommonLogic.stockOpendNumber(requisition.getCorrespondId(), enginOrderItem.getMaterialId());
                if (enginOrderItem.getRefundableQty() > integer)
                    throw new RemoteServiceException(enginOrderItem.getMaterialName()+enginOrderItem.getSpecification()+"仓库库存不足,无法提前开票");

                requisitionOrder.setOrderId(enginOrderItem.getId());
                requisitionOrder.setMainOrderId(enginOrder.getEnginOrderId());
                requisitionOrder.setRequisitionOrderId(requisition.getId());
                requisitionOrder.setMaterialCode(enginOrderItem.getMaterialNumber());
                requisitionOrder.setMaterialOldNumber(enginOrderItem.getMaterialOldNumber());

                requisitionItems.add(requisitionOrder);
            }
            requisitionOrderItemService.saveBatch(requisitionItems);
        }


        //添加零售订单的直接调拨单
        if (requisition.getOrderType().equals("RETAIL") || requisition.getOrderType().equals("RETAIL_POLICY")){
            RetailOrder retailOrder = restOrderService.getById(requisition.getOrderNo());

            //给订单设置发货
            retailOrder.setRequisitionStatus(1);
            retailOrder.updateById();

            requisition.setMainOrderId(retailOrder.getId());
            requisition.setCustomerId(retailOrder.getCustomerId());
            requisition.setCustomerName(retailOrder.getCustomerName());
            requisition.setCustomerNumber(retailOrder.getCustomerNumber());
            requisition.setOrderTime(new Date());
            requisition.setAdminCompanyId(retailOrder.getAdminCompanyId());
            requisition.setExamineStatus(ExamineStatusEnum.WAIT.toString());
            requisition.insert();

            List<RetailOrderItem> retailOrderItems = retailOrderItemService.lambdaQuery().eq(RetailOrderItem::getRetailOrderId, requisition.getOrderNo()).list();
            List<RequisitionOrderItem> requisitionItems = new ArrayList<>();
            for (RetailOrderItem retailOrderItem : retailOrderItems) {
                RequisitionOrderItem requisitionOrder = BeanUtil.toBean(retailOrderItem, RequisitionOrderItem.class);

                if (retailOrderItem.getIsDirectTransfer() == true){
                    throw new RemoteServiceException("已直调无法提前开票");

                }

                if (retailOrderItem.getRefundableQty() <= 0)
                    throw new RemoteServiceException("订单数量0，无法提前开票");

                //校验库存是否充足
                Integer integer = stockCommonLogic.stockOpendNumber(requisition.getCorrespondId(), retailOrderItem.getMaterialId());
                if (retailOrderItem.getRefundableQty() > integer)
                    throw new RemoteServiceException(retailOrderItem.getMaterialName()+retailOrderItem.getSpecification()+"仓库库存不足,无法提前开票");

                requisitionOrder.setOrderId(retailOrderItem.getId());
                requisitionOrder.setMainOrderId(retailOrder.getId());
                requisitionOrder.setRequisitionOrderId(requisition.getId());
                requisitionItems.add(requisitionOrder);
            }
            requisitionOrderItemService.saveBatch(requisitionItems);
        }



    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(List<String> id, HttpServletRequest request) {
        for (String s : id) {
            RequisitionOrder byId = requisitionOrderService.getById(s);
            if (byId.getExamineStatus().equals("OK"))
                throw new RemoteServiceException("审核通过无法删除");

            List<RequisitionOrderItem> list = requisitionOrderItemService.lambdaQuery().eq(RequisitionOrderItem::getRequisitionOrderId, s).list();

            for (RequisitionOrderItem requisitionOrderItem : list) {
                if (byId.getOrderType().equals("RETAIL") || byId.getOrderType().equals("RETAIL_POLICY ")) {
                    RetailOrderItem retailOrderItem = retailOrderItemService.getById(requisitionOrderItem.getOrderId());
                    retailOrderItem.setRefundableQty(requisitionOrderItem.getRefundableQty());
                    retailOrderItem.updateById();
                }else {
                    EnginOrderItem enginOrderItem = enginOrderItemService.getById(requisitionOrderItem.getOrderId());
                    enginOrderItem.setRefundableQty(enginOrderItem.getRefundableQty());
                    enginOrderItem.updateById();
                }
            }
            requisitionOrderService.removeById(s);
            requisitionOrderItemService.lambdaUpdate().eq(RequisitionOrderItem::getRequisitionOrderId, s).remove();
        }
    }

    public void updateRequisition(RequisitionOrder requisitionOrder, HttpServletRequest request) {
        requisitionOrder.updateById();
    }

    @Transactional(rollbackFor = Exception.class)
    public void approval(String id, String examineStatus,String approvalRemark, HttpServletRequest request) {
        RequisitionOrder byId = requisitionOrderService.getById(id);
        //ToDo 同步金蝶
        if (examineStatus.equals(ExamineStatusEnum.OK.toString())){
            //添加工程订单的直接调拨单
            if (byId.getOrderType().equals("HOME") || byId.getOrderType().equals("TRADE")){
                EnginOrder enginOrder = enginOrderService.getById(byId.getOrderNo());
                ResultEntity resultEntity = salesOrderLogic.pushTransfer(enginOrder.getEnginOrderNo());
                TransferOrderBean transferOrderBean = new TransferOrderBean();
                transferOrderBean.setBillNo(id);
                transferOrderBean.setId(resultEntity.getId());
                transferOrderBean.setDate(DateUtil.formatTime(enginOrder.getOrderDate()));
                transferOrderBean.setRemarks(enginOrder.getRemark());
                List<TransferOrderBeanStock> transOrderBeanStockList = new ArrayList<>();
                List<RequisitionOrderItem> list = requisitionOrderItemService.lambdaQuery().eq(RequisitionOrderItem::getRequisitionOrderId, byId.getId()).list();
                for (BillItem item : resultEntity.getItems()) {
                    for (RequisitionOrderItem requisitionOrderItem : list) {

                        //校验库存是否充足
                        Integer integer = stockCommonLogic.stockOpendNumber(byId.getCorrespondId(), requisitionOrderItem.getMaterialId());
                        if (requisitionOrderItem.getRefundableQty() > integer)
                            throw new RemoteServiceException(requisitionOrderItem.getMaterialName()+requisitionOrderItem.getSpecification()+"仓库库存不足,无法提前开票");
                        EnginOrderItem enginOrderItem = enginOrderItemService.getById(requisitionOrderItem.getOrderId());
                        if (requisitionOrderItem.getOrderId().equals(item.getSupplyColVal())){
                            TransferOrderBeanStock transferOrderBeanStock = new TransferOrderBeanStock();
                            transferOrderBeanStock.setEntryId(item.getEntryId());

                            requisitionOrderItem.setKingDeeSeq(item.getSeq());
                            requisitionOrderItem.setKingDeeEntryId(item.getEntryId());
                            requisitionOrderItem.updateById();

                            //调入仓库编码
                            StockCorrespondPosition one = stockCorrespondPositionService.lambdaQuery().eq(StockCorrespondPosition::getCorrespondId, byId.getInCorrespondId()).one();
                            KingDeeStock kingDeeStock = kingDeeStockService.getById(one.getStockId());

                            //仓库编码
                            StockCorrespondPosition stockCorrespondPosition = stockCorrespondPositionService.lambdaQuery().eq(StockCorrespondPosition::getCorrespondId, byId.getCorrespondId()).one();
                            KingDeeStock kingDe = kingDeeStockService.getById(stockCorrespondPosition.getStockId());

                            transferOrderBeanStock.setDestStock(kingDeeStock.getNumber());
                            transferOrderBeanStock.setSrcStock(kingDe.getNumber());
                            transferOrderBeanStock.setNumber(enginOrderItem.getMaterialNumber());
                            transferOrderBeanStock.setQty(Convert.toBigDecimal(requisitionOrderItem.getRefundableQty()));
                            transOrderBeanStockList.add(transferOrderBeanStock);
                        }
                    }
                }
                transferOrderBean.setEntry(transOrderBeanStockList);
                ResultEntity resultEntity1 = salesOrderLogic.syncBillTransferData(transferOrderBean);

            }


            //添加零售订单的直接调拨单
            if (byId.getOrderType().equals("RETAIL") || byId.getOrderType().equals("RETAIL_POLICY")){
                RetailOrder retailOrder = restOrderService.getById(byId.getOrderNo());
                ResultEntity resultEntity = salesOrderLogic.pushTransfer(retailOrder.getId());
                TransferOrderBean transferOrderBean = new TransferOrderBean();
                transferOrderBean.setBillNo(id);
                transferOrderBean.setId(resultEntity.getId());
                transferOrderBean.setKlsCombo("001");
                transferOrderBean.setDate(DateUtil.formatTime(retailOrder.getTheTime()));
                transferOrderBean.setRemarks(retailOrder.getRemark());
                List<TransferOrderBeanStock> transOrderBeanStockList = new ArrayList<>();
                List<RequisitionOrderItem> list = requisitionOrderItemService.lambdaQuery().eq(RequisitionOrderItem::getRequisitionOrderId, byId.getId()).list();
                for (BillItem item : resultEntity.getItems()) {
                    for (RequisitionOrderItem requisitionOrderItem : list) {
                        //校验库存是否充足
                        Integer integer = stockCommonLogic.stockOpendNumber(byId.getCorrespondId(), requisitionOrderItem.getMaterialId());
                        if (requisitionOrderItem.getRefundableQty() > integer)
                            throw new RemoteServiceException(requisitionOrderItem.getMaterialName()+requisitionOrderItem.getSpecification()+"仓库库存不足,无法提前开票");
                        RetailOrderItem retailOrderItem = retailOrderItemService.getById(requisitionOrderItem.getOrderId());
                        if (requisitionOrderItem.getOrderId().equals(item.getSupplyColVal())){
                            TransferOrderBeanStock transferOrderBeanStock = new TransferOrderBeanStock();
                            transferOrderBeanStock.setEntryId(item.getEntryId());

                            requisitionOrderItem.setKingDeeSeq(item.getSeq());
                            requisitionOrderItem.setKingDeeEntryId(item.getEntryId());
                            requisitionOrderItem.updateById();

                            KingDeeStock kingDeeStock = kingDeeStockService.getById(byId.getInStockId());
                            KingDeeStock kingDeeStock1 = kingDeeStockService.getById(byId.getStockId());
                            transferOrderBeanStock.setDestStock(kingDeeStock.getNumber());
                            transferOrderBeanStock.setSrcStock(kingDeeStock1.getNumber());
                            transferOrderBeanStock.setNumber(retailOrderItem.getMaterialCode());
                            transferOrderBeanStock.setQty(Convert.toBigDecimal(requisitionOrderItem.getRefundableQty()));
                            transOrderBeanStockList.add(transferOrderBeanStock);
                        }
                    }
                }
                transferOrderBean.setEntry(transOrderBeanStockList);
                ResultEntity resultEntity1 = salesOrderLogic.syncBillTransferData(transferOrderBean);
            }

        }

        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        byId.setApprovalName(adminUser.getNickName());
        byId.setApprovalTime(new Date());
        byId.setExamineStatus(examineStatus);
        byId.setApprovalRemark(approvalRemark);
        byId.updateById();
    }


    /**
     * 退货单数据导出
     * @param requisitionBeans
     * @return
     */
    public ExcelData export(List<RequisitionBean> requisitionBeans){
        String[] titles = new String[]{"直接调拨单号","审核状态","单据日期","经销商编码","经销商名称",
                "调拨方向","厂产品代码","产品名称","规格型号","单位","调拨数量",
                "调出仓库","调出仓位","调入仓库","调入仓位","备注信息","制单人","制单日期","审核人","审核日期"};
        List<List<Object>> rows = new ArrayList<>();
        for (RequisitionBean requisitionBean : requisitionBeans) {
            List<Object> row = new ArrayList<>();
            row.add(requisitionBean.getId());
//            row.add(ExamineStatusEnum.valueOf(requisitionBean.getExamineStatus()).getMsg());
            row.add(EnumUtil.getNameFieldMap(ExamineStatusEnum.class, "value").get(requisitionBean.getExamineStatus()));
            row.add(DateUtil.formatDate(requisitionBean.getOrderTime()));
            row.add(requisitionBean.getCustomerNumber());
            row.add(requisitionBean.getCustomerName());
            row.add(requisitionBean.getDirection());
            row.add(requisitionBean.getMaterialCode());
            row.add(requisitionBean.getMaterialName());
            row.add(requisitionBean.getSpecification());
            row.add(requisitionBean.getUnit());
            row.add(requisitionBean.getQty());
            row.add(requisitionBean.getCorrespondName());
            row.add(requisitionBean.getStockName());
            row.add(requisitionBean.getInCorrespondName());
            row.add(requisitionBean.getInStockName());
            row.add(requisitionBean.getRemark());
            row.add(requisitionBean.getCreateBy());
            row.add(DateUtil.formatDate(requisitionBean.getCreateTime()));
            row.add(requisitionBean.getApprovalName());
            row.add(DateUtil.formatDate(requisitionBean.getApprovalTime()));
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        return excelData;
    }
}
