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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.uas.platform.b2b.erp.model.AcceptNotify;
import com.uas.platform.b2b.erp.model.AcceptNotifyConfirm;
import com.uas.platform.b2b.erp.model.AcceptNotifyVerify;
import com.uas.platform.b2b.erp.model.PurchaseNotify;
import com.uas.platform.b2b.erp.service.PurchaseNotifyService;
import com.uas.platform.b2b.erp.support.ErpBufferedLogger;
import com.uas.platform.b2b.model.PurchaseNotice;
import com.uas.platform.b2b.service.PurchaseNoticeService;
import com.uas.platform.core.logging.BufferedLoggerManager;
import com.uas.platform.core.util.serializer.FlexJsonUtils;
import org.apache.axis.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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 java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

/**
 * 对买家ERP的数据接口<br>
 * 买家送货提醒
 * 
 * @author yingp
 * 
 */
@Controller
@RequestMapping("/erp/purchase/notice")
public class PurchaseNotifyController {

	@Autowired
	private PurchaseNotifyService purchaseNotifyService;

	@Autowired
	private PurchaseNoticeService purchaseNoticeService;

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

	/**
	 * 将ERP的送货提醒写到平台
	 * 
	 * @param data
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public List<PurchaseNotify> saveNotifies(@RequestParam("data") String data) throws UnsupportedEncodingException {
		String jsonStr = URLDecoder.decode(data, "UTF-8");
		List<PurchaseNotify> notifies = FlexJsonUtils.fromJsonArray(jsonStr, PurchaseNotify.class);
		List<PurchaseNotice> noticeList = purchaseNotifyService.convertPurchaseNotify(notifies);
		noticeList = purchaseNoticeService.save(noticeList);
		logger.log("送货提醒", "上传送货提醒", notifies.size());
		return purchaseNotifyService.getB2bIdByNotices(noticeList);
	}

	/**
	 * 将送货提醒写到平台（EDI）
	 *
	 * @param data
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/EDI", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap saveEDINotifies(@RequestParam("data") String data) throws UnsupportedEncodingException {
		ModelMap map = new ModelMap();
		if (null == data) {
			map.put("success", false);
			map.put("message", "未传入参数！");
			return map;
		}
//		List<PurchaseNotify> modifiedNotifies = new ArrayList<PurchaseNotify>();
		String jsonStr = URLDecoder.decode(data, "UTF-8");
		JSONObject jsonObject = JSON.parseObject(jsonStr);
		if (StringUtils.isEmpty(jsonObject.getString("enUU")) || StringUtils.isEmpty(jsonObject.getString("PurchaseNotify"))) {
			map.put("success", false);
			map.put("message", "参数名有误！");
			return map;

		}
		List<PurchaseNotify> notifies = FlexJsonUtils.fromJsonArray(jsonObject.getString("PurchaseNotify"), PurchaseNotify.class);
		Long enUU = FlexJsonUtils.fromJson(jsonObject.getString("enUU"), Long.class);
		List<List<PurchaseNotice>> lists = purchaseNotifyService.convertEDIPurchaseNotify(notifies, enUU);
		purchaseNoticeService.save(lists.get(0));
		List<PurchaseNotice> oppNotices = lists.get(1);
		if (!CollectionUtils.isEmpty(oppNotices)) {
			for (PurchaseNotice notice : oppNotices) {
				PurchaseNotify notify = new PurchaseNotify();
				notify.setPn_id(notice.getSourceId());
				notify.setPn_qty(notice.getQty());
//				modifiedNotifies.add(notify);
			}
		}
		logger.log("送货提醒", "上传送货提醒", notifies.size());
		map.put("success", true);
		return map;
	}

	/**
	 * 从买家ERP获取平台的发货单
	 * 
	 * @return
	 */
	@RequestMapping(value = "/accept", method = RequestMethod.GET)
	@ResponseBody
	public List<AcceptNotify> getAcceptNotify() {
		List<AcceptNotify> notifies = purchaseNotifyService.convertSaleSend(purchaseNoticeService.findNotUploadSend());
		logger.log("供应商发货单", "下载来自供应商的发货单", notifies.size());
		return notifies;
	}


