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

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.uas.sso.support.Page;
import com.uas.platform.b2b.dao.PurchaseOrderAllDao;
import com.uas.platform.b2b.dao.PurchaseOrderDoneDao;
import com.uas.platform.b2b.dao.PurchaseOrderTodoDao;
import com.uas.platform.b2b.dao.PurchaseOrderWaitingDao;
import com.uas.platform.b2b.mobile.model.OrderReply;
import com.uas.platform.b2b.mobile.model.Purchase;
import com.uas.platform.b2b.mobile.service.PurchaseService;
import com.uas.platform.b2b.model.*;
import com.uas.platform.b2b.search.SearchService;
import com.uas.platform.b2b.service.PurchaseOrderService;
import com.uas.platform.b2b.service.UserService;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.b2b.support.UsageBufferedLogger;
import com.uas.platform.core.logging.BufferedLoggerManager;
import com.uas.platform.core.model.Constant;
import com.uas.platform.core.model.PageInfo;
import com.uas.platform.core.model.PageParams;
import com.uas.platform.core.model.Status;
import com.uas.platform.core.persistence.criteria.PredicateUtils;
import com.uas.platform.core.util.serializer.FlexJsonUtils;
import com.uas.platform.core.web.bind.RequestState;
import com.uas.search.b2b.model.MultiValue;
import com.uas.search.b2b.model.Sort;
import com.uas.search.b2b.util.SearchConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 对移动端的数据接口<br>
 * 卖家对收到的客户采购单的处理
 * 
 * @author yingp
 * 
 */
@Controller("mobile.SaleController")
@RequestMapping("/mobile/sale/orders")
public class SaleController {

	@Autowired
	private PurchaseOrderService purchaseOrderService;

	@Autowired
	private PurchaseService purchaseService;

	@Autowired
	private UserService userService;

	@Autowired
	private SearchService searchService;

	@Autowired
	private PurchaseOrderWaitingDao purchaseOrderWaitingDao;

	@Autowired
	private PurchaseOrderDoneDao purchaseOrderDoneDao;

	@Autowired
	private PurchaseOrderAllDao purchaseOrderAllDao;

	@Autowired
	private PurchaseOrderTodoDao purchaseOrderTodoDao;

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

