package com.goafanti.app.controller;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpMethod;
import org.springframework.validation.BindingResult;
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 org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import com.goafanti.achievement.bo.InputAchievement;
import com.goafanti.achievement.service.AchievementInterestService;
import com.goafanti.achievement.service.AchievementService;
import com.goafanti.banners.service.BannersService;
import com.goafanti.business.service.JtBusinessService;
import com.goafanti.common.bo.Result;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.constant.ErrorConstants;
import com.goafanti.common.constant.PageConstants;
import com.goafanti.common.controller.CertifyApiController;
import com.goafanti.common.enums.AchievementFields;
import com.goafanti.common.enums.AttachmentType;
import com.goafanti.common.enums.DemandFields;
import com.goafanti.common.model.Achievement;
import com.goafanti.common.model.Demand;
import com.goafanti.common.model.JpushEasemobAccount;
import com.goafanti.common.model.MessageConsumer;
import com.goafanti.common.model.MessageFromSystem;
import com.goafanti.common.model.MessageProducer;
import com.goafanti.common.model.User;
import com.goafanti.common.service.FieldGlossoryService;
import com.goafanti.common.utils.DateUtils;
import com.goafanti.common.utils.PasswordUtil;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.demand.bo.InputDemand;
import com.goafanti.demand.service.DemandService;
import com.goafanti.easemob.EasemobUtils;
import com.goafanti.easemob.bo.EasemobInfo;
import com.goafanti.message.bo.MessageBo;
import com.goafanti.message.bo.MessageListBo;
import com.goafanti.message.service.MessageService;
import com.goafanti.news.service.NewsService;
import com.goafanti.order.service.JtOrderService;
import com.goafanti.portal.bo.AchievementObject;
import com.goafanti.user.service.UserCareerService;
import com.goafanti.user.service.UserIdentityService;
import com.goafanti.user.service.UserInterestService;
import com.goafanti.user.service.UserService;

@RestController
@RequestMapping(value = "/app/user")
public class AppUserController extends CertifyApiController {
	@Resource
	private UserService userServiceImpl;
	@Resource
	private MessageService messageService;
	@Resource
	private EasemobUtils   easemobUtils;
	@Resource
	private BannersService		bannersService;
	@Resource
	private NewsService			newsService;
	@Resource
	private AchievementService	achievementService;
	@Resource
	private DemandService		demandService;
	@Resource
	private UserCareerService	userCareerService;
	@Resource
	private UserInterestService userInterestService; 
	@Resource
	private UserIdentityService	userIdentityService;
	@Resource
	private JtBusinessService			jtBusinessService;
	@Resource
	AchievementInterestService achievementInterestService;
	@Resource
	JtOrderService	jtOrderService;
	@Resource
	private FieldGlossoryService fieldGlossoryService;
	@Resource
	private UserService	userService;
	@Resource(name = "passwordUtil")
	private PasswordUtil	passwordUtil;
	
	@RequestMapping(value = "/uploadImg",method = RequestMethod.POST)
	public Result uploadAvatar(HttpServletRequest req){
		Result res = new Result();
		String headPortraitUrl = handleFile(res, "/avatar/", false, req, "");
		if(TokenManager.getToken() instanceof User){
			User u = new User();
			u.setId(TokenManager.getUserId());
			u.setHeadPortraitUrl(headPortraitUrl);
			userServiceImpl.updateByPrimaryKeySelective(u);
		}
		res.setData(headPortraitUrl);
		return res;
	}

	@RequestMapping(value = "/updateUser",method = RequestMethod.POST)
	public Result updateUser(User u){
		Result res = new Result();
		if(u!=null&&StringUtils.isNotEmpty(u.getMobile())){
			//验证手机号码格式是否正确
			Pattern p = Pattern.compile("^(1[1-9][0-9])\\d{8}$"); // 验证手机号           
			Matcher m = p.matcher(u.getMobile());   
			if(!m.matches()){
				res.getError().add(buildError("电话号码格式不对","电话号码格式不对"));
			}else{
				//验证手机是否存在
				int i = userService.getCountByMobile(u.getId(),u.getMobile(),u.getType());
				if(i>0){
					res.getError().add(buildError("电话号码重复","电话号码重复"));
				}
			}
		}
		u.setId(TokenManager.getUserId());
		userServiceImpl.updateByPrimaryKeySelective(u);
		return res;
	}
	
