package com.uas.platform.b2b.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.Enterprise;
import com.uas.platform.b2b.model.FileUpload;
import com.uas.platform.b2b.service.AttachService;
import com.uas.platform.b2b.service.EnterpriseService;
import com.uas.platform.core.util.serializer.FlexJsonUtils;

/**
 * 企业请求
 * @author suntg
 * @date 2015年3月10日17:37:37
 */
@Controller
@RequestMapping(value = "/enterprise")
public class EnterpriseController {
	
	@Autowired
	private EnterpriseService enterpriseService;
	@Autowired
	private AttachService attachService;
	
	/**
	 * 执照号是否可用
	 * @param code
	 * @return
	 */
	@RequestMapping(value = "/codeEnable", method = RequestMethod.GET)
	public ResponseEntity<String> bussinessCodeEnable(String code) {
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Type", "application/text; charset=utf-8");
		return new ResponseEntity<String>(enterpriseService.bussinessCodeEnable(code), 
				headers, HttpStatus.OK);
	}
	
	/**
	 * 注册新企业用户
	 */
	@RequestMapping("/register")
	public @ResponseBody
	ResponseEntity<ModelMap> register(HttpSession session, String enterprise, FileUpload uploadItem) {
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Type", "application/json; charset=utf-8");
		ModelMap map = new ModelMap();
		System.out.println("enName--" + enterprise);
		System.out.println("fileName--" + uploadItem.getFile().getOriginalFilename());
		Enterprise newEnterprise = FlexJsonUtils.fromJson(enterprise, Enterprise.class);//需要把字符串转成Object
		Attach attach = attachService.upload(uploadItem, "bussinessCodeImg", "客户营业执照复印件或照片");//先保存上传到文件
		if(attach == null){//文件过大
			map.put("error", "文件过大");
			return new ResponseEntity<ModelMap>(map, headers, HttpStatus.FORBIDDEN);
		} else {//上传成功
			newEnterprise.setEnBussinessCodeAttach(attach);
			Enterprise regEnterprise = enterpriseService.registerEnterprise(newEnterprise);
			if(regEnterprise == null) {//营业执照码验证
				map.put("error", "操作失败");
				return new ResponseEntity<ModelMap>(map, headers, HttpStatus.EXPECTATION_FAILED);
			}
			map.put("uu", regEnterprise.getUu());
			return new ResponseEntity<ModelMap>(map, headers, HttpStatus.OK);
		}
	}

}