	/**
	 * 作为卖家，查询收到的客户采购订单
	 * 
	 * @param params 分页参数
	 * @param searchFilter 过滤条件
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public org.springframework.data.domain.Page<Purchase> getReceivedPurchaseOrders(PageParams params, String searchFilter) {
		PageInfo info = new PageInfo(params);
		// 我作为卖家，把我的企业ID作为供应商ID传入
		info.expression(PredicateUtils.in("vendUU", SystemSession.getUser().getEnUUs(), false));
		SearchFilter filter = null;
		if( StringUtils.hasText(searchFilter)) {
			filter = FlexJsonUtils.fromJson(searchFilter, SearchFilter.class);
		}
		return purchaseService.convertPurchaseOrder(purchaseOrderService.findAllDetailByPageInfo(info, filter));
	}

	/**
	 * 作为卖家，根据采购单据ID查找采购订单(含明细)
	 * 
	 * @param id 询价单id
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	public Purchase getReceivedPurchaseOrderItemById(@PathVariable("id") Long id) {
		return purchaseService.convertPurchaseOrder(purchaseOrderService.findById(id));
	}

	/**
	 * 作为卖家，根据采购单据ID查找采购订单(含明细)
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}/info", method = RequestMethod.GET)
	@ResponseBody
	public PurchaseOrderAll getReceivedPurchaseOrderItemByIdForApp(@PathVariable("id") Long id) {
		return purchaseOrderService.findById(id);
	}

	/**
	 * 作为买家，根据采购单据ID查找采购订单(含明细)
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/purc/{id}/info", method = RequestMethod.GET)
	@ResponseBody
	public PurchaseOrderAll getPurchaseOrderItemById(@PathVariable("id") Long id) {
		return purchaseOrderService.findById(id);
	}

	/**
	 * 作为卖家，收到的采购订单(含明细)（全部）- 搜索
	 *
	 * @param page  页码
     * @param size 每页条数
     * @param keyword 关键词
	 * @return
	 */
	@RequestMapping(value = "/info/search", method = RequestMethod.GET)
	@ResponseBody
	public Page<PurchaseOrderAll> getPurchaseOrderItems(int page, int size, String keyword) {
		if (!StringUtils.isEmpty(keyword)) {
			com.uas.search.b2b.model.PageParams pageParams = new com.uas.search.b2b.model.PageParams(page, size, new HashMap<String, Object>());
			// 当前登录企业作为供应商
			pageParams.getFilters().put("pu_venduu", SystemSession.getUser().getEnterprise().getUu());
			SearchFilter filter = userService.distribute();
			if (filter != null && filter.getDistribute() == null) {
				return null;
			}
			if (filter != null && !CollectionUtils.isEmpty(filter.getDistribute())) {
				List<Object> list = new ArrayList<>();
				list.addAll(filter.getDistribute());
				pageParams.getFilters().put("pu_enuu", new MultiValue(list, true));
			}
			// TODO 其他过滤条件
			List<Sort> sortList = new ArrayList<>();
			sortList.add(new Sort("pu_id", false, Sort.Type.LONG, 1L));
			pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("pu_status", (short) Status.UNAUDIT.value());
			pageParams.setNotEqualFilters(map);
			System.out.println("saleOrder-search:" + keyword);
			logger.log("客户采购单", "app搜索收到的客户采购订单列表（包括采购明细）（全部）");
			return searchService.searchPurchaseOrderIdsForApp(keyword, pageParams);
		} else {
			logger.log("客户采购单", "app查看收到的客户采购订单列表（包括采购明细）（全部）");
			purchaseOrderAllDao.setDisplayStatus(SystemSession.getUser().getUserUU(),
					SystemSession.getUser().getEnterprise().getUu(), OrderType.sale.name());
			PageInfo pageInfo = new PageInfo(page, size);
			pageInfo.filter("vendUU", SystemSession.getUser().getEnterprise().getUu());
			org.springframework.data.domain.Sort.Order statusOrder = new org.springframework.data.domain.Sort.Order(org.springframework.data.domain.Sort.Direction.ASC, "status");
			org.springframework.data.domain.Sort.Order idOrder = new org.springframework.data.domain.Sort.Order(org.springframework.data.domain.Sort.Direction.DESC, "id");
			List<org.springframework.data.domain.Sort.Order> orders = new ArrayList<>();
			orders.add(statusOrder);
			orders.add(idOrder);
			pageInfo.setSort(new org.springframework.data.domain.Sort(orders));
			SearchFilter filter = new SearchFilter();
			SearchFilter distribute = userService.distribute();
			if (distribute != null && distribute.getDistribute() == null) {
				return null;
			}
			if (distribute != null && !CollectionUtils.isEmpty(distribute.getDistribute())) {
				filter.setDistribute(distribute.getDistribute());
			}
			System.out.println("saleOrder-nosearch:" + keyword);
			return toPage(purchaseOrderService.findAllOrdersDetailByPageInfo(pageInfo, filter));
		}
	}

	/**
	 * 作为卖家，收到的采购订单(含明细)(待回复) - 搜索
	 *
	 * @param page  页码
     * @param size 每页条数
     * @param keyword 关键词
	 * @return
	 */
	@RequestMapping(value = "/info/search", params = RequestState.TODO, method = RequestMethod.GET)
	@ResponseBody
	public Page<PurchaseOrderTodo> getTodoPurchaseOrderItems(int page, int size, String keyword) {
		if (!StringUtils.isEmpty(keyword)) {
			com.uas.search.b2b.model.PageParams pageParams = new com.uas.search.b2b.model.PageParams(page, size, new HashMap<String, Object>());
			SearchFilter filter = userService.distribute();
			if (filter != null && filter.getDistribute() == null) {
				return null;
			}
			if (filter != null && !CollectionUtils.isEmpty(filter.getDistribute())) {
				List<Object> list = new ArrayList<>();
				list.addAll(filter.getDistribute());
				pageParams.getFilters().put("pu_enuu", new MultiValue(list, true));
			}
			// 当前登录企业作为供应商
			List<Sort> sortList = new ArrayList<>();
			sortList.add(new Sort("pu_id", false, Sort.Type.LONG, new Long(1)));
			pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
			pageParams.getFilters().put("pu_venduu", SystemSession.getUser().getEnterprise().getUu());
			pageParams.getFilters().put("pu_status", Status.NOT_REPLY.value());
			logger.log("客户采购单", "app搜索收到的客户采购订单列表（包括采购明细）（待回复）");
			return searchService.searchPurchaseTodoOrderIdsForApp(keyword, pageParams);
		} else {
			logger.log("客户采购单", "App查看收到的客户采购单列表（待回复）");
			purchaseOrderAllDao.setDisplayStatus(SystemSession.getUser().getUserUU(),
					SystemSession.getUser().getEnterprise().getUu(), OrderType.sale.name());
			purchaseOrderTodoDao.updateStatusForSale(SystemSession.getUser().getEnterprise().getUu());
			PageInfo pageInfo = new PageInfo(page, size);
			pageInfo.filter("vendUU", SystemSession.getUser().getEnterprise().getUu());
			SearchFilter filter = new SearchFilter();
			SearchFilter distribute = userService.distribute();
			if (distribute != null && distribute.getDistribute() == null) {
				return null;
			}
			if (distribute != null && !CollectionUtils.isEmpty(distribute.getDistribute())) {
				filter.setDistribute(distribute.getDistribute());
			}
			return toPage(purchaseOrderService.findTodoByPageInfo(pageInfo, filter));
		}
	}