	@RequestMapping(value = "/logout",method = RequestMethod.GET)
	public Result logout(HttpServletRequest request){
		Result res = new Result();
		TokenManager.logout();
		return res;
	}
	
	@RequestMapping(value = "/userInfo",method = RequestMethod.GET)
	public Result userInfo(HttpServletRequest request){
		Result res = new Result();
		res.setData(userServiceImpl.selectBaseInfo());
		return res;
	}
	
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public Result index(){
		Result res = new Result();
		res.setData(messageService.selectMessageWithGroup());
		return res;
	}
	
	@RequestMapping(value = "/listMessage", method = RequestMethod.POST)
	public Result listMessage(Integer subject,Integer sourceType,Integer pageNo,Integer pageSize){
		Result res = new Result();
		/*if(null == subject){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "必须指定消息类型"));
			return res;
		}*/
		User u = TokenManager.getUserToken();
		if(u != null){
			List<MessageBo> boList = messageService.selectSyncMessage(u.getId()); 
			if(boList != null && boList.size()>0){
				List<MessageProducer> producers = new ArrayList<MessageProducer>();
				List<MessageConsumer> consumers = new ArrayList<MessageConsumer>();
				MessageProducer mp = null;
				MessageConsumer mc = null;
				Date date = new Date();
				for(MessageBo bo : boList){
					mp = new MessageProducer();
					mp.setId(bo.getId());
					mp.setSendTime(date);
					producers.add(mp);
					mc = new MessageConsumer();
					mc.setId(UUID.randomUUID().toString());
					mc.setConsumerId(TokenManager.getUserId());
					mc.setMessageId(bo.getMessageId());
					consumers.add(mc);
				}
				if(producers.size()>0)messageService.updateMessageProducer(producers);
				//新增 message_consumer
				if(consumers.size()>0)messageService.insertBatchConsumer(consumers);
			}
		}
		res.setData(messageService.listPersonalMessage(subject,sourceType,pageNo,pageSize));
		return res;
	}
	
	
	
	/**
	 * 同步绑定账号
	 * @param uuid
	 * @param registrationId
	 * @param userName
	 */
	@RequestMapping(value = "/synBindingAccount",method = RequestMethod.POST)
	private Result synBindingAccount(String uuid,String registrationId,String easemobName,String easemobPass){
		Result res = new Result();
		//更新 jpush_easemob_account
		messageService.updateJpushEasemobAccount(uuid, registrationId, easemobName,easemobPass);
		return res;
	}
	
	/*
	 * 更新极光推送
	 * 
	 * */
	
	@RequestMapping(value = "/updateJpushAccount",method = RequestMethod.POST)
	private Result updateJpush(String uuid,String registrationId,String easemobName,String easemobPass,String uid){
		Result res = new Result();
		//更新 jpush_easemob_account
		JpushEasemobAccount jpushEasemobAccount=messageService.selectSynAccByUid(uid);
		if(jpushEasemobAccount==null) {
			messageService.addJpushEasemobAccount(uuid, uid, easemobName, easemobPass);
		}
		messageService.updateJpushEasemobAccount(uuid, registrationId, easemobName,easemobPass);
		return res;
	}
	
