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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.uas.platform.b2b.dao.DeOrderDeleteLogDao;
import com.uas.platform.b2b.dao.DeputyOrderDao;
import com.uas.platform.b2b.dao.DeputyOrdersLogDao;
import com.uas.platform.b2b.dao.DeputyPaymentCompanyDao;
import com.uas.platform.b2b.erp.support.ErpBufferedLogger;
import com.uas.platform.b2b.mobile.dao.DeputyEnterpriseDao;
import com.uas.platform.b2b.model.*;
import com.uas.platform.b2b.service.DeputyOrderService;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.core.logging.BufferedLoggerManager;
import com.uas.platform.core.model.Status;
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 java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * ERP下载平台的代采订单
 *
 * @author hejq
 * @time 创建时间：2017年3月24日
 */
@Controller
@RequestMapping("/erp/sale/deputyOrder")
public class DeputyOrderDownController {

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

	@Autowired
	private DeputyOrderService deputyOrderService;

	@Autowired
	private DeputyOrderDao deputyOrderDao;

	@Autowired
	private DeputyEnterpriseDao deputyEnterpriseDao;

	@Autowired
	private DeputyPaymentCompanyDao deputyPaymentCompanyDao;

	@Autowired
	private DeputyOrdersLogDao deputyOrdersLogDao;

	@Autowired
	private DeOrderDeleteLogDao deOrderDeleteLogDao;

