package com.goafanti.app.controller;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
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.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.common.bo.Result;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.constant.ErrorConstants;
import com.goafanti.common.controller.BaseApiController;
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.User;
import com.goafanti.common.service.FieldGlossoryService;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.demand.bo.InputDemand;
import com.goafanti.demand.service.DemandService;
import com.goafanti.news.service.NewsService;
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(path = "/app/user", method = RequestMethod.GET)
public class AppUserController extends BaseApiController {
	@Resource
	private UserService userServiceImpl;
	@Resource
	private AchievementService	achievementService;
	@Resource
	private DemandService		demandService;
	@Resource
	private UserIdentityService	userIdentityService;
	@Resource
	AchievementInterestService achievementInterestService;
	@Resource
	private FieldGlossoryService fieldGlossoryService;



	@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(StringUtils.isBlank(u.getNickname())){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"用户昵称不能为空"));
			return res;
		}
		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();
		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.GET)
	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 = "/achievementList", method = RequestMethod.GET)
	private Result achievementList(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);
		}
		res.setData(achievementService.listAppMyAchievement(pNo, pSize));
		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);
		}
		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;
	}
	/**
	 * 专家详情
	 */
	@RequestMapping(value = "/expertsDetail", method = RequestMethod.GET)
	public Result expertsDetail(String uid) {
		Result res = new Result();
		if (StringUtils.isBlank(uid)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"专家必须指定","专家"));
			return res;
		}
		res.setData(userIdentityService.expertsDetail( uid));
		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.selectDemandDetail( 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=(String[])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.getCooperationMode()) {
            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();
		 /*String[] keywords ;
	       if (StringUtils.isNotEmpty(keyword3)) {
	        	keywords=new String[]{keyword1,keyword2};
	        }else if (StringUtils.isNotEmpty(keyword2)) {
	        	keywords=new String[]{keyword1};
	        }else {
	        	keywords=new String[]{keyword1,keyword2,keyword3};
			}
	        if (null!=keywords) {
	        	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, null);
		if (!res.getError().isEmpty()) {
			return res;
		}
		Demand d = new Demand();
		BeanUtils.copyProperties(demand, d);
		if (StringUtils.isNotBlank(demand.getUrgentDays())) {
			d.setUrgentDays(demand.getUrgentDays());
		}
		if (null==demand.getUrgentMoney()) {
			d.setUrgentMoney(demand.getUrgentMoney());
		}
		res.setData(demandService.saveAppUserDemand(d, validityPeriodFormattedDate, null));
		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_TECHNICAL_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;
    }


}