	/**
	 * 作为卖家，收到的采购订单(含明细)(已回复) - 搜索
	 *
	 * @param page  页码
     * @param size 每页条数
     * @param keyword 关键词
	 * @return
	 */
	@RequestMapping(value = "/info/search", params = RequestState.DONE, method = RequestMethod.GET)
	@ResponseBody
	public Page<PurchaseOrderDone> getDonePurchaseOrderItems(int page, int size, String keyword) {
		if (!StringUtils.isEmpty(keyword)) {
			com.uas.search.b2b.model.PageParams pageParams = new com.uas.search.b2b.model.PageParams(page, size, new HashMap<String, Object>());
			SearchFilter filter = userService.distribute();
			if (filter != null && filter.getDistribute() == null) {
				return null;
			}
			if (filter != null && !CollectionUtils.isEmpty(filter.getDistribute())) {
				List<Object> list = new ArrayList<>();
				for (Object object : filter.getDistribute()) {
					list.add(object);
				}
				pageParams.getFilters().put("pu_enuu", new MultiValue(list, true));
			}
			// 当前登录企业作为供应商
			List<Sort> sortList = new ArrayList<>();
			sortList.add(new Sort("pu_id", false, Sort.Type.LONG, new Long(1)));
			pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
			pageParams.getFilters().put("pu_venduu", SystemSession.getUser().getEnterprise().getUu());
			pageParams.getFilters().put("pu_reply", Constant.YES);
			ModelMap map = new ModelMap();
			map.put("pu_end", Constant.YES); // 过滤掉已结案状态的
			pageParams.setNotEqualFilters(map);
			logger.log("客户采购单", "app搜索收到的客户采购订单列表（包括采购明细）（已回复）");
			return searchService.searchPurchaseDoneOrderIdsForApp(keyword, pageParams);
		} else {
			logger.log("客户采购单", "App查看收到的客户采购单列表（已回复）");
			purchaseOrderAllDao.setDisplayStatus(SystemSession.getUser().getUserUU(),
					SystemSession.getUser().getEnterprise().getUu(), OrderType.sale.name());
			purchaseOrderDoneDao.updateStatusForSaleDone(SystemSession.getUser().getEnterprise().getUu());
			PageInfo pageInfo = new PageInfo(page, size);
			pageInfo.filter("vendUU", SystemSession.getUser().getEnterprise().getUu());
			SearchFilter filter = new SearchFilter();
			SearchFilter distribute = userService.distribute();
			if (distribute != null && distribute.getDistribute() == null) {
				return null;
			}
			if (distribute != null && !CollectionUtils.isEmpty(distribute.getDistribute())) {
				filter.setDistribute(distribute.getDistribute());
			}
			return toPage(purchaseOrderService.findDoneByPageInfo(pageInfo, filter));
		}
	}

