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

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
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.SaleAPBill;
import com.uas.platform.b2b.erp.service.SaleAPBillService;
import com.uas.platform.b2b.erp.support.ErpBufferedLogger;
import com.uas.platform.b2b.model.PurchaseApBill;
import com.uas.platform.b2b.service.PurchaseApBillService;
import com.uas.platform.core.logging.BufferedLoggerManager;

/**
 * 对卖家ERP的数据接口<br>
 * 客户应付票据
 * @author suntg
 *
 */
@Controller
@RequestMapping("/erp/sale/APBill")
public class SaleAPBillController {

	@Autowired
	private PurchaseApBillService purchaseApBillService;

	@Autowired
	private SaleAPBillService saleAPBillService;

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

	/**
	 * 卖家ERP从平台获取未下载的客户应付票据
	 * 
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public List<SaleAPBill> getSaleAPBills() {
		List<SaleAPBill> apBills = saleAPBillService.convertPurchaseApBills(purchaseApBillService.findNotUpload());
		logger.log("客户应付票据", "获取未下载的客户应付票据", apBills.size());
		return apBills;
	}

	/**
	 * 平台的客户应付票据传到供应商ERP之后，修改平台里面的客户应付票据的上传状态
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public void onSaleAPBillDownSuccess(@RequestParam("data") String data) throws UnsupportedEncodingException {
		purchaseApBillService.onUploadSuccess(URLDecoder.decode(data, "UTF-8").split(","));
	}
	
	/**
	 * 卖家ERP从平台获取未下载客户已反过帐的的客户采购验收单
	 * 
	 * @return
	 */
	@RequestMapping(value="/nonPosting", method = RequestMethod.GET)
	@ResponseBody
	public List<Long> getNonPosting() {
		List<Long> ids = new ArrayList<Long>();
		List<PurchaseApBill> apBills = purchaseApBillService.getNonPosting();
		if(! CollectionUtils.isEmpty(apBills)) {
			for(PurchaseApBill apBill : apBills) {
				ids.add(apBill.getId());
			}
		}
		logger.log("反过帐的的客户采购验收单", "下载反过帐的的客户采购验收单", apBills.size());
		return ids;
	}

	/**
	 * 平台的客户采购验收单传到供应商ERP之后，修改平台里面的客户采购验收单的上传状态
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value="/nonPosting", method = RequestMethod.POST)
	@ResponseBody
	public void onNonPostingDownSuccess(@RequestParam("data") String data) throws UnsupportedEncodingException {
		purchaseApBillService.onNonPostingUploadSuccess(URLDecoder.decode(data, "UTF-8").split(","));
	}

}