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.SaleDownChange;
import com.uas.platform.b2b.erp.model.SaleDownChangeReply;
import com.uas.platform.b2b.erp.service.SaleDownChangeService;
import com.uas.platform.b2b.service.PurchaseOrderChangeService;
import com.uas.platform.core.util.serializer.FlexJsonUtils;

/**
 * 对卖家ERP的数据接口<br>
 * 
 * @author yingp
 *
 */
@Controller
@RequestMapping("/erp/sale/change")
public class SaleDownChangeController {

	@Autowired
	private PurchaseOrderChangeService purchaseOrderChangeService;

	@Autowired
	private SaleDownChangeService saleDownChangeService;

	/**
	 * 卖家ERP从平台获取未回复的采购变更单
	 * 
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public List<SaleDownChange> getOrderChanges() {
		return saleDownChangeService.convertPurchaseOrderChange(purchaseOrderChangeService.findNotUploadOrderChange());
	}

	/**
	 * 平台的变更单传到供应商ERP之后，修改平台里面的变更单的上传状态
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public void onSaleDownChangeSuccess(@RequestParam("data") String data) throws UnsupportedEncodingException {
		purchaseOrderChangeService.onSaleDownChangeSuccess(URLDecoder.decode(data, "UTF-8").split(","));
	}

	/**
	 * 将卖家ERP的变更单回复信息写到平台
	 * 
	 * @param data
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/reply", method = RequestMethod.POST)
	@ResponseBody
	public void saveChangeReplies(@RequestParam("data") String data) throws UnsupportedEncodingException {
		String jsonStr = URLDecoder.decode(data, "UTF-8");
		List<SaleDownChangeReply> replies = FlexJsonUtils.fromJsonArray(jsonStr, SaleDownChangeReply.class);
		purchaseOrderChangeService.reply(replies);
	}

	/**
	 * 卖家ERP从平台获取在平台回复的记录
	 * 
	 * @return
	 */
	@RequestMapping(value = "/reply", method = RequestMethod.GET)
	@ResponseBody
	public List<SaleDownChangeReply> getChangeReply() {
		return saleDownChangeService.convertOrderChangeReply(purchaseOrderChangeService.findNotSendReply());
	}

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

}