	/**
	 * 作为卖家，收到的客户的待结案的申请
	 *
	 * @param page  页码
     * @param size 每页条数
     * @param keyword 关键词
	 * @return
	 */
	@RequestMapping(value="/items", params = RequestState.UPDATE, method = RequestMethod.GET)
	@ResponseBody
	public Page<PurchaseOrderAll> getToAgreedOrderItems(int page, int size, String keyword){
		if (!StringUtils.isEmpty(keyword)) {
			logger.log("客户采购单", "app搜索收到的客户采购订单列表（包括采购明细）（待结案）");
			com.uas.search.b2b.model.PageParams pageParams = new com.uas.search.b2b.model.PageParams(page, size, new HashMap<String, Object>());
			SearchFilter filter = userService.distribute();
			if (filter != null && filter.getDistribute() == null) {
				return null;
			}
			if (filter != null && !CollectionUtils.isEmpty(filter.getDistribute())) {
				List<Object> list = new ArrayList<>();
				for (Object object : filter.getDistribute()) {
					list.add(object);
				}
				pageParams.getFilters().put("pu_enuu", new MultiValue(list, true));
			}
			// 当前登录企业作为供应商
			List<Sort> sortList = new ArrayList<>();
			sortList.add(new Sort("pu_id", false, Sort.Type.LONG, new Long(1)));
			pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
			pageParams.getFilters().put("pu_venduu", SystemSession.getUser().getEnterprise().getUu());
			pageParams.getFilters().put("pu_status", Status.WAITSELLERCOMFIRM.value());
			pageParams.getFilters().put("pu_end", Constant.NO);
			return searchService.searchPurchaseOrderIdsForApp(keyword, pageParams);
		} else {
			logger.log("客户采购单", "App查看收到的客户采购单列表（已结案）");
			purchaseOrderAllDao.setDisplayStatus(SystemSession.getUser().getUserUU(),
					SystemSession.getUser().getEnterprise().getUu(), OrderType.sale.name());
			PageInfo pageInfo = new PageInfo(page, size);
			pageInfo.filter("vendUU", SystemSession.getUser().getEnterprise().getUu());
			pageInfo.filter("status", Status.WAITSELLERCOMFIRM.value());
			pageInfo.filter("end", Constant.NO);
			SearchFilter filter = new SearchFilter();
			SearchFilter distribute = userService.distribute();
			if (distribute != null && distribute.getDistribute() == null) {
				return null;
			}
			if (distribute != null && !CollectionUtils.isEmpty(distribute.getDistribute())) {
				filter.setDistribute(distribute.getDistribute());
			}
			return toPage(purchaseOrderService.findAllDetailByPageInfo(pageInfo, filter));
		}
	}


	/**
	 * 作为卖家，收到的采购订单(含明细)(已结案) - 搜索
	 *
	 * @param page  页码
     * @param size 每页条数
     * @param keyword 关键词
	 * @return
	 */
	@RequestMapping(value = "/info/search", params = RequestState.END, method = RequestMethod.GET)
	@ResponseBody
	public Page<PurchaseOrderEnd> getEndPurchaseOrderItems(int page, int size, String keyword) {
		if (!StringUtils.isEmpty(keyword)) {
			logger.log("客户采购单", "app查看收到的客户采购订单列表（包括采购明细）（已结案）");
			com.uas.search.b2b.model.PageParams pageParams = new com.uas.search.b2b.model.PageParams(page, size, new HashMap<String, Object>());
			SearchFilter filter = userService.distribute();
			if (filter != null && filter.getDistribute() == null) {
				return null;
			}
			if (filter != null && !CollectionUtils.isEmpty(filter.getDistribute())) {
				List<Object> list = new ArrayList<>();
				for (Object object : filter.getDistribute()) {
					list.add(object);
				}
				pageParams.getFilters().put("pu_enuu", new MultiValue(list, true));
			}
			// 当前登录企业作为供应商
			List<Sort> sortList = new ArrayList<>();
			sortList.add(new Sort("pu_id", false, Sort.Type.LONG, new Long(1)));
			pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
			pageParams.getFilters().put("pu_venduu", SystemSession.getUser().getEnterprise().getUu());
			pageParams.getFilters().put("pu_end", Constant.YES);
			return searchService.searchPurchaseEndOrderIdsForApp(keyword, pageParams);
		} else {
			logger.log("客户采购单", "App查看收到的客户采购单列表（已结案）");
			purchaseOrderAllDao.setDisplayStatus(SystemSession.getUser().getUserUU(),
					SystemSession.getUser().getEnterprise().getUu(), OrderType.sale.name());
			PageInfo pageInfo = new PageInfo(page, size);
			pageInfo.filter("vendUU", SystemSession.getUser().getEnterprise().getUu());
			SearchFilter filter = new SearchFilter();
			SearchFilter distribute = userService.distribute();
			if (distribute != null && distribute.getDistribute() == null) {
				return null;
			}
			if (distribute != null && !CollectionUtils.isEmpty(distribute.getDistribute())) {
				filter.setDistribute(distribute.getDistribute());
			}
			return toPage(purchaseOrderService.findEndOrdersByPageInfo(pageInfo, filter));
		}
	}