	/**
	 * 买家ERP从平台获取代采订单
	 *
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public List<DeputyOrder> getDeOrders() {
		List<DeputyOrder> deOrders = deputyOrderService.findByDeputyuu(SystemSession.getUser().getEnterprise().getUu());
		logger.log("代采定单", "下载客户的代采订单", deOrders.size());
		return deOrders;
	}

	/**
	 * 将已存入的数据id返回，更新下载状态
	 *
	 * @param data
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public void downloadStatus(@RequestParam("data") String data) throws UnsupportedEncodingException {
		String jsonStr = URLDecoder.decode(data, "UTF-8");
		String[] idStr = jsonStr.split(",");
		for (String id : idStr) {
			if (id != null) {
				DeputyOrder deOrder = deputyOrderDao.findOne(Long.valueOf(id));
				if (null != deOrder) {
					deOrder.setDownloadstatus("已下载");
					deOrder.setErpdate(new Date());
					deputyOrderDao.save(deOrder);
				}
			}
		}
	}

	/**
	 * 更新维护付款企业信息
	 *
	 * @param data
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/payCompany", method = RequestMethod.POST)
	@ResponseBody
	public void saveOrUpdatePayCompany(@RequestParam("data") String data) throws UnsupportedEncodingException {
		String jsonStr = URLDecoder.decode(data, "UTF-8");
		DeputyPaymentCompany company = JSON.parseObject(jsonStr, DeputyPaymentCompany.class);
		DeputyPaymentCompany deCompany = new DeputyPaymentCompany();
		// 先判断维护企业是不是代采企业
		DeputyEnterprise enterprise = deputyEnterpriseDao.findByDeputyenuu(SystemSession.getUser().getEnterprise().getUu());
		if (enterprise == null) {
			enterprise = new DeputyEnterprise();
			enterprise.setDate(new Date());
			enterprise.setDeputyenuu(SystemSession.getUser().getEnterprise().getUu());
			enterprise.setUseruu(SystemSession.getUser().getUserUU());
			enterprise.setEnuu(SystemSession.getUser().getEnterprise().getUu());
			deputyEnterpriseDao.save(enterprise);
			deCompany = deputyPaymentCompanyDao.findByEnuuAndEnname(SystemSession.getUser().getEnterprise().getUu(),
					company.getEnname());
			if (deCompany != null) {
				deCompany.setAddress(company.getAddress());
				deCompany.setDepuseruu(SystemSession.getUser().getUserUU());
				deCompany.setUser(company.getUser());
				deCompany.setUsertel(company.getUsertel());
				deCompany.setDate(new Date());
				deputyPaymentCompanyDao.save(deCompany);
				logger.log("付款企业", "更新付款企业信息", 1);
			} else {
				deputyPaymentCompanyDao.save(company);
				logger.log("付款企业", "新增付款企业信息", 1);
			}
		} else {
			deCompany = deputyPaymentCompanyDao.findByEnuuAndEnname(SystemSession.getUser().getEnterprise().getUu(),
					company.getEnname());
			if (deCompany != null) {
				deCompany.setAddress(company.getAddress());
				deCompany.setDepuseruu(SystemSession.getUser().getUserUU());
				deCompany.setUser(company.getUser());
				deCompany.setUsertel(company.getUsertel());
				deCompany.setDate(new Date());
				deputyPaymentCompanyDao.save(deCompany);
				logger.log("付款企业", "更新付款企业信息", 1);
			} else {
				deputyPaymentCompanyDao.save(company);
				logger.log("付款企业", "新增付款企业信息", 1);
			}
		}
	}

	/**
	 * 将重复的数据返回，保存记录
	 *
	 * @param data
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/repetitions", method = RequestMethod.POST)
	@ResponseBody
	public void downRepetitions(@RequestParam("data") String data) throws UnsupportedEncodingException {
		String jsonStr = URLDecoder.decode(data, "UTF-8");
		List<DeputyOrdersLog> logs = JSON.parseArray(jsonStr, DeputyOrdersLog.class);
		if (!CollectionUtils.isEmpty(logs)) {
			for (DeputyOrdersLog log : logs) {
				List<DeputyOrdersLog> oldLogs = deputyOrdersLogDao.findBySourceid(log.getSourceid());
				if (oldLogs.size() == 0) {
					log.setMessage("单号已存在");
					log.setDate(new Date());
					deputyOrdersLogDao.save(log);
				}
				DeputyOrder order = deputyOrderDao.findOne(log.getSourceid());
				order.setDownloadstatus("停止下载");
				deputyOrderDao.save(order);
			}
		}
	}

	/**
	 * 代采订单传输日志
	 *
	 * @param data
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/transferLogs", method = RequestMethod.POST)
	@ResponseBody
	public void transferLogs(@RequestParam("data") String data) throws UnsupportedEncodingException {
		String jsonStr = URLDecoder.decode(data, "UTF-8");
		List<DeputyOrdersLog> logs = JSON.parseArray(jsonStr, DeputyOrdersLog.class);
		if (!CollectionUtils.isEmpty(logs)) {
			for (DeputyOrdersLog log : logs) {
				DeputyOrder order = deputyOrderDao.findOne(log.getSourceid());
				if (order != null) {
					Integer size = order.getDeputyOrderItems().size();
					log.setSourceSize(size);
					if (log.getDownloadSize() < size) {
						log.setMessage("数据传输异常");
					} else {
						log.setMessage("success");
					}
					log.setDate(new Date());
					deputyOrdersLogDao.save(log);
				}
			}
		}
	}

	/**
	 * ERP审核不通过的单据传回来更新状态
	 *
	 * @param data
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/notAgreed/back", method = RequestMethod.POST)
	@ResponseBody
	public void notAgreedBills(@RequestParam("data") String data) throws UnsupportedEncodingException {
		String codeStr = URLDecoder.decode(data, "UTF-8");
		logger.log("代采订单驳回", "代采订单驳回尝试传回B2B：" + codeStr, 1);
		List<DeputyOrder> orders = JSONObject.parseArray(codeStr, DeputyOrder.class);
		List<DeputyOrder> deOrders = new ArrayList<DeputyOrder>();
		if (!CollectionUtils.isEmpty(orders)) {
			for (DeputyOrder order : orders) {
				DeputyOrder deOrder = deputyOrderDao.findByCodeAndDeputyuuAndDownloadstatus(order.getCode(),
						SystemSession.getUser().getEnterprise().getUu(), "已下载");
				if (deOrder != null) {
					deOrder.setDownloadstatus("待下载");
					deOrder.setEntrystatus("保存");
					deOrder.setStatuscode(Status.NOTAGREED.value());
					deOrder.setStatus(Status.NOTAGREED.name());
					deOrder.setRemark(order.getRemark());
					logger.log("代采订单驳回", "代采订单驳回传回B2B成功：" + order.getCode(), 1);
					deOrder = deputyOrderDao.save(deOrder);
					deOrders.add(deOrder);
				} else {
					logger.log("代采订单驳回", "未找到符合条件的代采订单：" + order.getCode(), 1);
				}
			}
			// ContextUtils.publishEvent(new DeputyorderReplyEvent(deOrders));
		}

	}

	/**
	 * ERP审核通过的单据传回来更新状态
	 *
	 * @param data
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/agreed/back", method = RequestMethod.POST)
	@ResponseBody
	public void agreedBills(@RequestParam("data") String data) throws UnsupportedEncodingException {
		String codeStr = URLDecoder.decode(data, "UTF-8");
		List<DeputyOrder> orders = JSONObject.parseArray(codeStr, DeputyOrder.class);
		List<DeputyOrder> deOrders = new ArrayList<DeputyOrder>();
		if (!CollectionUtils.isEmpty(orders)) {
			for (DeputyOrder order : orders) {
				// 发现ERP很多没有fromcode，所以更新为salecode
				DeputyOrder deOrder = deputyOrderDao.findByCodeAndDeputyuuAndDownloadstatus(order.getCode(),
						SystemSession.getUser().getEnterprise().getUu(), "已下载");
				if (deOrder != null) {
					deOrder.setStatuscode(Status.AGREED.value());
					deOrder.setStatus(Status.AGREED.name());
					deOrder = deputyOrderDao.save(deOrder);
					deOrders.add(deOrder);
				}
			}
			// ContextUtils.publishEvent(new DeputyorderReplyEvent(deOrders));
		}

	}

	/**
	 * 获取客户删除订单的记录，同步到ERP进行删除处理
	 *
	 * @return
	 */
	@RequestMapping(value = "/deletelogs", method = RequestMethod.GET)
	@ResponseBody
	public List<DeOrderDeleteLog> getLogs() {
		List<DeOrderDeleteLog> logs = deOrderDeleteLogDao
				.findByDeputyuuAndStatus(SystemSession.getUser().getEnterprise().getUu(), Status.NOT_UPLOAD.value());
		logger.log("代采定单", "下载客户订单删除记录", logs.size());
		return logs;
	}

	/**
	 * 获取客户删除订单的记录，同步到ERP进行删除处理
	 *
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/deletelogs/back", method = RequestMethod.POST)
	@ResponseBody
	public void updateDeleteLogs(@RequestParam("data") String data) throws UnsupportedEncodingException {
		String jsonStr = URLDecoder.decode(data, "UTF-8");
		String[] idStr = jsonStr.split(",");
		for (String id : idStr) {
			if (id != null) {
				DeOrderDeleteLog log = deOrderDeleteLogDao.findOne(Long.valueOf(id));
				if (null != log) {
					log.setStatus(Status.DOWNLOADED.value());
					log.setDate(new Date());
					deOrderDeleteLogDao.save(log);
				}
			}
		}
	}
}
