package com.uas.platform.b2b.erp.controller;

import com.uas.platform.b2b.erp.model.PurchaseProdInOut;
import com.uas.platform.b2b.erp.service.PurchaseProdInOutService;
import com.uas.platform.b2b.erp.support.ErpBufferedLogger;
import com.uas.platform.b2b.service.PurchaseBadOutService;
import com.uas.platform.core.logging.BufferedLoggerManager;
import com.uas.platform.core.util.serializer.FlexJsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

/**
 * 对买家ERP的数据接口<br>
 * 买家不良品出库单接口
 * 
 * @author suntg
 * 
 */
@Controller
@RequestMapping("/erp/purchase/prodBadOut")
public class PurchaseProdBadOutController {

	@Autowired
	PurchaseBadOutService purchaseBadOutService;
	
	@Autowired
	PurchaseProdInOutService purchaseProdInOutService;

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

	/**
	 * 将ERP的不良品出库单写到平台
	 * 
	 * @param data
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public List<PurchaseProdInOut> savePurchases(@RequestParam("data") String data) throws UnsupportedEncodingException {
		String jsonStr = URLDecoder.decode(data, "UTF-8");
		List<PurchaseProdInOut> prodInOuts = FlexJsonUtils.fromJsonArray(jsonStr, PurchaseProdInOut.class);
		purchaseBadOutService.save(purchaseProdInOutService.convertBadOuts(prodInOuts));
		logger.log("不良品出库单", "上传不良品出库单", prodInOuts.size());
		return purchaseProdInOutService.getProdBadOutB2bId(prodInOuts);
	}

	/**
	 * 将ERP的反过账的不良品出库单写到平台
	 * 
	 * @param data
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value="/nonPosting", method = RequestMethod.POST)
	@ResponseBody
	public void nonPostingProdInOuts(@RequestParam("data") String data) throws UnsupportedEncodingException {
		String jsonStr = URLDecoder.decode(data, "UTF-8");
		List<PurchaseProdInOut> prodInOuts = FlexJsonUtils.fromJsonArray(jsonStr, PurchaseProdInOut.class);
		purchaseBadOutService.nonPosting(purchaseProdInOutService.convertNonPostingBadOuts(prodInOuts));
		logger.log("反过账的不良品出库单", "上传反过账的不良品出库单", prodInOuts.size());
	}

}