	/**
	 * 获取已收货的订单 - 搜索
	 *
	 * @param page  页码
     * @param size 每页条数
     * @param keyword 关键词
	 *
	 */
	@RequestMapping(value = "/info/search", params = RequestState.RECEIVED, method = RequestMethod.GET)
	@ResponseBody
	public Page<PurchaseOrderReceived> getReceivedPurchaseOrderItems(int page, int size, String keyword) {
		if (!StringUtils.isEmpty(keyword)) {
			logger.log("客户采购单", "app查看收到的客户采购订单列表（包括采购明细）（已收货）");
			com.uas.search.b2b.model.PageParams pageParams = new com.uas.search.b2b.model.PageParams(page, size, new HashMap<String, Object>());
			SearchFilter filter = userService.distribute();
			if (filter != null && filter.getDistribute() == null) {
				return null;
			}
			if (filter != null && !CollectionUtils.isEmpty(filter.getDistribute())) {
				List<Object> list = new ArrayList<>();
				list.addAll(filter.getDistribute());
				pageParams.getFilters().put("pu_enuu", new MultiValue(list, true));
			}
			// 当前登录企业作为供应商
			List<Sort> sortList = new ArrayList<>();
			sortList.add(new Sort("pu_id", false, Sort.Type.LONG, new Long(1)));
			pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
			pageParams.getFilters().put("pu_venduu", SystemSession.getUser().getEnterprise().getUu());
			pageParams.getFilters().put("pu_end", Constant.NO);
			return searchService.searchPurchaseReceivedOrderIdsForApp(keyword, pageParams);
		} else {
			logger.log("客户采购单", "App查看收到的客户采购订单列表（包括采购明细）（待交货）");
			purchaseOrderAllDao.setDisplayStatus(SystemSession.getUser().getUserUU(),
					SystemSession.getUser().getEnterprise().getUu(), OrderType.sale.name());
			purchaseOrderWaitingDao.updateStatusForSale(SystemSession.getUser().getEnterprise().getUu());
			PageInfo pageInfo = new PageInfo(page, size);
			pageInfo.filter("vendUU", SystemSession.getUser().getEnterprise().getUu());
			SearchFilter filter = new SearchFilter();
			SearchFilter distribute = userService.distribute();
			if (distribute != null && distribute.getDistribute() == null) {
				return null;
			}
			if (distribute != null && !CollectionUtils.isEmpty(distribute.getDistribute())) {
				filter.setDistribute(distribute.getDistribute());
			}
			return toPage(purchaseOrderService.findReceivedByPageInfo(pageInfo, filter));
		}
	}

	/**
	 * 获取待发货的订单 - 搜索
	 *
	 * @param page  页码
     * @param size 每页条数
     * @param keyword 关键词
	 * @return
	 */
	@RequestMapping(value = "/info/search", params = RequestState.WAITING, method = RequestMethod.GET)
	@ResponseBody
	public Page<PurchaseOrderWaiting> getWaitingPurchaseOrderItems(int page, int size, String keyword) {
		if (!StringUtils.isEmpty(keyword)) {
			logger.log("客户采购单", "app查看收到的客户采购订单列表（包括采购明细）（待交货）");
			com.uas.search.b2b.model.PageParams pageParams = new com.uas.search.b2b.model.PageParams(page, size, new HashMap<String, Object>());
			SearchFilter filter = userService.distribute();
			if (filter != null && filter.getDistribute() == null) {
				return null;
			}
			if (filter != null && !CollectionUtils.isEmpty(filter.getDistribute())) {
				List<Object> list = new ArrayList<>();
				list.addAll(filter.getDistribute());
				pageParams.getFilters().put("pu_enuu", new MultiValue(list, true));
			}
			// 当前登录企业作为供应商
			List<Sort> sortList = new ArrayList<>();
			sortList.add(new Sort("pu_id", false, Sort.Type.LONG, new Long(1)));
			pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
			pageParams.getFilters().put("pu_venduu", SystemSession.getUser().getEnterprise().getUu());
			List<Object> list = new ArrayList<>();
			list.add(Constant.YES);
			list.add((short) 2); // 建索引时，将不处于已结案状态，但是货物全部交接完毕的单，end值设为了2
			ModelMap map = new ModelMap();
			map.put("pu_end", new MultiValue(list, true));
			map.put("pu_status", (short) Status.UNAUDIT.value());
			pageParams.setNotEqualFilters(map);
			return searchService.searchPurchaseWaitingOrderIdsForApp(keyword, pageParams);
		} else {
			logger.log("客户采购单", "App查看收到的客户采购订单列表（包括采购明细）（待交货）");
			purchaseOrderAllDao.setDisplayStatus(SystemSession.getUser().getUserUU(),
					SystemSession.getUser().getEnterprise().getUu(), OrderType.sale.name());
			purchaseOrderWaitingDao.updateStatusForSale(SystemSession.getUser().getEnterprise().getUu());
			PageInfo pageInfo = new PageInfo(page, size);
			pageInfo.filter("vendUU", SystemSession.getUser().getEnterprise().getUu());
			SearchFilter filter = new SearchFilter();
			SearchFilter distribute = userService.distribute();
			if (distribute != null && distribute.getDistribute() == null) {
				return null;
			}
			if (distribute != null && !CollectionUtils.isEmpty(distribute.getDistribute())) {
				filter.setDistribute(distribute.getDistribute());
			}
			return toPage(purchaseOrderService.findWaitingByPageInfo(pageInfo, filter));
		}
	}

