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

import com.uas.platform.b2b.core.util.StringUtil;
import com.uas.platform.b2b.core.util.ThreadTask;
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.erp.service.PurchaseService;
import com.uas.platform.b2b.erp.service.VendorService;
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.apache.axis.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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

/**
 * 采购单接
 *
 * @author hejq
 */
@Service
public class PurchaseServiceImpl implements PurchaseService {

	@Autowired
	private ProductDao productDao;

	@Autowired
	private VendorDao vendorDao;

	@Autowired
	private EnterpriseDao enterpriseDao;

	@Autowired
	private UserDao userDao;

	@Autowired
	private PurchaseOrderDao purchaseOrderDao;

	@Autowired
	private PurchaseOrderItemDao purchaseOrderItemDao;

	@Autowired
	private UserOrderDao userOrderDao;

	@Autowired
	private VendorService vendorService;

	@Autowired
    private NotExistProductService notExistProductService;

	@Autowired
    private CommonDao commonDao;

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

	@Override
	public List<PurcOrderInfoItem> convertPurchase(List<Purchase> purchases) {
		List<PurcOrderInfoItem> orderItems = new ArrayList<PurcOrderInfoItem>();
		// 应用来源
        final String appId = "uas";
		long enUU = SystemSession.getUser().getEnterprise().getUu();
		for (Purchase purchase : purchases) {
			// 先查看是否已存在
			List<PurchaseOrder> orders = purchaseOrderDao.findByEnUUAndCode(enUU, purchase.getPu_code());
			if (CollectionUtils.isEmpty(orders)) {
				PurchaseOrderInfo order = purchase.convert();
				// 将order的UserUU set 为em_uu
				List<Vendor> vendors = vendorDao.findByMyEnUUAndVendUU(order.getEnUU(), order.getVendUU());
				Vendor vendor = null;
				if (vendors.size() == 0) {
					// 供应商资料在平台上不存在 添加企业的供应商资料
					vendor = addVendor(order);
					if (null != vendor) {
						// 添加企业圈合作伙伴关系
						vendorService.addPartnerShipRecord(vendor, appId);
					}
				} else {// 供应商资料在平台上存在
					vendor = vendors.get(0);
					// 单据不包含供应商联系人UU号&&供应商列表中有供应商联系人
					if (order.getVendUserUU() == null || order.getVendUserUU() == 0) {
						// 将供应商列表中的联系人设为单据的供应商联系人
						order.setVendUserUU(vendor.getVendUserUU());
					}
					if (order.getUserUU() == null || order.getUserUU() == 0) {
						order.setUserUU(SystemSession.getUser().getUserUU());
					}
				}
				// 平台中存在供应商的UU&&单据有明细行
				if (vendor != null && !CollectionUtils.isEmpty(order.getOrderItems())) {
					if (order.getUserUU() != null) {
						List<User> myUsers = userDao.findByEnUUAndUserUU(
								SystemSession.getUser().getEnterprise().getUu(), order.getUserUU());
						if (myUsers.size() > 0) {
							order.setUserUU(myUsers.get(0).getUserUU());
						} else {
							// 单据所属用户UU号不属于客户企业时设为企业管理员
							order.setUserUU(SystemSession.getUser().getEnterprise().getEnAdminuu());
						}
					}
					order.setUser(null);
					List<NotExistProduct> productList = new ArrayList<>();
					String sign = "";
					for (PurcOrderInfoItem item : order.getOrderItems()) {
						item.setOrder(order);
						item.setStatus((short) Status.NOT_REPLY.value());
						// 取平台的产品ID
						Product product = item.getProduct();
						List<Product> products = productDao.findByEnUUAndCode(product.getEnUU(), product.getCode());
						if (products.size() > 0) {
							item.setProduct(products.get(0));
							item.setProductId(products.get(0).getId());
							item.setErpDate(new Date());
							orderItems.add(item);
						} else {
							if (StringUtils.isEmpty(sign)) {
								sign = StringUtil.uuid();
							}
							productList.add(new NotExistProduct(product.getCode(), enUU, OrderType.purchase.name(), purchase.getPu_code(), Constant.NO, sign));
						}
					}
					if (!CollectionUtils.isEmpty(productList)) {
						notExistProductService.batchSave(productList, ExceptionNote.SALE_PRODUCT_NOTFOUND.getPhrase(), sign);
					}
				}
			}
		}
		return orderItems;
	}

	@Override
	public List<PurchaseReply> convertPurchaseOrderReply(List<PurchaseOrderReply> orderReplies) {
		List<PurchaseReply> replies = new ArrayList<PurchaseReply>();
		for (PurchaseOrderReply orderReply : orderReplies) {
			replies.add(new PurchaseReply(orderReply));
		}
		return replies;
	}

