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.PurchaseChange;
import com.uas.platform.b2b.erp.model.PurchaseChangeReply;
import com.uas.platform.b2b.erp.service.PurchaseChangeService;
import com.uas.platform.b2b.service.PurchaseOrderChangeService;
import com.uas.platform.core.util.serializer.FlexJsonUtils;

/**
 * 对买家ERP的数据接口<br>
 * 买家订单变更单处理
 * 
 * @author yingp
 * 
 */
@Controller
@RequestMapping("/erp/purchase/change")
public class PurchaseChangeController {

	@Autowired
	private PurchaseChangeService purchaseChangeService;

	@Autowired
	private PurchaseOrderChangeService purchaseOrderChangeService;

	/**
	 * 将ERP的采购变更单写到平台
	 * 
	 * @param data
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public void savePurchases(@RequestParam("data") String data) throws UnsupportedEncodingException {
		String jsonStr = URLDecoder.decode(data, "UTF-8");
		List<PurchaseChange> changes = FlexJsonUtils.fromJsonArray(jsonStr, PurchaseChange.class);
		purchaseOrderChangeService.save(purchaseChangeService.convertPurchaseChange(changes));
	}

	/**
	 * 买家ERP从平台获取变更单的回复信息
	 * 
	 * @return
	 */
	@RequestMapping(value = "/reply", method = RequestMethod.GET)
	@ResponseBody
	public List<PurchaseChangeReply> getReply() {
		return purchaseChangeService.convertPurchaseOrderChangeReply(purchaseOrderChangeService.findNotUploadReply());
	}

	/**
	 * 平台的变更单回复信息传到ERP之后，修改平台里面的变更单的回复状态
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/reply", method = RequestMethod.POST)
	@ResponseBody
	public void onReplySuccess(@RequestParam("data") String data) throws UnsupportedEncodingException {
		purchaseOrderChangeService.onReplyUploadSuccess(URLDecoder.decode(data, "UTF-8").split(","));
	}

}