	/**
	 * 作为卖家，回复收到的采购订单
	 *
	 * @param json   采购单回复实体json串
	 * @return
	 */
	@RequestMapping(value = "/reply")
	public ResponseEntity<String> replyOrderItem(String json) throws UnsupportedEncodingException {
		List<OrderReply> orderReplies = FlexJsonUtils.fromJsonArray(URLDecoder.decode(json, "utf-8"), OrderReply.class);
		for (OrderReply orderReply : orderReplies) {
			Long pdId = orderReply.getPdId();
			PurchaseOrderReply reply = orderReply.convert();
            PurchaseOrderItem item = new PurchaseOrderItem();
            item.setId(pdId);
            reply.setOrderItem(item);
            reply = purchaseOrderService.reply(reply);
            logger.log("客户采购单", "App回复单个客户采购单明细", reply.replyDescription(), reply.getOrderItem().getOrder().getCode(),
                    item.getId());
        }
		return new ResponseEntity<String>(HttpStatus.OK);
	}

	/**
	 * 作为卖家，批量回复采购订单
	 *
	 * @param idString
	 * @return
	 */
	@RequestMapping(value = "/items/reply", method = RequestMethod.POST)
	public ResponseEntity<String> replyOrderItems(Long date, @RequestBody String idString) {
		List<PurchaseOrderReply> replies = purchaseOrderService.reply(idString.split(","), date);
		for (PurchaseOrderReply reply : replies) {
			logger.log("客户采购单", "批量回复客户采购明细", reply.replyDescription(), reply.getOrderItem().getOrder().getCode(),
					reply.getOrderItem().getId());
		}
//        purchaseOrderService.replyByBatch(idString, SystemSession.getUser().getUserName(), SystemSession.getUser().getIp(), SystemSession.getUser().getEnterprise().getUu(), SystemSession.getUser().getUserUU());
		return new ResponseEntity<String>(HttpStatus.OK);
	}

	/**
	 * 作为买家，收到的采购订单(含明细)
	 *
	 * @param page  页码
     * @param size 每页条数
     * @param keyword 关键词
	 * @return
	 */
	@RequestMapping(value = "/purc/info/search", method = RequestMethod.GET)
	@ResponseBody
	public Page<PurchaseOrderAll> getAllPurcOrderItems(int page, int size, String keyword) {
		if (!StringUtils.isEmpty(keyword)) {
			logger.log("采购单", "app查看收到的采购订单列表（包括采购明细）（全部）");
			com.uas.search.b2b.model.PageParams pageParams = new com.uas.search.b2b.model.PageParams(page, size, new HashMap<String, Object>());
			List<Sort> sortList = new ArrayList<>();
			sortList.add(new Sort("pu_id", false, Sort.Type.LONG, new Long(1)));
			pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
			pageParams.getFilters().put("pu_enuu", SystemSession.getUser().getEnterprise().getUu());
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("pu_status", (short) Status.UNAUDIT.value());
			pageParams.setNotEqualFilters(map);
			return searchService.searchPurchaseOrderIdsForApp(keyword, pageParams);
		} else {
			logger.log("采购单", "app查看采购订单列表（包括采购明细）（全部）");
			purchaseOrderAllDao.setDisplayStatus(SystemSession.getUser().getUserUU(),
					SystemSession.getUser().getEnterprise().getUu(), OrderType.purc.getPhrase());
			purchaseOrderWaitingDao.updateStatusForSale(SystemSession.getUser().getEnterprise().getUu());
			PageInfo pageInfo = new PageInfo(page, size);
			pageInfo.filter("enUU", SystemSession.getUser().getEnterprise().getUu());
			SearchFilter filter = new SearchFilter();
			return toPage(purchaseOrderService.findAllDetailByPageInfo(pageInfo, filter));
		}
	}