	/**
	 * 平台的发货单传到ERP之后，修改平台里面的发货单的状态
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/accept/back", method = RequestMethod.POST)
	@ResponseBody
	public void onSendSuccess(@RequestParam("data") String data) throws UnsupportedEncodingException {
		purchaseNoticeService.onSendUploadSuccess(URLDecoder.decode(data, "UTF-8").split(","));
	}

	/**
	 * 从买家ERP获取平台的发货单(EDI)
	 *
	 * @return
	 */
	@RequestMapping(value = "/accept/EDI", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap getEDIAcceptNotify(@RequestParam("data") String data) throws UnsupportedEncodingException {
		ModelMap map = new ModelMap();
		if (null == data) {
			map.put("success", false);
			map.put("message", "未传入参数！");
			return map;
		}
		String enUU = URLDecoder.decode(data, "UTF-8");
		List<AcceptNotify> notifies = purchaseNotifyService.convertSaleSend(purchaseNoticeService.findNotUploadSendEDI(Long.valueOf(enUU)));
		logger.log("供应商发货单", "下载来自供应商的发货单", notifies.size());
		map.put("success", true);
		map.put("AcceptNotify", notifies);
		return map;
	}

	/**
	 * 平台的发货单传到ERP之后，修改平台里面的发货单的状态(EDI)
	 *
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/accept/back/EDI", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap onSendSuccessEDI(@RequestParam("data") String data) throws UnsupportedEncodingException {
		ModelMap map = new ModelMap();
		if (null == data) {
			map.put("success", false);
			map.put("message", "未传入参数！");
			return map;
		}
		purchaseNoticeService.onSendUploadSuccess(URLDecoder.decode(data, "UTF-8").split(","));
		map.put("success", true);
		return map;
	}

	/**
	 * 买家ERP主动收料的记录上传到平台 <br>
	 * 买卖双方直接电话沟通之后，结果由买家填写到ERP系统的情况
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/accept", method = RequestMethod.POST)
	@ResponseBody
	public void send(@RequestParam("data") String data) throws UnsupportedEncodingException {
		String jsonStr = URLDecoder.decode(data, "UTF-8");
		List<AcceptNotify> accepts = FlexJsonUtils.fromJsonArray(jsonStr, AcceptNotify.class);
		purchaseNoticeService.send(purchaseNotifyService.convertAcceptNotify(accepts));
		logger.log("主动收料通知单", "上传主动收料通知单", accepts.size());
	}

	/**
	 * 买家结案送货提醒后，传到平台
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/end", method = RequestMethod.POST)
	@ResponseBody
	public void end(@RequestParam("data") String data) throws UnsupportedEncodingException {
		String jsonStr = URLDecoder.decode(data, "UTF-8");
		List<PurchaseNotify> ends = FlexJsonUtils.fromJsonArray(jsonStr, PurchaseNotify.class);
		purchaseNoticeService.end(ends);
		logger.log("送货提醒", "上传结案送货提醒", ends.size());
	}

	/**
	 * 买家修改收料通知的数量后，写回到平台（UAS点全部拒收）
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/accept/confirm", method = RequestMethod.POST)
	@ResponseBody
	public void onConfirm(@RequestParam("data") String data) throws UnsupportedEncodingException {
		String jsonStr = URLDecoder.decode(data, "UTF-8");
		List<AcceptNotifyConfirm> confirms = FlexJsonUtils.fromJsonArray(jsonStr, AcceptNotifyConfirm.class);
		purchaseNoticeService.onSaleSendChange(purchaseNotifyService.convertAcceptNotifyDetail(confirms));
		logger.log("送货提醒", "上传收料通知的确认数量", confirms.size());
	}

	/**
	 * 买家收料通知转收料单的数量，写回到平台
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/accept/verify", method = RequestMethod.POST)
	@ResponseBody
	public void onVerify(@RequestParam("data") String data) throws UnsupportedEncodingException {
		String jsonStr = URLDecoder.decode(data, "UTF-8");
		List<AcceptNotifyVerify> verifies = FlexJsonUtils.fromJsonArray(jsonStr, AcceptNotifyVerify.class);
		purchaseNoticeService.onVerify(purchaseNotifyService.convertAcceptNotifyVerify(verifies));
		logger.log("送货提醒", "上传转收料单的数量", verifies.size());
	}

	/**
	 * 买家反审核收料单的数量，写回到平台
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/accept/unverify", method = RequestMethod.POST)
	@ResponseBody
	public void onUnVerify(@RequestParam("data") String data) throws UnsupportedEncodingException {
		String jsonStr = URLDecoder.decode(data, "UTF-8");
		List<AcceptNotifyVerify> verifies = FlexJsonUtils.fromJsonArray(jsonStr, AcceptNotifyVerify.class);
		purchaseNoticeService.unVerify(purchaseNotifyService.convertAcceptUnauditVerify(verifies));
		logger.log("送货提醒", "上传反审核收料单的数量", verifies.size());
	}

}