	/**
	 * 读取消息
	 * @param messageId
	 * @throws IllegalAccessException 
	 * @throws InvocationTargetException 
	 */
	@RequestMapping(value = "/readMessage",method = RequestMethod.GET)
	private Result readMessage(String messageId){
		Result res = new Result();
		if(StringUtils.isBlank(messageId)){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"", "消息编号为空"));
			return res;
		}
		//读取消息详情
		MessageFromSystem mfs = messageService.selectSystemMessageDetail(messageId);
		MessageListBo bo = new MessageListBo();
		bo.setCreateTime(mfs.getCreateTime()==null?"":DateUtils.formatDate(mfs.getCreateTime(), AFTConstants.YYYYMMDDHHMMSS));
		bo.setResourceType(String.valueOf(mfs.getResourceType()));
		bo.setSubject(String.valueOf(mfs.getSubject()));
		bo.setMessageId(mfs.getId());
		bo.setTitle(mfs.getTitle());
		bo.setBody(mfs.getBody());
		bo.setIsRead("1");//app操作已读
		res.setData(bo);
		//更新 message_consumer
		messageService.updateMessageConsumer(messageId);
		return res;
	}
	/**
	 * 读取推送消息
	 * @param messageId
	 * @throws IllegalAccessException 
	 * @throws InvocationTargetException 
	 */
	@RequestMapping(value = "/readJpushMessage",method = RequestMethod.GET)
	private Result readJpushMessage(String messageId){
		Result res = new Result();
		res.data(messageService.updateReadJpushMessage(messageId));
		return res;
	}

	/**
	 * 查询环信昵称和头像
	 * @param easemobName
	 * @return
	 */
	@RequestMapping(value = "/getNicknameAndHeadPortrait",method = RequestMethod.GET)
	public Result getNicknameAndHeadPortrait(String easemobName){
		Result res = new Result();
		User user = userServiceImpl.selectByNumber(easemobName);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("nickName", user.getNickname());
		jsonObject.put("headPortraitUrl", null == user.getHeadPortraitUrl()?"":user.getHeadPortraitUrl());
		res.setData(jsonObject);
		return res;
	}
	
	
	/**
	 * 关注功能
	 */
	@RequestMapping(value = "/interestAdd", method = RequestMethod.POST)
	public Result Addinterest( Integer type,String objectId,String interest) {
		Result res = new Result();
		if (null==type) {
			res.getError().add(buildError( "分类错误！", "分类错误"));
			return res;
		}
		String uid=null;
		if (StringUtils.isNotBlank(TokenManager.getUserId())) {
			uid=TokenManager.getUserId();
		}
		if (Integer.valueOf(interest)==0) {
			res.setData(achievementInterestService.saveInterest( uid, type, objectId,interest));
		}else {
			res.setData(achievementInterestService.deleteInterest( uid, type, objectId,interest));
		}
			
		return res;
	}
	
	


	/**
	 * 我的需求
	 */
	@RequestMapping(value = "/demandList", method = RequestMethod.GET)
	public Result demandList(String pageNo, String pageSize) {
		Result res = new Result();
		Integer pNo = 1;
		Integer pSize = 10;
		if (StringUtils.isNumeric(pageSize)) {
			pSize = Integer.parseInt(pageSize);
		}

		if (StringUtils.isNumeric(pageNo)) {
			pNo = Integer.parseInt(pageNo);
		}
		if(TokenManager.getUserId() ==null) {
			res.getError().add(buildError(ErrorConstants.NON_LOGIN, "", ""));return res;
		}
		res.setData(demandService.listMyDemand( pNo, pSize));
		return res;
	}
	/**
	 * 关注列表
	 */
	@RequestMapping(value = "/interestList", method = RequestMethod.GET)
	public Result interestList(Integer type,String pageNo, String pageSize) {
		Result res = new Result();
		Integer pNo = 1;
		Integer pSize = 10;
		if (null==type||type<0||type>8) {
			res.getError().add(buildError( "类型选择错误", "类型选择错误"));
		}
		if (StringUtils.isNumeric(pageSize)) {
			pSize = Integer.parseInt(pageSize);
		}

		if (StringUtils.isNumeric(pageNo)) {
			pNo = Integer.parseInt(pageNo);
		}
		res.setData(demandService.selectinterest(type, pNo, pSize));
		return res;
	}
	
	/**
	 * 成果详情
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/achievementDetail", method = RequestMethod.GET)
	private Result userDetail(String id ) {
		Result res = new Result();
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"成果必须指定","成果"));
			return res;
		}
		res.setData(achievementService.selectAppUserOwnerDetail(id));
		return res;
	}
	/**
	 * 需求详情
	 */
	@RequestMapping(value = "/demandDetail", method = RequestMethod.GET)
	public Result DemandDetail(String id ) {
		Result res = new Result();
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"需求必须指定","需求"));
			return res;
		}
		res.setData(demandService.selectAppDemandDetail( id));
		return res;
	}
	
	/**
     * 新增成果
     */
	@RequestMapping(value = "/appAddAchievement", method = RequestMethod.POST)
    private Result appAddAchievement(@Valid InputAchievement ia, BindingResult bindingResult,
            String keyword1,String keyword2,String keyword3) {
        Result res = new Result();
        List<String> keyword=new ArrayList<>();
        if (!StringUtils.isBlank(keyword1)) {
        	keyword.add(keyword1);
		}
        if (!StringUtils.isBlank(keyword2)) {
        	keyword.add(keyword2);
		}
        if (!StringUtils.isBlank(keyword3)) {
        	keyword.add(keyword3);
		}
        String[] keywords = keyword.toArray(new String[keyword.size()]);
        ia.setKeyword(StringUtils.join(keywords,","));
        if (bindingResult.hasErrors()) {
            res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
                    AchievementFields.getFieldDesc(bindingResult.getFieldError().getField())));
            return res;
        }
        
       res = disposeInputAchievement(res, ia, keywords);
        if (!res.getError().isEmpty()) {
            return res;
        }
        Achievement a = new Achievement();
        BeanUtils.copyProperties(ia, a);
        res.setData(achievementService.saveAppAchievement(a, keywords));
        return res;
    }
    
    private Result disposeInputAchievement(Result res, InputAchievement ia, String[] keywords) {
        if (StringUtils.isBlank(ia.getName())) {
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到成果名称", "成果名称"));
            return res;
        }
        if (null == ia.getCategory()) {
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到数据类别", "数据类别"));
            return res;
        }
        if (StringUtils.isBlank(ia.getKeyword())) {
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到关键词", "关键词"));
            return res;
        }
        if (null == keywords || keywords.length < 1) {
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到关键词", "关键词"));
            return res;
        }
        if (null == ia.getFieldA()) {
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到行业", "行业"));
            return res;
        }
        for (int i = 0; i < keywords.length; i++) {
            if (AFTConstants.KEYWORDLENTH < keywords[i].length()) {
                res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "关键词长度"));
                return res;
            }
        }
        return res;
    }
    
    /**
	 * 新增需求
	 */
	@RequestMapping(value = "/appAddDemand", method = RequestMethod.POST)
	public Result appAddDemand(@Valid InputDemand demand, BindingResult bindingResult,
			String keyword1,String keyword2,String keyword3,
			String validityPeriodFormattedDate) {
		Result res = new Result();
		 List<String> keyword=new ArrayList<>();
	        if (!StringUtils.isBlank(keyword1)) {
	        	keyword.add(keyword1);
			}
	        if (!StringUtils.isBlank(keyword2)) {
	        	keyword.add(keyword2);
			}
	        if (!StringUtils.isBlank(keyword3)) {
	        	keyword.add(keyword3);
			}
	        String[] keywords = keyword.toArray(new String[keyword.size()]);
	        demand.setKeyword(StringUtils.join(keywords,","));
		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					DemandFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}
		res = disposeDemand(res, demand, keywords);
		if (!res.getError().isEmpty()) {
			return res;
		}
		Demand d = new Demand();
		BeanUtils.copyProperties(demand, d);
		if (null == demand.getUrgentMoney()) {
			d.setUrgentMoney(demand.getUrgentMoney());
		}
		res.setData(demandService.saveAppUserDemand(d, validityPeriodFormattedDate, keywords));
		return res;
	}
	
	private Result disposeDemand(Result res, InputDemand demand, String[] keywords) {
		if (StringUtils.isBlank(demand.getName())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到需求名称", "需求名称"));
			return res;
		}

		if (StringUtils.isBlank(demand.getKeyword())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到关键词", "关键词"));
			return res;
		}

		if (null == keywords || keywords.length < 1) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到关键词", "关键词"));
			return res;
		}

		if (null == demand.getIndustryCategoryA()) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到行业类别", "行业类别"));
			return res;
		}

		if (null == demand.getDemandType()) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到需求类型", "需求类型"));
			return res;
		}

		if (StringUtils.isBlank(demand.getProblemDes())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到问题说明", "问题说明"));
			return res;
		}
		

		/*for (int i = 0; i < keywords.length; i++) {
			if (AFTConstants.KEYWORDLENTH < keywords[i].length()) {
				res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "关键词长度"));
				return res;
			}
		}*/

		return res;
	}
    
    
    /**
     * 成果、需求图片上传
     */
    @RequestMapping(value = "/uploadPicture", method = RequestMethod.POST)
    public Result uploadPicture(HttpServletRequest req, String sign) {
        Result res = new Result();
        AttachmentType attachmentType = AttachmentType.getField(sign);
        if (attachmentType == AttachmentType.ACHIEVEMENT_PICTURE) {
            res.setData(handleFiles(res, "/achievement/", false, req, sign, "achievement"));
        } else if (attachmentType==AttachmentType.DEMAND_PICTURE){
        	 res.setData(handleFiles(res, "/demand/", false, req, sign, "demand"));
        }else {
            res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
        }
        return res;
    }
    /**
     * 获取领域
     * @param pid
     * @param level
     * @return
     */
    @RequestMapping(value = "/getField", method = RequestMethod.POST)
    public Result getField(Integer pid, Integer level) {
    	Result res = new Result();
    	res.setData(fieldGlossoryService.getField(pid, level));
    	return res;
    }
	

	/**
	 * 获取环信登录账号，如果未注册则先注册
	 */
	@RequestMapping(value = "/easemob", method = RequestMethod.GET)
	public Result getEasemob() {
		User u = TokenManager.getUserToken();
		if (u != null) {
			JSONObject res = easemobUtils.send(new EasemobInfo().uri("/users/" + u.getNumber()).method(HttpMethod.GET));
			JSONObject resultObj = new JSONObject();
			resultObj.put("easemobPass", new SimpleHash("md5", u.getId(), null, 1).toHex());
			resultObj.put("easemobName", String.valueOf(u.getNumber()));
			resultObj.put("nickname", StringUtils.isBlank(u.getNickname()) ? "技淘用户" + u.getNumber() : u.getNickname());
			if (res == null || StringUtils.equals("service_resource_not_found", (CharSequence) res.get("error"))) {
				easemobUtils.sendLater(
						new EasemobInfo().uri("/users/").data(resultObj.toJSONString()).method(HttpMethod.POST));
			}
			return res().data(resultObj);
		} else {
			return res().error(buildError("user only", "必须是登录会员才能访问。"));
		}
	}
	/**
	 * 修改密码
	 * @param newPwd
	 * @param pwd
	 * @return
	 */
	@RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
	@ResponseBody
	public Result resetPassword(String newPwd,String pwd) {
		Result res=new Result();
		if (StringUtils.isBlank(newPwd)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "新密码"));
			return res;
		}
		if (res.getError().isEmpty() && TokenManager.isLogin()) {
			User u = new User();
			User user = userService.selectByPrimaryKey(TokenManager.getUserId());
			u.setId(user.getId());
			u.setCreateTime(user.getCreateTime());
			u.setPassword(newPwd);
			u.setPassword(passwordUtil.getEncryptPwd(u));
			if (!user.getPassword().equals(passwordUtil.getEncryptPwd(pwd, user.getCreateTime()))) {
				res.getError().add(buildError(ErrorConstants.PWD_NOT_MATCH_ERROR));
			} else {
				res.setData(userService.updateByPrimaryKeySelective(u));
			}
		}
		return res;
		
	}
	

	/*APP我的订单列表
	 * userType-----0-购买者   1-出售者  2-管理员
	 * 
	 * */
	@RequestMapping(value="/orderList",method = RequestMethod.GET)
	public Result getMyJtOrderList(Integer orderType,Integer userType,Integer pageNo,Integer pageSize) {
		Result result=new Result();
		if(userType==null || userType>1 || userType<0) { 
			result.getError().add(buildError(ErrorConstants.PARAM_ERROR,"","用户类型错误"));
			return result;
		}
		result.setData(jtOrderService.appSearchOrderList(orderType, userType, pageNo, pageSize));
		
		return result;
	}
	
	/*
	 * APP我的成果列表
	 **/
	@RequestMapping(value="/appAchievementList",method = RequestMethod.GET)
	public Result msyJtAchievementList(Integer auditStatus, String name,Integer dataCategory,  String startDate,
			String endDate,  Integer pageNo, Integer pageSize) {
		Result result=new Result();
		if(null==pageNo||pageNo<0)pageNo=1;
		if(null==pageSize||pageSize<0)pageSize=10;
		if(TokenManager.getUserId() ==null) {
			result.getError().add(buildError(ErrorConstants.NON_LOGIN, "", ""));return result;
		}
		Pagination<AchievementObject> p=achievementService.listMyAchievement(auditStatus, name, dataCategory,
				 startDate, endDate, pageNo, pageSize);
		result.data(p); 
		return result;
	}
	/**
	 * 修改成果
	 */
	@RequestMapping(value = "/updateAchievement", method = RequestMethod.POST)
	public Result updateAchievement(@Valid InputAchievement ia, BindingResult bindingResult,
			@RequestParam(name = "keywords[]", required = false) String[] keywords,
			@RequestParam(name = "publishPages[]", required = false)  String[] publishPages) {
		Result res = new Result();
		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					AchievementFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}
		if (StringUtils.isBlank(ia.getId())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到成果ID", "成果ID"));
			return res;
		}
		/*if (!AchievementAuditStatus.CREATE.getCode().equals(ia.getAuditStatus())
				&& !AchievementAuditStatus.SUBMIT.getCode().equals(ia.getAuditStatus())
				&& !AchievementAuditStatus.UNAUDITED.getCode().equals(ia.getAuditStatus())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "当前状态无法提交审核！"));
			return res;
		}*/
		List<String> webPages = new ArrayList<String>();
		List<String> appPages = new ArrayList<String>();
		PageConstants.putAchievement(publishPages, webPages, appPages);
		res = disposeInputAchievement(res, ia, keywords,publishPages);
		if (!res.getError().isEmpty()) {
			return res;
		}
		/*if(webPages.size()==0 && appPages.size() == 0){
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "页面参数错误","页面参数"));
			return res;
		}*/
		/*if(TokenManager.getUserId() ==null) {
			res.getError().add(buildError(ErrorConstants.NON_LOGIN, "", ""));return res;
		}*/
		Achievement a = new Achievement();
		BeanUtils.copyProperties(ia, a);
		a.setOwnerId(TokenManager.getUserId());
		res.setData(achievementService.updateAchievement(a, keywords, null,webPages,appPages));
		return res;
	}
	private Result disposeInputAchievement(Result res, InputAchievement ia, String[] keywords,String[] publishPages) {
		if (StringUtils.isBlank(ia.getName())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到成果名称", "成果名称"));
			return res;
		}
		if (null == ia.getCategory()) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到数据类别", "数据类别"));
			return res;
		}
		if (null == ia.getFieldA()) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到行业", "行业"));
			return res;
		}
		if (StringUtils.isBlank(ia.getKeyword())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到关键词", "关键词"));
			return res;
		}

		if (null == keywords || keywords.length < 1) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到关键词", "关键词"));
			return res;
		}
		
	
		for (int i = 0; i < keywords.length; i++) {
			if (AFTConstants.KEYWORDLENTH < keywords[i].length()) {
				res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "关键词长度"));
				return res;
			}
		}
		return res;
	}
	/**
	 * 修改需求
	 */
	@RequestMapping(value = "/updateDemand", method = RequestMethod.POST)
	public Result updateDemand(@Valid InputDemand demand, BindingResult bindingResult,
			@RequestParam(name = "keywords[]", required = false) String[] keywords,
			@RequestParam(name = "publishPages[]", required = false)  String[] publishPages,
			String validityPeriodFormattedDate) {
		Result res = new Result();
		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					DemandFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}
		if (StringUtils.isBlank(demand.getId())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到需求ID", "需求ID"));
			return res;
		}
		/*if (!DemandAuditStatus.CREATE.getCode().equals(demand.getAuditStatus())
				&& !DemandAuditStatus.UNAUDITED.getCode().equals(demand.getAuditStatus())
				&& !DemandAuditStatus.REVOKE.getCode().equals(demand.getAuditStatus())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "当前状态无法提交审核！"));
			return res;
		}*/
		//demand.setAuditStatus(DemandAuditStatus.INAUDIT.getCode()); 两步操作，先保存后提交
		res = disposeDemand(res, demand, keywords, publishPages);
		if (!res.getError().isEmpty()) {
			return res;
		}
		List<String> webPages = new ArrayList<String>();
		List<String> appPages = new ArrayList<String>();