	/**
	 * 添加供应商资料
	 * 
	 * @param order
	 */
	private Vendor addVendor(PurchaseOrderInfo order) {
		Vendor vendor = new Vendor();
		vendor.setMyEnUU(order.getEnUU());
		vendor.setMyEnterprise(SystemSession.getUser().getEnterprise());
		// 默认开启供应商
		vendor.setVendswitch(Constant.YES);
		vendor.setCustswitch(Constant.YES);
		// 买方用户（联系人）
		// 1、单据存在买方用户UU号：买方企业存在对应uu号的用户，设为该用户；买方企业不存在对应uu号的用户，供应商和单据设为当前用户(管理员)
		// 2、单据不存在买方用户UU号：供应商和单据设为当前用户(管理员)
		if (order.getUserUU() != null && order.getUserUU() != 0) {
			List<User> myUsers = userDao.findByEnUUAndUserUU(order.getEnUU(), order.getUserUU());
			if (myUsers.size() > 0) {
				vendor.setMyUserUU(order.getUserUU());
			} else {
				vendor.setMyUserUU(SystemSession.getUser().getUserUU());
				order.setUserUU(SystemSession.getUser().getUserUU());
			}
		} else {
			vendor.setMyUserUU(SystemSession.getUser().getUserUU());
			order.setUserUU(SystemSession.getUser().getUserUU());
		}
		Enterprise enterprise = enterpriseDao.findOne(order.getVendUU());
		// 供应商企业UU号存在对应的企业
		if (enterprise != null) {
			vendor.setVendorEnterprise(enterprise);
			vendor.setVendEnUU(order.getVendUU());
			if (order.getVendUserUU() != null) {
				List<User> users = userDao.findByEnUUAndUserUU(enterprise.getUu(), order.getVendUserUU());
				if (users.size() > 0) {
					vendor.setVendUserUU(order.getVendUserUU());
				} else {
					vendor.setVendUserUU(enterprise.getEnAdminuu());
					order.setVendUserUU(enterprise.getEnAdminuu());
				}
			} else {
				vendor.setVendUserUU(enterprise.getEnAdminuu());
				order.setVendUserUU(enterprise.getEnAdminuu());
			}
			logger.log("添加供应商", "通过订单【" + order.getCode() + "】自动添加供应商：【" + enterprise.getEnName() + "】，" + enterprise.getUu());
			vendor = vendorDao.save(vendor);
			saveUserOrders(vendor);
			return vendor;
		}
		return null;
	}

	private void saveUserOrders(final Vendor vendor){
		ThreadTask.getInstance().execute(new Runnable() {
			@Override
			public void run() {
				/* 添加供应商的阅读记录*/
				List<User> users = userDao.findByEnUU(vendor.getVendEnUU());
				UserOrders userOrders;
				List<UserOrders> list = new ArrayList<>();
				for (User user : users) {
					if (user == null) {
						continue;
					}
					userOrders = new UserOrders(user.getUserUU(), vendor.getVendEnUU(), vendor.getId(), "sale", "purc$vendors");
					list.add(userOrders);
				}
				userOrderDao.save(list);
			}
		});
	}

	@Override
	public List<PurchaseOrderReply> convertPurchaseReply(List<PurchaseReply> replies) {
		List<PurchaseOrderReply> orderReplies = new ArrayList<PurchaseOrderReply>();
		long enUU = SystemSession.getUser().getEnterprise().getUu();
		for (PurchaseReply reply : replies) {
			List<PurchaseOrderItem> items = purchaseOrderItemDao.findByEnUUAndOrderCodeAndNumber(enUU,
					reply.getPr_pucode(), reply.getPr_pddetno());
			if (!CollectionUtils.isEmpty(items)) {
				PurchaseOrderReply orderReply = reply.convert();
				orderReply.setOrderItem(items.get(0));
				orderReplies.add(orderReply);
			}
		}
		return orderReplies;
	}

	@Override
	public List<PurchaseOrderItem> convertPurchaseEnd(List<PurchaseDetailEnd> ends) {
		List<PurchaseOrderItem> orderItems = new ArrayList<PurchaseOrderItem>();
		long enUU = SystemSession.getUser().getEnterprise().getUu();
		for (PurchaseDetailEnd end : ends) {
			List<PurchaseOrderItem> items = purchaseOrderItemDao.findByEnUUAndOrderCodeAndNumber(enUU, end.getPd_code(),
					end.getPd_detno());
			if (!CollectionUtils.isEmpty(items)) {
				PurchaseOrderItem orderItem = items.get(0);
				orderItem.setEnd(end.getPd_ended());
				orderItem.setEndStatus((short) Status.NOT_UPLOAD.value());
				orderItems.add(orderItem);
			}
		}
		return orderItems;
	}

    @Override
    public List<MessageLog> convertMessageLog(List<PrintLog> printNotUploadReply) {
        List<MessageLog> messageLogs = new ArrayList<MessageLog>();
        for (PrintLog printlog: printNotUploadReply) {
        	messageLogs.add(new MessageLog(printlog));
		}
		return messageLogs;
    }

	/**
	 * 通过上传id查询平台采购单对应的id
	 *
	 * @param purchaseList purchase数组
	 * @return
	 */
	@Override
	public List<Purchase> getB2bId(List<Purchase> purchaseList) {
		for (Purchase purchase : purchaseList) {
            List<PurchaseOrder> purchaseOrders = purchaseOrderDao.findByEnUUAndAndErpId(SystemSession.getUser().getEnterprise().getUu(), purchase.getPu_id());
		    if (!CollectionUtils.isEmpty(purchaseOrders)) {
		        purchase.setPu_b2bid(purchaseOrders.get(0).getId());
            }
		}
		return purchaseList;
	}

    /**
     * 更新采购单价格
     *
     * @param detailPriceList 出入库单据
     * @param type            类型
     * @author hejq
     * @date 2018-06-28 15:37
     */
    @Override
    public void refreshPrice(List<OrderDetailPrice> detailPriceList, String type) {
        logger.log("更新采购单价格", "ERP单据:" + type + "，大小:" + detailPriceList.size());
        for (OrderDetailPrice detailPrice : detailPriceList) {
            String sql = "update purc$orderitems set pd_price = " + detailPrice.getPrice() + ", pd_taxrate = " + detailPrice.getTaxrate()
                    + " where pd_id = " + detailPrice.getId();
            commonDao.getJdbcTemplate().update(sql);
        }
    }
}
