package com.uas.platform.b2b.erp.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.ProductSample;
import com.uas.platform.b2b.erp.model.ProductSampleApproval;
import com.uas.platform.b2b.erp.service.PurchaseSampleService;
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.temporary.model.OrderType;
import com.uas.platform.core.model.Constant;
import org.apache.axis.utils.StringUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 打样申请单
 *
 * @author hejq
 */
@Service
public class PurchaseSampleServiceImpl implements PurchaseSampleService {

	@Autowired
	private PurchaseProofingDao purchaseProofingDao;

	@Autowired
    private PurchaseProofingApprovalDao purchaseProofingApprovalDao;

	@Autowired
	private UserDao userDao;

	@Autowired
	private ProductDao productDao;

	@Autowired
	private EnterpriseDao enterpriseDao;

	@Autowired
	private VendorDao vendorDao;

	@Autowired
	private VendorService vendorService;

	@Autowired
    private NotExistProductService notExistProductService;

	@Override
	public List<PurchaseProofingItem> convertProofing(List<ProductSample> samples) {
		List<PurchaseProofingItem> proofingItems = new ArrayList<PurchaseProofingItem>();
		// 应用来源
		final String appId = "uas";
		long enUU = SystemSession.getUser().getEnterprise().getUu();
		for (ProductSample sample : samples) {
			List<PurchaseProofing> proofingList = purchaseProofingDao.findByEnUUAndCode(enUU, sample.getPs_code());
			List<Product> products = productDao.findByEnUUAndCode(enUU, sample.getPs_prodcode());
			List<NotExistProduct> productList = new ArrayList<>();
			String sign = "";
			if (!CollectionUtils.isEmpty(products)) {
				// 平台中不存在的单据&&物料已经上传到平台
				if (proofingList.size() == 0) {
					PurchaseProofing proofing = sample.convert();
					if (!CollectionUtils.isEmpty(proofing.getProofingItems())) {
						Long userUU = proofing.getUserUU();
						if (userUU != null) {
							List<User> users = userDao.findByEnUUAndUserUU(enUU, userUU);
							if (users.size() > 0) {
                                userUU = users.get(0).getUserUU();
                            } else {
                                userUU = SystemSession.getUser().getUserUU();
                            }
						} else {
                            userUU = SystemSession.getUser().getUserUU();
                        }
						// 单据中能获取到申请人的uu号，并且有效则为申请人，否则为企业管理员
						proofing.setUserUU(userUU);
						proofing.setUser(null);
						proofing.setProduct(products.get(0));
						proofing.setProductId(products.get(0).getId());
                        // 对明细遍历
						for (PurchaseProofingItem proofingItem : proofing.getProofingItems()) {
							proofingItem.setProofing(proofing);
							List<Vendor> vendors = vendorDao.findByMyEnUUAndVendUU(enUU, proofingItem.getVendUU());
							Vendor vendor = null;
                            // 供应商列表中不存在供应商关系
							if (vendors.size() == 0) {
                                // 增加供应商关系
								vendor = addVendor(proofingItem);
								if (null != vendor) {
									vendorService.addPartnerShipRecord(vendor, appId);
								}
							} else {
								vendor = vendors.get(0);
							}
                            // 供应商uu号不为非法的值
							if (vendor != null) {
								// 如果明细中客户联系人UU号为空或者UU号不存在对应的用户，则设为供应商资料中的供应商联系人（可能为空）
								if (proofingItem.getVendUserUU() != null) {
									List<User> vendUsers = userDao.findByEnUUAndUserUU(vendor.getVendEnUU(),
											proofingItem.getVendUserUU());
									if (vendUsers.size() == 0) {
                                        proofingItem.setVendUserUU(vendor.getVendUserUU());
                                    }
								} else {
                                    proofingItem.setVendUserUU(vendor.getVendUserUU());
                                }
								proofingItem.setErpDate(new Date(System.currentTimeMillis()));
								proofingItem.setDate(new Date(System.currentTimeMillis()));
								proofingItems.add(proofingItem);
							}
						}
					}
				}
			} else {
			    if (StringUtils.isEmpty(sign)) {
			        sign = StringUtil.uuid();
                }
                productList.add(new NotExistProduct(sample.getPs_prodcode(), enUU, OrderType.proof.name(), sample.getPs_code(), Constant.NO, sign));
			}
			if (!CollectionUtils.isEmpty(productList)) {
                notExistProductService.batchSave(productList, ExceptionNote.PROOF_PRODUCT_NOTFOUND.getPhrase(), sign);
            }
		}
		return proofingItems;
	}

	/**
	 * 添加供应商资料
	 * 
	 * @param proofingItem
	 */
	private Vendor addVendor(PurchaseProofingItem proofingItem) {
		Enterprise enterprise = enterpriseDao.findOne(proofingItem.getVendUU());
		if (enterprise != null) {
			Vendor vendor = new Vendor();
			vendor.setMyEnUU(proofingItem.getProofing().getEnUU());
			vendor.setMyUserUU(SystemSession.getUser().getUserUU());
			vendor.setMyEnterprise(SystemSession.getUser().getEnterprise());
			vendor.setVendorEnterprise(enterprise);
			vendor.setVendEnUU(enterprise.getUu());
			vendor.setCustswitch(Constant.YES);
			vendor.setVendswitch(Constant.YES);
			if (proofingItem.getVendUserUU() != null) {
				List<User> users = userDao.findByEnUUAndUserUU(enterprise.getUu(), proofingItem.getVendUserUU());
				if (users.size() > 0) {
					vendor.setVendUserUU(proofingItem.getVendUserUU());
				}
			}
			return vendorDao.save(vendor);
		}
		return null;
	}

	@Override
	public List<PurchaseProofingApproval> convertApproval(List<ProductSampleApproval> sampleApprovals) {
		List<PurchaseProofingApproval> proofingApprovals = new ArrayList<PurchaseProofingApproval>();
		for (ProductSampleApproval sampleApproval : sampleApprovals) {
			if (sampleApproval.getPa_venduu() != null) {
				List<Vendor> vendors = vendorDao.findByMyEnUUAndVendUU(SystemSession.getUser().getEnterprise().getUu(),
						sampleApproval.getPa_venduu());
				if (vendors.size() > 0) {
                    proofingApprovals.add(sampleApproval.convert());
                }
			}
		}
		return proofingApprovals;
	}

	/**
	 * 查询打样申请单对应的平台的id
	 *
	 * @param productSamples 打样申请
	 * @return
	 */
	@Override
	public List<ProductSample> getB2bId(List<ProductSample> productSamples) {
	    for (ProductSample sample : productSamples) {
	        List<PurchaseProofing> proofings = purchaseProofingDao.findByEnUUAndErpId(SystemSession.getUser().getEnterprise().getUu(), sample.getPs_id());
	        if (!CollectionUtils.isEmpty(proofings)) {
	            sample.setPs_b2bid(proofings.get(0).getId());
            }
        }
		return productSamples;
	}

    /**
     * 查询认定单对应的平台的id
     *
     * @param sampleApprovals erp认定单
     * @return
     */
    @Override
    public List<ProductSampleApproval> getApprovalB2bId(List<ProductSampleApproval> sampleApprovals) {
        for (ProductSampleApproval sample : sampleApprovals) {
            List<PurchaseProofingApproval> proofings = purchaseProofingApprovalDao.findByEnUUAndErpId(SystemSession.getUser().getEnterprise().getUu(), sample.getPa_id());
            if (!CollectionUtils.isEmpty(proofings)) {
                sample.setPa_b2bid(proofings.get(0).getId());
            }
        }
        return sampleApprovals;
    }
}