//		PageConstants.putDemand(publishPages, webPages, appPages);
//		if(webPages.size()==0 && appPages.size() == 0){
//			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "页面参数错误"));
//			return res;
//		}
		Demand d = new Demand();
		BeanUtils.copyProperties(demand, d);
		d.setEmployerId(TokenManager.getUserId());
		res.setData(demandService.updateUserDemand(d, validityPeriodFormattedDate, keywords, webPages,appPages));
		return res;
	}
	private Result disposeDemand(Result res, InputDemand demand, String[] keywords,String[] publishPages) {
		if (StringUtils.isBlank(demand.getName())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到需求名称", "需求名称"));
			return res;
		}

//		if (!DemandDataCategory.USERDEMAND.getCode().equals(demand.getDataCategory())
//				&& !DemandDataCategory.ORGDEMAND.getCode().equals(demand.getDataCategory())) {
//			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "数据类型"));
//			return res;
//		}

		if (StringUtils.isBlank(demand.getKeyword())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到关键词", "关键词"));
			return res;
		}

		if (null == keywords || keywords.length < 1) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到关键词", "关键词"));
			return res;
		}

		if (null == demand.getIndustryCategoryA()) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到行业类别", "行业类别"));
			return res;
		}

		if (null == demand.getDemandType()) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到需求类型", "需求类型"));
			return res;
		}

		if (StringUtils.isBlank(demand.getProblemDes())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到问题说明", "问题说明"));
			return res;
		}

		for (int i = 0; i < keywords.length; i++) {
			if (AFTConstants.KEYWORDLENTH < keywords[i].length()) {
				res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "关键词长度"));
				return res;
			}
		}

		return res;
	}
	
	/*
	 * 收藏列表 0 成果 1需求 2项目
	 * */
	@RequestMapping(value="/appMyCollection",method=RequestMethod.GET)
	public Result listProjectIInterestedIn(Integer type,Integer pageNo,Integer pageSize) {
		Result res=new Result();
		if(StringUtils.isBlank(TokenManager.getUserId())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "当前用户未登陆"));
			return res;
		}
		if(null==type||type>3||type<0) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "列表类型", "列表类型请指定"));
			return res;
		}
		if (type==0) {
			res.setData(achievementService.myCollectionAchievement(pageNo, pageSize));
		} else if(type==1){
			res.setData(demandService.myCollectionDemand(pageNo, pageSize));
		} else if(type==2){
			res.setData(jtBusinessService.myCollectionProject(pageNo,pageSize));
		}
		return res;
	}
	/*
	 * 关注列表 -专家 顾问
	 * */
	@RequestMapping(value="/appMyInterested",method=RequestMethod.GET)
	public Result appMyInterested(Integer type,Integer pageNo,Integer pageSize) {
		Result result=new Result();
		if(StringUtils.isBlank(TokenManager.getUserId())) {
			result.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "当前用户未登陆"));
			return result;
		}
			result.setData(userIdentityService.appMyInterestedExpert(type,pageNo,pageSize));
		return result;
	}
	/**
	 * 消息列表
	 */
	@RequestMapping(value="/applistMessage",method=RequestMethod.GET)
	public Result applistMessage(Integer pageNo,Integer pageSize){
		Result result=new Result();
		if(StringUtils.isBlank(TokenManager.getUserId())) {
			result.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "当前用户未登陆"));
			return result;
		}
		result.setData(messageService.applistMessage(pageNo,pageSize));
		return result;
	}
	/**
	 * 读取消息
	 */
	@RequestMapping(value="/appReadMessage",method=RequestMethod.GET)
	public Result updateAppReadMessage(String id){
		Result result=new Result();
		if(StringUtils.isBlank(id)) {
			result.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "消息ID错误"));
			return result;
		}
		result.setData(messageService.updateAppReadMessage(id));
		return result;
	}
	
	/** 图片上传 **/
	@RequestMapping(value = "/uploadHeadPortrait", method = RequestMethod.POST)
	public Result uploadCustomerImg(HttpServletRequest req,String sign){
		Result res = new Result();
		res.setData(handleFile(res, "/customer_head_portrait/", false, req, sign));
		return res;
	}
	
}