	/**
	 * 作为买家（常见是有UAS系统的,万利达这种），发出的采购订单(含明细)(待回复)
	 *
	 * @param page  页码
     * @param size 每页条数
     * @param keyword 关键词
	 * @return
	 */
	@RequestMapping(value = "/purc/info/search", params = RequestState.TODO, method = RequestMethod.GET)
	@ResponseBody
	public Page<PurchaseOrderTodo> getTodoPurcOrderItems(int page, int size, String keyword) {
		if (!StringUtils.isEmpty(keyword)) {
			logger.log("采购单", "app查看发出的采购订单列表（包括采购明细）（待回复）");
			com.uas.search.b2b.model.PageParams pageParams = new com.uas.search.b2b.model.PageParams(page, size, new HashMap<String, Object>());
			List<Sort> sortList = new ArrayList<>();
			sortList.add(new Sort("pu_id", false, Sort.Type.LONG, new Long(1)));
			pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
			pageParams.getFilters().put("pu_enuu", SystemSession.getUser().getEnterprise().getUu());
			pageParams.getFilters().put("pu_status", Status.NOT_REPLY);
			return searchService.searchPurchaseTodoOrderIdsForApp(keyword, pageParams);
		} else {
			logger.log("采购单", "app查看采购订单列表（包括采购明细）（待回复）");
			purchaseOrderAllDao.setDisplayStatus(SystemSession.getUser().getUserUU(),
					SystemSession.getUser().getEnterprise().getUu(), OrderType.purc.getPhrase());
			purchaseOrderTodoDao.updateStatusForPurc(SystemSession.getUser().getEnterprise().getUu());
			PageInfo pageInfo = new PageInfo(page, size);
			pageInfo.filter("enUU", SystemSession.getUser().getEnterprise().getUu());
			pageInfo.filter("status", Status.NOT_REPLY.value());
			SearchFilter filter = new SearchFilter();
			return toPage(purchaseOrderService.findTodoByPageInfo(pageInfo, filter));
		}
	}

	/**
	 * 作为买家（常见是有UAS系统的,万利达这种），发出的采购订单(含明细)(已回复)
	 *
	 * @param page  页码
     * @param size 每页条数
     * @param keyword 关键词
	 * @return
	 */
	@RequestMapping(value = "/purc/info/search", params = RequestState.DONE, method = RequestMethod.GET)
	@ResponseBody
	public Page<PurchaseOrderDone> getDonePurcOrderItems(int page, int size, String keyword) {
		if (!StringUtils.isEmpty(keyword)) {
			logger.log("采购单", "app查看收到的采购订单列表（包括采购明细）（已回复）");
			com.uas.search.b2b.model.PageParams pageParams = new com.uas.search.b2b.model.PageParams(page, size, new HashMap<String, Object>());
			List<Sort> sortList = new ArrayList<>();
			sortList.add(new Sort("pu_id", false, Sort.Type.LONG, new Long(1)));
			pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
			pageParams.getFilters().put("pu_enuu", SystemSession.getUser().getEnterprise().getUu());
			pageParams.getFilters().put("pu_reply", Constant.YES);
			return searchService.searchPurchaseDoneOrderIdsForApp(keyword, pageParams);
		} else {
			logger.log("采购单", "app查看采购订单列表（包括采购明细）（已回复）");
			purchaseOrderAllDao.setDisplayStatus(SystemSession.getUser().getUserUU(),
					SystemSession.getUser().getEnterprise().getUu(), OrderType.purc.getPhrase());
			purchaseOrderDoneDao.updateStatusForPurcDone(SystemSession.getUser().getEnterprise().getUu());
			PageInfo pageInfo = new PageInfo(page, size);
			pageInfo.filter("enUU", SystemSession.getUser().getEnterprise().getUu());
			SearchFilter filter = new SearchFilter();
			return toPage(purchaseOrderService.findDoneByPageInfo(pageInfo, filter));
		}
	}

