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

import com.uas.platform.b2b.core.util.ContextUtils;
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.Make;
import com.uas.platform.b2b.erp.model.MakeEnd;
import com.uas.platform.b2b.erp.model.MakeReply;
import com.uas.platform.b2b.erp.model.OrderDetailPrice;
import com.uas.platform.b2b.erp.service.MakeService;
import com.uas.platform.b2b.erp.service.VendorService;
import com.uas.platform.b2b.event.MakeOrderEndReleaseEvent;
import com.uas.platform.b2b.model.*;
import com.uas.platform.b2b.service.NotExistProductService;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class MakeServiceImpl implements MakeService {

	@Autowired
	private MakeOrderDao makeOrderDao;

	@Autowired
	private ProductDao productDao;

	@Autowired
	private EnterpriseDao enterpriseDao;

	@Autowired
	private VendorDao vendorDao;

	@Autowired
	private VendorService vendorService;

	@Autowired
    private CommonDao commonDao;

	@Autowired
	private NotExistProductService notExistProductService;

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

	@Override
	public List<MakeOrder> convertMakes(List<Make> makes) {
		List<MakeOrder> makeOrders = new ArrayList<MakeOrder>();
		// 应用来源
        final String appId = "uas";
		long enUU = SystemSession.getUser().getEnterprise().getUu();
		for (Make make : makes) {
			List<MakeOrder> orders = makeOrderDao.findByEnUUAndCode(enUU, make.getMa_code());
			Enterprise vendor = enterpriseDao.findEnterpriseByUu(make.getVe_uu());
			List<Product> products = productDao.findByEnUUAndCode(enUU, make.getMa_prodcode());
            List<NotExistProduct> notExistProducts = new ArrayList<>();
            String sign = "";
            if (!CollectionUtils.isEmpty(products)) {
				if (orders.size() == 0 && vendor != null) {
					MakeOrder makeOrder = make.convert();
					Product product = products.get(0);
					makeOrder.setProduct(product);
					makeOrder.setProductId(product.getId());
					List<Vendor> vendors = vendorDao.findByMyEnUUAndVendUU(enUU, make.getVe_uu());
					Vendor vend = new Vendor();
					if (CollectionUtils.isEmpty(vendors)) {
						vend = addVendor(make);
						if (null != vend) {
							// 添加合作伙伴
							vendorService.addPartnerShipRecord(vend, appId);
						}
					} else {
						vend = vendors.get(0);
					}
					makeOrder.setUserUU(vend.getMyUserUU());
					makeOrder.setVendUserUU(vend.getVendUserUU());
					makeOrder.setErpDate(new Date());
					makeOrders.add(makeOrder);
				}
			} else {
				if (StringUtils.isEmpty(sign)) {
					sign = StringUtil.uuid();
				}
				notExistProducts.add(new NotExistProduct(make.getMa_prodcode(), enUU, OrderType.make.name(), make.getMa_code(), Constant.NO, sign));
			}
			if (!CollectionUtils.isEmpty(notExistProducts)) {
                notExistProductService.batchSave(notExistProducts, ExceptionNote.MAKE_PRODUCT_NOTFOUND.getPhrase(), sign);
            }
		}
		return makeOrders;
	}

	/**
	 * 增加供应商关系
	 * 
	 * @param make
	 */
	private Vendor addVendor(Make make) {
		Long vendUU = make.getVe_uu();
		if (vendUU == 0 || vendUU == null) {
			throw new IllegalArgumentException("委外订单增加供应商错误，供应商UU号参数错误");
		} else {
			Enterprise vend = enterpriseDao.findOne(vendUU);
			if (vend == null) {
                throw new IllegalArgumentException("委外订单增加供应商错误，供应商UU号参数错误");
            }
			Vendor vendor = new Vendor();
			vendor.setMyEnUU(SystemSession.getUser().getEnterprise().getUu());
			vendor.setMyEnterprise(SystemSession.getUser().getEnterprise());
			vendor.setVendEnUU(vend.getUu());
			vendor.setMyUserUU(SystemSession.getUser().getUserUU());
			vendor.setVendUserUU(vend.getEnAdminuu());
			return vendorDao.save(vendor);
		}
	}

	@Override
	public List<MakeReply> convertMakeOrderReply(List<MakeOrderReply> replies) {
		List<MakeReply> makeReplies = new ArrayList<MakeReply>();
		if (!CollectionUtils.isEmpty(replies)) {
			for (MakeOrderReply reply : replies) {
				makeReplies.add(new MakeReply(reply));
			}
		}
		return makeReplies;
	}

	@Override
	public List<MakeOrder> convertMakeEnd(List<MakeEnd> ends) {
		List<MakeOrder> makeOrders = new ArrayList<MakeOrder>();
		long enUU = SystemSession.getUser().getEnterprise().getUu();
		if (!CollectionUtils.isEmpty(ends)) {
			for (MakeEnd end : ends) {
				List<MakeOrder> existOrders = makeOrderDao.findByEnUUAndCode(enUU, end.getMa_code());
				if (!CollectionUtils.isEmpty(existOrders)) {
					MakeOrder makeOrder = existOrders.get(0);
					makeOrder.setEnd(end.getMa_ended());
					makeOrder.setEndSendStatus((short) Status.NOT_UPLOAD.value());
					makeOrders.add(makeOrder);
				}
			}
		}
		ContextUtils.publishEvent(new MakeOrderEndReleaseEvent(makeOrders));
		return makeOrders;
	}

	/**
	 * 更新委外单价格
	 *
	 * @param detailPriceList 出入库单据
	 * @param type            类型
	 * @author hejq
	 * @date 2018-06-28 16:57
	 */
	@Override
	public void refreshPrice(List<OrderDetailPrice> detailPriceList, String type) {
        logger.log("更新委外单价格", "ERP单据:" + type + "，大小:" + detailPriceList.size());
        for (OrderDetailPrice detailPrice : detailPriceList) {
            String sql = "update make$orders set ma_price = " + detailPrice.getPrice() + ", ma_taxrate = " + detailPrice.getTaxrate()
                    + " where ma_id = " + detailPrice.getId();
            commonDao.getJdbcTemplate().update(sql);
        }
	}
}
