package com.uas.platform.b2b.service.impl;

import com.uas.platform.b2b.core.util.StringUtil;
import com.uas.platform.b2b.dao.*;
import com.uas.platform.b2b.erp.exception.ExceptionNote;
import com.uas.platform.b2b.erp.model.*;
import com.uas.platform.b2b.model.*;
import com.uas.platform.b2b.model.Attach;
import com.uas.platform.b2b.service.NotExistOrderService;
import com.uas.platform.b2b.service.NotExistProductService;
import com.uas.platform.b2b.service.SaleOrderItemService;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.b2b.support.UsageBufferedLogger;
import com.uas.platform.b2b.temporary.model.OrderType;
import com.uas.platform.core.logging.BufferedLoggerManager;
import com.uas.platform.core.model.Constant;
import com.uas.platform.core.model.Status;
import org.apache.axis.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 明细附件
 *
 * Created by hejq on 2018-06-19.
 */
@Service
public class SaleOrderItemServiceImpl implements SaleOrderItemService {

    @Autowired
    private SaleOrderItemDao itemDao;

    @Autowired
    private PurchaseOrderDao orderDao;

    @Autowired
    private ProductDao productDao;

    @Autowired
    private NotExistProductService notExistProductService;

    @Autowired
    private NotExistOrderService orderService;

    private final static UsageBufferedLogger logger = BufferedLoggerManager.getLogger(UsageBufferedLogger.class);

    /**
     * 批量保存
     *
     * @param items
     */
    @Override
    public void save(List<SaleOrderItem> items) {
        if (!CollectionUtils.isEmpty(items)) {
            items = itemDao.save(items);
            for (SaleOrderItem item : items) {
                orderDao.updatePurchaseStatus((short) Status.NOT_REPLY.value(), item.getPuId());
                logger.log("更新采购单状态", "通过自动上传采购单明细更新采购单状态", "pd_id: " + item.getId() + ";pu_id: " + item.getPuId());
            }
        }
    }

    /**
     * 将ERP采购单明细封装成平台所需明细
     *
     * @param details 采购单明细
     * @return
     */
    @Override
    public List<SaleOrderItem> covert(List<PurchaseDetail> details) {
        List<SaleOrderItem> items = new ArrayList<>();
        Long enUU = SystemSession.getUser().getEnterprise().getUu();
        List<NotExistOrders> ordersList = new ArrayList<>();
        String sign = "";
        for (PurchaseDetail detail : details) {
            List<PurchaseOrder> orders = orderDao.findByEnUUAndCode(enUU, detail.getPd_code());
            if (!CollectionUtils.isEmpty(orders)) {
                Long puId = orders.get(0).getId();
                SaleOrderItem item = convert(detail);
                if (null != item) {
                    item.setPuId(puId);
                    items.add(item);
                }
            } else {
                if (StringUtils.isEmpty(sign)) {
                    sign = StringUtil.uuid();
                }
                ordersList.add(new NotExistOrders(enUU, detail.getPd_code(), OrderType.saleMain.name(), Constant.NO, sign));
            }
        }
        if (!CollectionUtils.isEmpty(ordersList)) {
            orderService.batchSave(ordersList, ExceptionNote.SALE_NOTFOUND.getPhrase(), sign);
        }
        return items;
    }

    /**
     * 将ERP采购单明细封装成平台所需明细
     *
     * @param detail 采购单明细
     * @return
     */
    private SaleOrderItem convert(PurchaseDetail detail) {
        Long enUU = SystemSession.getUser().getEnterprise().getUu();
        SaleOrderItem item = new SaleOrderItem();
        item.setDelivery(detail.getPd_delivery());
        item.setNumber(detail.getPd_detno());
        item.setPrice(detail.getPd_price());
        item.setQty(detail.getPd_qty());
        item.setTaxrate(detail.getPd_rate());
        item.setFactory(detail.getPd_factory());
        item.setVendspec(detail.getPd_vendspec());
        item.setRemark(detail.getPd_remark());
        item.setStatus((short) Status.NOT_REPLY.value());
        item.setBeipin(detail.getPd_beipin());
        item.setErpDate(new Date(System.currentTimeMillis()));
        if (!org.apache.commons.collections.CollectionUtils.isEmpty(detail.getAttaches())) {
            Set<Attach> b2bAttaches = new HashSet<Attach>();
            for(com.uas.platform.b2b.erp.model.Attach attach : detail.getAttaches()) {
                com.uas.platform.b2b.model.Attach b2bAttach = attach.convertToB2bAttach("客户采购订单明细物料附件");
                b2bAttaches.add(b2bAttach);
            }
            item.setAttachs(b2bAttaches);
        }
        List<Product> products = productDao.findByEnUUAndCode(enUU, detail.getPd_prodcode());
        if (!CollectionUtils.isEmpty(products)) {
            item.setProductId(products.get(0).getId());
            return item;
        }  else {
            List<NotExistProduct> productList = new ArrayList<>();
            String sign = StringUtil.uuid();
            productList.add(new NotExistProduct(detail.getPd_prodcode(), enUU,  OrderType.purchase.name(),
                    detail.getPd_code(), detail.getPd_detno(), sign));
            notExistProductService.batchSave(productList, ExceptionNote.SALE_PRODUCT_NOTFOUND.getPhrase(), sign);
        }
        return null;
    }
}