	/**
	 * 作为买家，查看发出的采购单（已结案）
	 *
	 * @param page  页码
     * @param size 每页条数
     * @param keyword 关键词
	 * @return
	 */
	@RequestMapping(value = "/purc/info/search", params = RequestState.END, method = RequestMethod.GET)
	@ResponseBody
	public Page<PurchaseOrderEnd> getEndPurcOrderItems(int page, int size, String keyword) {
		if (!StringUtils.isEmpty(keyword)) {
			logger.log("采购单", "app查看收到的采购订单列表（包括采购明细）（已结案）");
			com.uas.search.b2b.model.PageParams pageParams = new com.uas.search.b2b.model.PageParams(page, size, new HashMap<String, Object>());
			List<Sort> sortList = new ArrayList<>();
			sortList.add(new Sort("pu_id", false, Sort.Type.LONG, new Long(1)));
			pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
			pageParams.getFilters().put("pu_enuu", SystemSession.getUser().getEnterprise().getUu());
			pageParams.getFilters().put("pu_end", Constant.YES);
			return searchService.searchPurchaseEndOrderIdsForApp(keyword, pageParams);
		} else {
			logger.log("采购单", "app查看采购订单列表（包括采购明细）（已结案）");
			purchaseOrderAllDao.setDisplayStatus(SystemSession.getUser().getUserUU(),
					SystemSession.getUser().getEnterprise().getUu(), OrderType.purc.getPhrase());
			PageInfo pageInfo = new PageInfo(page, size);
			pageInfo.filter("enUU", SystemSession.getUser().getEnterprise().getUu());
			pageInfo.filter("end", Constant.YES);
			SearchFilter filter = new SearchFilter();
			return toPage(purchaseOrderService.findEndOrdersByPageInfo(pageInfo, filter));
		}
	}

	/**
	 * @param page  页码
     * @param size 每页条数
     * @param keyword 关键词
	 *            获取待发货的订单
	 */
	@RequestMapping(value = "/purc/info/search", params = RequestState.WAITING, method = RequestMethod.GET)
	@ResponseBody
	public Page<PurchaseOrderWaiting> getWaitingPurcOrderItems(int page, int size, String keyword) {
		if (!StringUtils.isEmpty(keyword)) {
			logger.log("采购单", "app查看收到的采购订单列表（包括采购明细）（待交货）");
			com.uas.search.b2b.model.PageParams pageParams = new com.uas.search.b2b.model.PageParams(page, size, new HashMap<String, Object>());
			List<Sort> sortList = new ArrayList<>();
			sortList.add(new Sort("pu_id", false, Sort.Type.LONG, new Long(1)));
			List<Object> list = new ArrayList<>();
			list.add(Constant.YES);
			list.add((short) 2); // 建索引时，将不处于已结案状态，但是货物全部交接完毕的单，end值设为了2
			ModelMap map = new ModelMap();
			map.put("pu_end", new MultiValue(list, true));
			map.put("pu_status", (short) Status.UNAUDIT.value());
			pageParams.setNotEqualFilters(map);
			return searchService.searchPurchaseWaitingOrderIdsForApp(keyword, pageParams);
		} else {
			logger.log("采购单", "app查看采购订单列表（包括采购明细）（待交货）");
			purchaseOrderAllDao.setDisplayStatus(SystemSession.getUser().getUserUU(),
					SystemSession.getUser().getEnterprise().getUu(), OrderType.purc.getPhrase());
			purchaseOrderWaitingDao.updateStatusForPurc(SystemSession.getUser().getEnterprise().getUu());
			PageInfo pageInfo = new PageInfo(page, size);
			pageInfo.filter("enUU", SystemSession.getUser().getEnterprise().getUu());
			SearchFilter filter = new SearchFilter();
			return toPage(purchaseOrderService.findWaitingByPageInfo(pageInfo, filter));
		}
	}

	/**
	 * page信息转换
	 *
	 * @param page
	 *            直接从数据库获取的page数据
	 * @return 合并后的结果
	 */
	private <T> Page<T> toPage(org.springframework.data.domain.Page<T> page) {
		if (page.getContent() == null) {
			return null;
		}
		Page<T> result = new Page<>();
		result.setContent(page.getContent());
		result.setFirst(page.isFirst());
		result.setLast(page.isLast());
		result.setTotalElements(page.getTotalElements());
		result.setNumber(page.getNumber());
		result.setSize(page.getSize());
		return result;
	}
}
