package com.uas.platform.b2b.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.uas.platform.b2b.model.Attach;
import com.uas.platform.b2b.model.FileUpload;
import com.uas.platform.b2b.model.PurchaseProofingItem;
import com.uas.platform.b2b.model.PurchaseProofingSend;
import com.uas.platform.b2b.service.AttachService;
import com.uas.platform.b2b.service.PurchaseProofingService;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.core.model.PageInfo;
import com.uas.platform.core.model.PageParams;
import com.uas.platform.core.util.serializer.FlexJsonUtils;

/**
 * 卖家获取对应的客户打样申请单
 * 
 * @author suntg
 * 
 */
@Controller
@RequestMapping("/sale/sample")
public class SaleSampleController {

	@Autowired
	private PurchaseProofingService purchaseProofingService;
	
	@Autowired
	private AttachService attachService;

	/**
	 * 作为卖家，分页获取客户的打样申请单
	 * 
	 * @param json
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public Page<PurchaseProofingItem> getProofingItems(PageParams params) {
		PageInfo info = new PageInfo(params);
		// 我作为卖家，把我的企业ID作为供应商ID传入
		info.filter("vendUU", SystemSession.getUser().getEnterprise().getUu());
		return purchaseProofingService.findAllByPageInfo(info);
	}

	/**
	 * 作为卖家，根据打样申请明细ID查找客户客户打样申请明细
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	public PurchaseProofingItem getProofingItemById(@PathVariable("id") Long id) {
		return purchaseProofingService.findById(id);
	}
	
	/**
	 * 作为卖家，在平台上对客户打样申请进行送样
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}/send", method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> sendSample(String json, @PathVariable("id") Long id, FileUpload uploadItem) {
		PurchaseProofingSend proofingSend = FlexJsonUtils.fromJson(json, PurchaseProofingSend.class);
		PurchaseProofingItem proofingItem = new PurchaseProofingItem();
		if(uploadItem != null && uploadItem.getFile() != null) {
			Attach attach = attachService.uploadAndSave(uploadItem, "purchaseProofing", "送样单附件");
			proofingSend.setAttach(attach.getId().toString());
		}
		proofingItem.setId(id);
		proofingSend.setProofingItem(proofingItem);
		proofingSend.setItemId(id);
		purchaseProofingService.send(proofingSend);
		return new ResponseEntity<String>(HttpStatus.OK);
	}

}
