package com.goafanti.demand.controller;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSON;
import com.goafanti.admin.service.AttachmentService;
import com.goafanti.common.bo.Result;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.constant.ErrorConstants;
import com.goafanti.common.controller.CertifyApiController;
import com.goafanti.common.enums.AchievementImportFields;
import com.goafanti.common.enums.AttachmentType;
import com.goafanti.common.enums.DeleteStatus;
import com.goafanti.common.enums.DemandAuditStatus;
import com.goafanti.common.enums.DemandFields;
import com.goafanti.common.enums.DemandImportFields;

import com.goafanti.common.enums.DemandSwitchSign;
import com.goafanti.common.model.Attachment;
import com.goafanti.common.model.Demand;
import com.goafanti.common.model.DemandFollow;
import com.goafanti.common.model.DemandFollowDetail;

import com.goafanti.common.model.DemandPublish;
import com.goafanti.common.utils.LoggerUtils;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.demand.bo.DemandImportBo;
import com.goafanti.demand.bo.InputDemand;
import com.goafanti.demand.service.DemandFollowService;
import com.goafanti.demand.service.DemandPublishPageService;
import com.goafanti.demand.service.DemandPublishService;
import com.goafanti.demand.service.DemandService;
import com.goafanti.user.service.UserService;

@RestController
@RequestMapping(value = "/api/admin/demand")
public class AdminDemandApiController extends CertifyApiController {
	@Resource
	private DemandService		demandService;
	@Resource
	private UserService			userService;
	@Resource
	private AttachmentService		aftFileService;
	
