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.MakeChange;
import com.uas.platform.b2b.erp.model.MakeChangeReply;
import com.uas.platform.b2b.erp.service.MakeChangeService;
import com.uas.platform.b2b.erp.support.ErpBufferedLogger;
import com.uas.platform.b2b.service.MakeOrderChangeService;
import com.uas.platform.core.logging.BufferedLoggerManager;
import com.uas.platform.core.util.serializer.FlexJsonUtils;

/**
 * 对买家ERP的数据接口<br>
 * 买家委外加工单变更单处理
 * 
 * @author suntg
 * @since 2015年8月7日10:35:50
 */
@Controller
@RequestMapping("/erp/make/change")
public class MakeChangeController {

	@Autowired
	private MakeChangeService makeChangeService;

	@Autowired
	private MakeOrderChangeService makeOrderChangeService;

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

	/**
	 * 将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<MakeChange> changes = FlexJsonUtils.fromJsonArray(jsonStr, MakeChange.class);
		makeOrderChangeService.save(makeChangeService.convertMakeChange(changes));
		logger.log("委外加工变更单", "上传委外加工变更单", changes.size());
	}

	/**
	 * 买家ERP从平台获取委外变更单的回复信息
	 * 
	 * @return
	 */
	@RequestMapping(value = "/reply", method = RequestMethod.GET)
	@ResponseBody
	public List<MakeChangeReply> getReply() {
		List<MakeChangeReply> replies = makeChangeService.convertMakeOrderChangeReply(
				makeOrderChangeService.findNotUploadReply());
		logger.log("委外变更单", "下载委外变更单回复信息", replies.size());
		return replies;
	}

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


}
