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

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

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 com.uas.platform.b2b.erp.model.APCheck;
import com.uas.platform.b2b.erp.service.APCheckService;
import com.uas.platform.b2b.erp.support.ErpBufferedLogger;
import com.uas.platform.b2b.service.PurchaseApCheckService;
import com.uas.platform.core.logging.BufferedLoggerManager;
import com.uas.platform.core.util.serializer.FlexJsonUtils;

/**
 * 对卖家ERP的数据接口<br>
 * 应付对账单
 * @author aof
 * @date 2015年12月7日
 */
@Controller
@RequestMapping("/erp/sale/APCheck")
public class APCheckController {
	
	@Autowired
	private PurchaseApCheckService saleAPCheckService;
	
	@Autowired
	private APCheckService apCheckService;
	
	private final static ErpBufferedLogger logger = BufferedLoggerManager.getLogger(ErpBufferedLogger.class);
	
	/**
	 * 买家ERP从平台获取待下载的应付对账单
	 * 
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public List<APCheck> getApCheck() {
		List<APCheck> downs = apCheckService.convertApCheck(saleAPCheckService.findNotUploadAPcheck());
		logger.log("客户应付对账", "下载客户应付对账", downs.size());
		return downs;
	}
	
	/**
	 * 平台的应收对账传到供应商ERP之后，修改平台里面的订单的上传状态
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public void onApCheckSuccess(@RequestParam("data") String data) throws UnsupportedEncodingException {
		saleAPCheckService.onApCheckSuccess(URLDecoder.decode(data, "UTF-8").split(","));
	}
	
	/**
	 * 买家ERP回复平台传入的应收账单(不同意和确认)
	 * 
	 * @return
	 */
	@RequestMapping(value="/reply",method = RequestMethod.POST)
	@ResponseBody
	public void getReply(@RequestParam("data") String data) throws UnsupportedEncodingException {
		String jsonStr = URLDecoder.decode(data, "UTF-8");
		List<APCheck> apChecks = FlexJsonUtils.fromJsonArray(jsonStr, APCheck.class);
		saleAPCheckService.saveApChecks(apCheckService.convertAPChecks(apChecks));
		logger.log("应收对账单", "上传客户应收对账单", apChecks.size());
	}
}
