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.Inquiry;
import com.uas.platform.b2b.erp.model.InquiryDecide;
import com.uas.platform.b2b.erp.model.InquiryDetail;
import com.uas.platform.b2b.erp.model.InquiryDetailDet;
import com.uas.platform.b2b.erp.service.InquiryService;
import com.uas.platform.b2b.erp.service.VendorService;
import com.uas.platform.b2b.erp.support.ErpBufferedLogger;
import com.uas.platform.b2b.event.PurchaseInquiryItemSaveReleaseEvent;
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.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 采购询价
 *
 * @author hejq
 */
@Service
public class InquiryServiceImpl implements InquiryService {

	@Autowired
	private ProductDao productDao;

	@Autowired
	private VendorDao vendorDao;

	@Autowired
	private PurchaseInquiryDao purchaseInquiryDao;

	@Autowired
	private PurchaseInquiryItemDao purchaseInquiryItemDao;

	@Autowired
	private SaleQuotationItemDao saleQuotationItemDao;

	@Autowired
	private EnterpriseDao enterpriseDao;

	@Autowired
	private UserDao userDao;

	@Autowired
    private CommonDao commonDao;

	@Autowired
	private VendorService vendorService;

	@Autowired
    private NotExistProductService notExistProductService;

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

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

	@Override
	public List<PurchaseInquiryItemTemp> convertInquiry(List<Inquiry> inquiries) {
		List<PurchaseInquiryItemTemp> tempList = new ArrayList<PurchaseInquiryItemTemp>();
        // 应用来源
		final String appId = "uas";
		long enUU = SystemSession.getUser().getEnterprise().getUu();
		for (Inquiry inquiry : inquiries) {
			// 先查看是否已存在
			List<PurchaseInquiry> existInquiries = purchaseInquiryDao.findByEnUUAndCode(enUU, inquiry.getIn_code());
            // 不存在才继续，存在不作操作
			if (existInquiries.size() == 0) {
				PurchaseInquiry purchaseInquiry = inquiry.convert();
				// 如果记录人UU在b2b找不到，设置为null
				if (null != purchaseInquiry.getRecorderUU()) {
					User recorder = userDao.findOne(purchaseInquiry.getRecorderUU());
					if (null == recorder) {
						purchaseInquiry.setRecorderUU(null);
					}
				}
				if (!CollectionUtils.isEmpty(purchaseInquiry.getInquiryItems())) {
                    List<NotExistProduct> productList = new ArrayList<>();
                    String sign = "";
					for (PurchaseInquiryItem item : purchaseInquiry.getInquiryItems()) {
						// 存储时间
						item.setErpDate(new Date(System.currentTimeMillis()));
						Vendor vendor = null;
						// 不存在先设置
						if (item.getUserUU() == null || item.getUserUU() == 0) {
							item.setUserUU(SystemSession.getUser().getUserUU());
						}
						List<Vendor> vendors = vendorDao.findByMyEnUUAndVendUU(purchaseInquiry.getEnUU(), item.getVendUU());
						if (vendors.size() > 0) {
							vendor = vendors.get(0);
							// 如果询价单明细行没有指定供应商联系人，取平台中供应商资料中的联系人
							if (item.getVendUserUU() == null || item.getVendUserUU() == 0) {
								item.setVendUserUU(vendor.getVendUserUU());
							}
						} else {
							// 添加供应商资料
							vendor = addVendor(item);
							// 添加合作伙伴关系
							if (null != vendor) {
								vendorService.addPartnerShipRecord(vendor, appId);
							}
						}
						if (vendor != null) {
							// 取平台的产品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());
							} else {
								if (StringUtils.isEmpty(sign)) {
									sign = StringUtil.uuid();
								}
                                productList.add(new NotExistProduct(product.getCode(), enUU, OrderType.inquiry.name(), inquiry.getIn_code(), item.getNumber(), sign));
							}
							item.setInquiry(purchaseInquiry);
							PurchaseInquiryTemp temp = new PurchaseInquiryTemp();
							BeanUtils.copyProperties(purchaseInquiry, temp, PurchaseInquiryTemp.class);
							PurchaseInquiryItemTemp itemTemp = new PurchaseInquiryItemTemp();
							BeanUtils.copyProperties(item, itemTemp, PurchaseInquiryItemTemp.class);
							itemTemp.setInquiry(temp);
							tempList.add(itemTemp);
						}
					}
					if (!CollectionUtils.isEmpty(productList)) {
					    notExistProductService.batchSave(productList, ExceptionNote.INQUIRY_PRODUCT_NOTFOUND.getPhrase(), sign);
                    }
				}
			}
		}
		return tempList;
	}

	@Override
	public List<InquiryDetail> convertPurchaseInquiryReply(List<PurchaseInquiryItem> inquiryItems) {
		List<InquiryDetail> details = new ArrayList<InquiryDetail>();
		if (!CollectionUtils.isEmpty(inquiryItems)) {
			for (PurchaseInquiryItem item : inquiryItems) {
				details.add(new InquiryDetail(item));
			}
		}
		return details;
	}

	@Override
	public List<PurchaseInquiryItem> convertInquiryDecide(List<InquiryDecide> decides) {
		List<PurchaseInquiryItem> inquiryItems = new ArrayList<PurchaseInquiryItem>();
		if (!CollectionUtils.isEmpty(decides)) {
			long enUU = SystemSession.getUser().getEnterprise().getUu();
			for (InquiryDecide decide : decides) {
				List<PurchaseInquiryItem> items = purchaseInquiryItemDao.findByEnUUAndCodeAndNumber(enUU, decide.getIn_code(),
						decide.getId_detno());
				if (!CollectionUtils.isEmpty(items)) {
					PurchaseInquiryItem item = items.get(0);
					item.setAgreed(decide.getId_agreed());
					item.setDecideStatus((short) Status.NOT_UPLOAD.value());
					inquiryItems.add(item);
				}
			}
		}
		return inquiryItems;
	}

	@Override
	public List<Inquiry> convertSaleQuotation(List<SaleQuotation> quotations) {
		List<Inquiry> inquiries = new ArrayList<Inquiry>();
		if (!CollectionUtils.isEmpty(quotations)) {
			for (SaleQuotation quotation : quotations) {
				inquiries.add(new Inquiry(quotation));
			}
		}
		return inquiries;
	}

	@Override
	public List<SaleQuotationItem> convertQuotationDecide(List<InquiryDecide> decides) {
		List<SaleQuotationItem> quotationItems = new ArrayList<SaleQuotationItem>();
		if (!CollectionUtils.isEmpty(decides)) {
			for (InquiryDecide decide : decides) {
				List<SaleQuotationItem> items = saleQuotationItemDao
						.findByQuotationIdAndNumber(decide.getB2b_qu_id(), decide.getId_detno());
				if (!CollectionUtils.isEmpty(items)) {
					SaleQuotationItem item = items.get(0);
					item.setAgreed(decide.getId_agreed());
					item.setDecideStatus((short) Status.NOT_UPLOAD.value());
					quotationItems.add(item);
				}
			}
		}
		return quotationItems;
	}


    /**
	 * 添加供应商资料
	 * 
	 * @param inquiryItem
	 */
	private Vendor addVendor(PurchaseInquiryItem inquiryItem) {
		Vendor vendor = new Vendor();
		vendor.setMyEnUU(SystemSession.getUser().getEnterprise().getUu());
		if (inquiryItem.getUserUU() != null && inquiryItem.getUserUU() != 0) {
			vendor.setMyUserUU(inquiryItem.getUserUU());
		} else {
			vendor.setMyUserUU(SystemSession.getUser().getUserUU());
		}
		vendor.setMyUserUU(SystemSession.getUser().getUserUU());
		vendor.setMyEnterprise(SystemSession.getUser().getEnterprise());
		vendor.setCustswitch(Constant.YES);
		vendor.setVendswitch(Constant.YES);
		Enterprise vendEnterprise = enterpriseDao.findOne(inquiryItem.getVendUU());
		if (vendEnterprise != null) {
			vendor.setVendorEnterprise(vendEnterprise);
			vendor.setVendEnUU(inquiryItem.getVendUU());
			if (inquiryItem.getVendUserUU() != null) {
				List<User> users = userDao.findByEnUUAndUserUU(vendEnterprise.getUu(), inquiryItem.getVendUserUU());
				if (users.size() > 0) {
					vendor.setVendUserUU(inquiryItem.getVendUserUU());
				} else {
					vendor.setVendUserUU(vendEnterprise.getEnAdminuu());
					inquiryItem.setVendUserUU(vendEnterprise.getEnAdminuu());
				}
			} else {
				vendor.setVendUserUU(vendEnterprise.getEnAdminuu());
				inquiryItem.setVendUserUU(vendEnterprise.getEnAdminuu());
			}
			usageLogger.log("添加供应商资料", "通过询价单【" + inquiryItem.getId() + "】自动添加供应商【" + inquiryItem.getVendUU() + "】");
			return vendorDao.save(vendor);
		}
		return null;
	}

    @Override
    public void save(List<InquiryDetail> details) {
        if(!CollectionUtils.isEmpty(details)) {
        	Set<String> codes = new HashSet<>();
        	List<PurchaseInquiryItem> items = new ArrayList<>();
            for(InquiryDetail detail : details) {
                //先查询已经上传的询价单主表信息
                Inquiry inquiry = getInquiry(detail.getIn_code(), detail.getId_id());
                if(null != inquiry) {
                    List<InquiryDetail> inquiryDetails = commonDao.query("select * from purc$inquiryitems where id_inid = " + inquiry.getIn_id() + " and id_sourceid = " + detail.getId_id(), InquiryDetail.class);
                    if(inquiryDetails.size() == 0) {
                        //查询对应平台的物料信息
                        List<Product> products = productDao.findByEnUUAndCode(SystemSession.getUser().getEnterprise().getUu(), detail.getId_prodcode());
                        if(products.size() > 0) {
                            Long prodId = products.get(0).getId();
                            Long id = commonDao.getJdbcTemplate().queryForLong("select purc$inquiryitems_seq.nextval from dual");
                            String sql = "insert into purc$inquiryitems(id_id,id_sourceid,id_number,id_inid,id_useruu,id_prid,id_currency,id_taxrate,id_remark,id_venduu,id_venduseruu,id_fromdate,id_todate,id_status,id_sendstatus,id_erpdate,id_date,id_sourceapp) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                            commonDao.getJdbcTemplate().update(sql, id,detail.getId_id(), detail.getId_detno(), inquiry.getIn_id(), SystemSession.getUser().getUserUU(), prodId, detail.getId_currency(), detail.getId_rate(), detail.getId_remark(), detail.getVe_uu(), detail.getVe_contactuu(), detail.getId_fromdate(), detail.getId_todate(), Status.NOT_REPLY.value(), Status.NOT_UPLOAD.value(), new Date(), inquiry.getIn_date(), "erp");
                            //插入分段信息
                            if(detail.getDets().size() > 0) {
                                for(InquiryDetailDet det : detail.getDets()) {
                                    sql = "insert into purc$inquiryreply (ir_id,ir_lapqty,ir_idid) VALUES (purc$inquiryreply_seq.nextval, ?, ?)";
                                    commonDao.getJdbcTemplate().update(sql, det.getIdd_lapqty() == null ? 0 :  det.getIdd_lapqty(), id);
                                }
                            }
                            logger.log("自动询价明细上传", "新增了自动询价的明细（" + id + "）", 1);
                        }
						// 产生消息
						PurchaseInquiryItem inquiryItem = purchaseInquiryItemDao.findByVendUUAndSourceId(detail.getVe_uu(), detail.getId_id());
						if (null != inquiryItem && null != inquiryItem.getInquiry() && !codes.contains(inquiryItem.getInquiry().getCode() + inquiryItem.getVendUU())) {
							// 可能存在一个单里两个企业都是注册了之后，同时传输明细的情况，所以需要enuu 和code 一起判断
							codes.add(inquiryItem.getInquiry().getCode() + inquiryItem.getVendUU());
							items.add(inquiryItem);
						}
                    }
                }
            }
            if (!CollectionUtils.isEmpty(items)) {
				ContextUtils.publishEvent(new PurchaseInquiryItemSaveReleaseEvent(items));
			}
        }
    }

    private Inquiry getInquiry(String in_code, Long id) {
	    String sql = "select in_id, in_date from purc$inquiry left join purc$inquiryitems on id_inid = in_id where in_code = '" + in_code + "' and in_enuu = " + SystemSession.getUser().getEnterprise().getUu() + " and purc$inquiryitems.id_sourceid <> " + id;
        List<Inquiry> inquiries = commonDao.getJdbcTemplate().query(sql, new BeanPropertyRowMapper<Inquiry>(Inquiry.class));
        return inquiries.size() > 0 ? inquiries.get(0) : null;
    }

	/**
	 * 通过ERP上传的数据查询平台存储的id
	 *
	 * @param inquiryList 询价信息
	 * @return 获取结果的询价信息
	 */
	@Override
	public List<Inquiry> getB2bId(List<Inquiry> inquiryList) {
		for (Inquiry inquiry : inquiryList) {
			List<PurchaseInquiry> inquiries = purchaseInquiryDao.findByEnUUAndSourceId(SystemSession.getUser().getEnterprise().getUu(), inquiry.getIn_id());
			if (!CollectionUtils.isEmpty(inquiries)) {
				inquiry.setIn_b2bid(inquiries.get(0).getId());
			}
		}
		return inquiryList;
	}
}