	@Resource
	DemandPublishService	demandPublishService;
	@Resource
	DemandFollowService		demandFollowService;
	/**
	 * 科技需求匹配科技成果
	 */
	@RequestMapping(value = "/matchAchievement", method = RequestMethod.POST)
	public Result matchAchievement(String id) {
		Result res = new Result();
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到需求ID", "成果ID"));
			return res;
		}
		Demand d = demandService.selectByPrimaryKey(id);
		if (null == d|| !DeleteStatus.UNDELETE.getCode().equals(d.getDeletedSign())
				|| !DemandAuditStatus.AUDITED.getCode().equals(d.getAuditStatus())) {
			res.getError().add(buildError("", "当前状态无法匹配！"));
			return res;
		}
		res.setData(demandService.updateMatchAchievement(d));
		return res;
	}

	/**
	 * 批量导入科技需求
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/importDemand", method = RequestMethod.POST)
	public Result importDemand(@RequestParam(name = "data", required = false) String d) {
		Result res = new Result();
		List<DemandImportBo> data = JSON.parseArray(d, DemandImportBo.class);
		if (data == null || data.isEmpty()) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "导入数据"));
			return res;
		}

		if (data.size() > AFTConstants.IMPORTMAXLENTH) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "导入数据量"));
			return res;
		}
		res = disposeImportDemand(res, data);
		if (!res.getError().isEmpty()) {
			return res;
		}
		data = (List<DemandImportBo>) res.getData();
		demandService.insertImport(data);
		return res;

	}

	/**
	 * 成果需求匹配列表
	 */
	@RequestMapping(value = "/achievementDemand", method = RequestMethod.GET)
	public Result achievementDemand(String id) {
		Result res = new Result();
		res.setData(demandService.selectAchievementDemandListByDemandId(id));
		return res;
	}

	/**
	 * 上传技术需求批量导入Excel模板
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/uploadTemplate", method = RequestMethod.POST)
	public Result uploadPatentTemplate(HttpServletRequest req, String sign) {
		Result res = new Result();
		String fileName = "";
		List<MultipartFile> files = getFiles(req);
		MultipartFile mf = files.get(0);
		String suffix = mf.getOriginalFilename().substring(mf.getOriginalFilename().lastIndexOf("."));
		if (suffix.equals(".xls") || suffix.equals(".xlsx")) {
			AttachmentType attachmentType = AttachmentType.getField(sign);
			if (attachmentType == AttachmentType.DEMAND_TEMPLATE) {
				fileName = sign + suffix;
			} else {
				res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
				return res;
			}
			String name = handleFile(res, req, fileName, files, mf);
			res.setData(name);
			if (!StringUtils.isBlank(name) && null == aftFileService.selectAftFileBySign(sign)) {
				Attachment f = new Attachment();
				f.setId(UUID.randomUUID().toString());
				f.setFileName(AttachmentType.DEMAND_TEMPLATE.getDesc());
				f.setUid(TokenManager.getAdminId());
				f.setComment(AttachmentType.DEMAND_TEMPLATE.getDesc());
				f.setSign(sign);
				f.setFilePath("/admin/" + fileName);
				f.setDeleletedSign(DeleteStatus.UNDELETE.getCode());
				aftFileService.insert(f);
			}
		} else {
			res.getError().add(buildError(ErrorConstants.FILE_PATTERN_ERROR, "文件格式错误，请重新上传！"));
		}
		return res;
	}

	/**
	 * 下载技术需求批量导入Excel模板
	 * 
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/downloadTemplate", method = RequestMethod.GET)
	public Result downloadTemplateFile(HttpServletResponse response, String sign) {
		Result res = new Result();
		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.DEMAND_TEMPLATE) {
			String fileName = "";
			Attachment af = aftFileService.selectAftFileBySign(sign);
			if (null == af) {
				res.getError().add(buildError(ErrorConstants.FILE_NON_EXISTENT, "", "找不到文件！"));
			} else {
				String path = af.getFilePath();
				String suffix = path.substring(path.lastIndexOf("."));
				fileName = AttachmentType.DEMAND_TEMPLATE.getDesc() + suffix;
				downloadFile(response, fileName, path);
			}
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}
		return res;
	}

	/**
	 * 个人用户--需求列表
	 */
	@RequestMapping(value = "/userList", method = RequestMethod.GET)
	public Result userList(String employerName, Integer auditStatus, Integer province, Integer serialNumber, String name, String keyword,
			Integer infoSources, Integer demandType, String validityPeriodStartDate, String validityPeriodEndDate,
			String username, Integer status, Integer releaseStatus, String releaseDateStartDate,
			String releaseDateEndDate,String createDateStartDate, String createDateEndDate, String pageNo, String pageSize,Integer boutique,Integer hot) {
		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.selectUserDemandManageList(employerName, auditStatus, province, serialNumber, name, keyword,
				infoSources, demandType, validityPeriodStartDate, validityPeriodEndDate, username, status,
				releaseStatus, releaseDateStartDate, releaseDateEndDate, createDateStartDate,  createDateEndDate, pNo, pSize,boutique,hot));
		return res;
	}

	/**
	 * 组织用户--需求列表(个人组织合并)
	 */
	@RequestMapping(value = "/orgList", method = RequestMethod.GET)
	public Result orgList(Integer dataCategory,String employerName, Integer auditStatus, Integer province, Integer serialNumber, String name, String keyword,
			Integer infoSources, Integer demandType, String validityPeriodStartDate, String validityPeriodEndDate,
			String unitName, Integer status, Integer releaseStatus, String releaseDateStartDate,
			String releaseDateEndDate,String createDateStartDate, String createDateEndDate, String pageNo, String pageSize,Integer boutique,Integer hot,String recordPerson) {
		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.selectOrgDemandManageList(dataCategory,employerName, auditStatus, province, serialNumber, name, keyword,
				infoSources, demandType, validityPeriodStartDate, validityPeriodEndDate, unitName, status,
				releaseStatus, releaseDateStartDate, releaseDateEndDate, createDateStartDate,  createDateEndDate, pNo, pSize,boutique,hot,TokenManager.getAdminId(),recordPerson));
		return res;
	}

	/**
	 * 新增需求
	 */
	@RequestMapping(value = "/apply", method = RequestMethod.POST)
	public Result userApply(@Valid InputDemand demand, BindingResult bindingResult,
			@RequestParam(name = "keywords[]", required = false) String[] keywords,
			String validityPeriodFormattedDate,String coverImg,Integer hot) {
		
		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.getEmployerId()) && StringUtils.isBlank(demand.getEmployerName())){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到需求雇主", "需求雇主"));
			return res;
		}

		res = disposeDemand(res, demand, keywords);
		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());
		}
		demandService.saveUserDemand(d, validityPeriodFormattedDate, keywords);
		return res;
	}

	/**
	 * 个人需求详情
	 */
	@RequestMapping(value = "/userDemandDetail", method = RequestMethod.GET)
	public Result userDemandDetail(String id) {
		Result res = new Result();
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到需求ID", "需求ID"));
			return res;
		}

		res.setData(demandService.selectUserDemandDetail(id));
		return res;
	}

	/**
	 * 组织用户详情(个人组织合并)
	 */
	@RequestMapping(value = "/orgDemandDetail", method = RequestMethod.GET)
	public Result orgDemandDetail(String id,Integer dataCategory) {
		Result res = new Result();

		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到需求ID", "需求ID"));
			return res;
		}
		if(dataCategory==0){
			res.setData(demandService.selectUserDemandDetail(id));
			return res;
		}else if(dataCategory==1){
			res.setData(demandService.selectOrgDemandDetail(id));
			return res;
		}
		return res;
	}

	/**
	 * 需求管理--获取个人用户下拉
	 */
	@RequestMapping(value = "/userNames", method = RequestMethod.GET)
	public Result getUserNames() {
		Result res = new Result();
		res.setData(userService.selectDemandUserNames());
		return res;
	}

	/**
	 * 需求管理--获取组织用户下拉
	 */
	@RequestMapping(value = "/unitNames", method = RequestMethod.GET)
	public Result getUnitNames() {
		Result res = new Result();
		res.setData(userService.selectDemandUnitNames());
		return res;
	}

	/**
	 * 需求资料--图片上传
	 */
	@RequestMapping(value = "/uploadPicture", method = RequestMethod.POST)
	public Result uploadPicture(HttpServletRequest req, String sign, String uid) {
		Result res = new Result();
		if (StringUtils.isBlank(uid)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到用户ID", "用户ID"));
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);

		if (attachmentType == AttachmentType.DEMAND_PICTURE|| attachmentType == AttachmentType.DEMAND_COVER_PICTURE) {
			res.setData(handleFiles(res, "/demand/", false, req, sign, uid));
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}

		return res;
	}

	/**
	 * 需求资料--文本文件上传
	 */
	@RequestMapping(value = "/uploadTextFile", method = RequestMethod.POST)
	public Result uploadTextFile(HttpServletRequest req, String sign, String uid) {
		Result res = new Result();

		if (StringUtils.isBlank(uid)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到用户ID", "用户ID"));
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);

		if (attachmentType == AttachmentType.DEMAND_TEXT_FILE) {
			res.setData(handleFiles(res, "/demand/", false, req, sign, uid));
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}
		return res;
	}

	/**
	 * 修改需求
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public Result updateUser(@Valid InputDemand demand, BindingResult bindingResult, Integer switchSign,
			@RequestParam(name = "keywords[]", required = false) String[] keywords,
			String validityPeriodFormattedDate,String coverImg,Integer hot) {
		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 (StringUtils.isBlank(demand.getEmployerId()) && StringUtils.isBlank(demand.getEmployerName())){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到需求雇主", "需求雇主"));
			return res;
		}
		
		if (!DemandSwitchSign.CLOSE.getCode().equals(switchSign)
				&& !DemandSwitchSign.OPEN.getCode().equals(switchSign)) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "开关标记"));
			return res;
		}
		
		if (!DemandAuditStatus.CREATE.getCode().equals(demand.getAuditStatus())
				&& !DemandAuditStatus.SUBMIT.getCode().equals(demand.getAuditStatus())
				&& !DemandAuditStatus.UNAUDITED.getCode().equals(demand.getAuditStatus())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "当前状态无法提交审核！"));
			return res;
		}

		res = disposeDemand(res, demand, keywords);
		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.updateUserDemand(d, validityPeriodFormattedDate, keywords, switchSign));
				
		return res;
	}

	/**
	 * 需求撤消发布(下架)
	 */
	@RequestMapping(value = "/offShelf", method = RequestMethod.POST)
	public Result offShelf(String id,Integer releaseStatus) {
		Result res = new Result();
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到需求ID", "需求ID"));
			return res;
		}

		Demand d = demandService.selectByPrimaryKey(id);

		if (null == d) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "需求ID"));
			return res;
		}
		d.setReleaseStatus(releaseStatus);
		res.setData(demandService.updateReleaseStatus(d));
		return res;
	}

	/**
	 * 下载需求文件--文本文件
	 */
	@RequestMapping(value = "/download", method = RequestMethod.GET)
	public Result download(HttpServletResponse response, String id) {
		Result res = new Result();

		if (StringUtils.isEmpty(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "需求ID"));
			return res;
		}

		Demand d = demandService.selectByPrimaryKey(id);
		if (null == d) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "需求ID"));
			return res;
		}

		downloadUnPrivateFile(response, d.getTextFileDownloadFileName(), d.getTextFileUrl());
		return res;
	}

	/**
	 * 删除需求(个人&团体)
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public Result delete(@RequestParam(name = "ids[]", required = false) String[] ids) {
		Result res = new Result();
		if (ids == null || ids.length != 1) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", ""));
		} else {
			
			//marketingManagementService.deleteByProductId(Arrays.asList(ids));
			res.setData(demandService.deleteByPrimaryKey(Arrays.asList(ids)));
		}
		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 (!DemandDataCategory.USERDEMAND.getCode().equals(demand.getDataCategory())
				&& !DemandDataCategory.ORGDEMAND.getCode().equals(demand.getDataCategory())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "数据类型"));
			return res;
		}*/
		if (null == demand.getDataCategory()) {
			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.getInfoSources()) {
			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;
	}

	private String handleFile(Result res, HttpServletRequest req, String fileName, List<MultipartFile> files,
			MultipartFile mf) {
		if (!files.isEmpty()) {
			try {
				mf.transferTo(toAdminPrivateFile(fileName));
				LoggerUtils.debug(getClass(), fileName + " 文件上传成功");
			} catch (IllegalStateException | IOException e) {
				LoggerUtils.error(getClass(), "文件上传失败", e);
				res.getError().add(buildError("", "文件上传失败!"));
				return "";
			}
		} else {
			res.getError().add(buildError("", "文件上传失败!"));
			return "";
		}
		return fileName;
	}

	private Result disposeImportDemand(Result res, List<DemandImportBo> data) {
		Field[] field = DemandImportBo.class.getDeclaredFields();
		for (DemandImportBo bo : data) {
			for (Field f : field) {
				try {
					Object fo = f.get(bo);
					f.setAccessible(true);
					String fn = f.getName();
					if (!fn.equals("keywords") && (fo == null || "".equals(fo))) {
						res.getError().add(
								buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", DemandImportFields.getFieldDesc(fn)));
						return res;
					}
				} catch (IllegalArgumentException | IllegalAccessException e) {
				}
			}

			String[] keywords = bo.getKeyword().trim().split(",|，");
			if (null == keywords || keywords.length < 1) {
				res.getError()
						.add(buildError(ErrorConstants.PARAM_ERROR, "", AchievementImportFields.KEYWORD.getDesc()));
				return res;
			}

			List<String> list = new ArrayList<>();
			for (String s : keywords) {
				if (!StringUtils.isBlank(s)) {
					list.add(s.trim());
				}
			}

			bo.setKeywords(list);
		}
		res.setData(data);
		return res;
	}
	
	/**
	 * 我的需求列表
	 */
	@RequestMapping(value = "/myList", method = RequestMethod.GET)
	public Result myList(Integer dataCategory,String employerName, Integer auditStatus, Integer province, Integer serialNumber, String name, String keyword,
			Integer infoSources, Integer demandType, String validityPeriodStartDate, String validityPeriodEndDate,
			String unitName, Integer status, Integer releaseStatus, String releaseDateStartDate,
			String releaseDateEndDate,String createDateStartDate, String createDateEndDate, String pageNo, String pageSize,Integer boutique,Integer hot) {
		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.selectMyDemandManageList(dataCategory,employerName, auditStatus, province, serialNumber, name, keyword,
				infoSources, demandType, validityPeriodStartDate, validityPeriodEndDate, unitName, status,
				releaseStatus, releaseDateStartDate, releaseDateEndDate, createDateStartDate,  createDateEndDate, pNo, pSize,boutique,hot,TokenManager.getAdminId()));
		return res;
	}
	
	/**
	 * 科技需管理求列表
	 */
	@RequestMapping(value = "/manageList", method = RequestMethod.GET)
	public Result manageList(Integer dataCategory,String employerName, Integer auditStatus, Integer province, Integer serialNumber, String name, String keyword,
			Integer infoSources, Integer demandType, String validityPeriodStartDate, String validityPeriodEndDate,
			String unitName, Integer status, Integer releaseStatus, String releaseDateStartDate,
			String releaseDateEndDate,String createDateStartDate, String createDateEndDate, String pageNo, String pageSize,Integer boutique,Integer hot,String recordPerson) {
		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.selectManageDemandManageList(dataCategory,employerName, auditStatus, province, serialNumber, name, keyword,
				infoSources, demandType, validityPeriodStartDate, validityPeriodEndDate, unitName, status,
				releaseStatus, releaseDateStartDate, releaseDateEndDate, createDateStartDate,  createDateEndDate, pNo, pSize,boutique,hot,TokenManager.getAdminId(),recordPerson));
		return res;
	}
	/**
     * 需求发布
     */
    @RequestMapping(value = "/addDemandPublish", method = RequestMethod.POST)
    private Result addDemandPublish(DemandPublish d) {
    	Result res = new Result();
    	if (StringUtils.isBlank(d.getDemandId())) {
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到需求", "需求"));
            return res;
        }
        res.setData(demandPublishService.insertDemandPublish(d));     
        return res;
    }
    /**
     * 撤销发布
     */
    @RequestMapping(value = "/deletePublish", method = RequestMethod.GET)
    private Result deletePublish(String id) {
        Result res = new Result();
        res.setData(demandPublishService.deletePublish(id));     
        return res;
    }
    /**
     * 修改发布
     */
    @RequestMapping(value = "/updatePublish", method = RequestMethod.GET)
    private Result updatePublish(DemandPublish d) {
        Result res = new Result();
        res.setData(demandPublishService.updatePublish(d));     
        return res;
    }
    
    /**
     * 发布列表
     */
    @RequestMapping(value = "/listPublish", method = RequestMethod.GET)
    private Result listPublish(String name,String publishPlatform,Integer publishClient,String publishPage,
    		Integer ifTop, Integer pageNo, Integer pageSize,String employerName) {
        Result res = new Result();
        if (null==pageNo) {
			pageNo=1;
		}
        if (null==pageSize) {
			pageSize=10;
		}
        res.setData(demandPublishService.listPublish( name, publishPlatform, publishClient, publishPage,
        		 ifTop,  pageNo,  pageSize,employerName));     
        return res;
    }
    /**
     * 获取需求页面位置
     */
    @RequestMapping(value="/getPublishPage",method = RequestMethod.GET)
    private Result getPublishPage(){
    	Result res=new Result();
    	return res.data(DemandPublishPageService.getBranchInformation());
    }
    /**
     * 新增匹配跟进保存
     */
    @RequestMapping(value = "/addDemandFollow", method = RequestMethod.POST)
    private Result addDemandFollow(DemandFollow d) {
    	Result res = new Result();
    	if (StringUtils.isBlank(d.getDemandId())) {
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到需求", "需求"));
            return res;
        }
    	if (StringUtils.isBlank(d.getContactMobile())) {
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到联系人电话", "联系人电话"));
            return res;
        }
    	if (StringUtils.isBlank(d.getContacts())) {
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到联系人", "联系人"));
            return res;
        }
    	if (StringUtils.isBlank(d.getOrganization())) {
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到机构", "机构"));
            return res;
        }
    	res.data(demandFollowService.insertDemandFollow(d));     
        return res;
    }
    
    /**
     * 修改匹配跟进
     */
    @RequestMapping(value = "/updateDemandFollow", method = RequestMethod.POST)
    private Result DemandFollow(DemandFollow d) {
    	Result res = new Result();
    	if (StringUtils.isBlank(d.getId())) {
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到需求匹配", "匹配跟进"));
            return res;
        }
    	res.setData(demandFollowService.updateDemandFollow(d));     
        return res;
    }
    
    /**
     * 新增跟进情况
     */
    @RequestMapping(value = "/addDemandFollowDetail", method = RequestMethod.POST)
    private Result addDemandFollowDetail(DemandFollowDetail d,String createTimeFormattedDate) {
    	Result res = new Result();
    	if (StringUtils.isBlank(d.getDemandFollowId())) {
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到需求匹配跟进", "需求匹配跟进"));
            return res;
        }
    	if (StringUtils.isBlank(d.getRemarks())) {
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到跟进情况", "跟进情况"));
            return res;
        }
    	if (null==d.getResult()) {
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到跟进结果", "跟进结果"));
            return res;
        }
    	if (StringUtils.isBlank(createTimeFormattedDate)) {
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到跟进时间", "跟进时间"));
            return res;
        }
    	res.data(demandFollowService.insertDemandFollowDetail(d,createTimeFormattedDate));     
        return res;
    }
    
    /**
     * 跟进列表
     */
    @RequestMapping(value = "/listDemandFollow", method = RequestMethod.GET)
    private Result listDemandFollow(String id,Integer pNo,Integer pSize) {
    	Result res = new Result();
    	if (StringUtils.isBlank(id)) {
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到需求匹配跟进", "需求匹配跟进"));
            return res;
        }
    	res.data(demandFollowService.selectDemandFollow( id, pNo, pSize));
        return res;
    }
    
    /**
     * 删除跟进
     */
    @RequestMapping(value = "/deleteDemandFollow", method = RequestMethod.GET)
    private Result deleteDemandFollow(String id) {
    	Result res = new Result();
    	if (StringUtils.isBlank(id)) {
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到需求匹配跟进", "需求匹配跟进"));
            return res;
        }
    	res.data(demandFollowService.deleteDemandFollow( id));
        return res;
    }
    
    /**
     * 跟进情况列表
     */
    @RequestMapping(value = "/listDemandFollowDetail", method = RequestMethod.GET)
    private Result listDemandFollowDetail(String id,Integer pNo, Integer pSize) {
    	Result res = new Result();
    	if (StringUtils.isBlank(id)) {
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到需求跟进", "需求跟进"));
            return res;
        }
    	res.data(demandFollowService.selectDemandFollowDetail( id,pNo,  pSize));
        return res;
    }
    /**
     * 匹配跟进
     */
    @RequestMapping(value = "/DemandFollowDetails", method = RequestMethod.GET)
    private Result DemandFollowDetails(String id) {
    	Result res = new Result();
    	if (StringUtils.isBlank(id)) {
            res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到需求跟进", "需求跟进"));
            return res;
        }
    	res.data(demandService.DemandFollowDetails(id));
        return res;
    }
}
