package com.goafanti.patent.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
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.multipart.MultipartFile;

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.AttachmentType;
import com.goafanti.common.model.Attachment;
import com.goafanti.common.utils.DateUtils;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.patent.bo.PatentNewBo;
import com.goafanti.patent.service.PatentNewService;


@Controller
@RequestMapping(value = "/api/admin/patentNew")
public class AdminPatentNewApiController extends CertifyApiController {

	@Resource
	private PatentNewService patentNewService;
	@Resource
	private AttachmentService	attachmentService;
 
	
	/**
	 * 新增专利信息
	 */
	@RequestMapping(value = "/addPatentNew", method = RequestMethod.POST)
	public Result addPatentNew(PatentNewBo p){
		Result res = new Result();
		if (StringUtils.isBlank(p.getPatentNo())|| StringUtils.isBlank(p.getName())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "专利", "专利"));
			return res;
		}
		if (StringUtils.isBlank(p.getEmail())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "邮箱", "邮箱"));
			return res;
		}
		if ( StringUtils.isBlank(p.getApplyDates())|| StringUtils.isBlank(p.getAuthorizationDates())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "时间", "时间"));
			return res;
		}else {
			 SimpleDateFormat sdf = new SimpleDateFormat( AFTConstants.YYYYMMDD);
		        
			 try {
				p.setApplyDate(sdf.parse(p.getApplyDates()));
				p.setAuthorizationDate(sdf.parse(p.getAuthorizationDates()));
			} catch (ParseException e) {
				res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "时间", "时间"));
				return res;
			}
		}
		return res.data(patentNewService.addPatenNew(p));
	}
	/**
	 * 修改专利信息
	 */
	@RequestMapping(value = "/updatePatentNew", method = RequestMethod.POST)
	public Result updatePatentNew(PatentNewBo p){
		Result res = new Result();
		if (p.getApplyDates()!=null) {
			p.setApplyDate(DateUtils.StringToDate(p.getApplyDates(),AFTConstants.YYYYMMDD));
		}
		if(p.getAuthorizationDates()!=null) {
			p.setAuthorizationDate(DateUtils.StringToDate(p.getAuthorizationDates(),AFTConstants.YYYYMMDD));
		}
		if (p.getTid()!=null&&patentNewService.checkTid(p.getTid())) {
			StringBuffer str=new StringBuffer("项目").append("[").append(p.getTid()).append("]"); 
			res.getError().add(buildError(ErrorConstants.DATA_EMPTY_ERROR, str.toString(), str.toString()));
			return res;
		}
		return res.data(patentNewService.updatePatenNew(p));
	}
	/**
	 * 专利列表
	 */
	@RequestMapping(value = "/selectPatentNew", method = RequestMethod.GET)
	public Result selectPatentNew(PatentNewBo p,Integer pageSize,Integer pageNo){
		Result res = new Result();
		return res.data(patentNewService.selectPatentNew(p,pageSize,pageNo));
	}
	
	
	/**
	 * 专利日志列表
	 */
	@RequestMapping(value = "/selectPatentNewLog", method = RequestMethod.GET)
	public Result selectPatentNew(Integer id){
		Result res = new Result();
		if (id==null) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"编号","编号"));
			return res;
		}
		return res.data(patentNewService.selectPatentNewLog(id));
	}
	/** 证件上传 **/
	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	public Result uploadRefundOrderFile(HttpServletRequest req,String sign){
		Result res = new Result();
		//order_refund_file
		res.setData(handleFile(res, "/patent_certificate/", false, req, sign));
		return res;
	}
	
	/**
	 * 导出专利列表
	 */
	@RequestMapping(value = "/export", method = RequestMethod.GET)
	public Result export(PatentNewBo p,Integer pageSize,Integer pageNo){
		Result res = new Result();
		return res.data(patentNewService.export( p, pageSize, pageNo));
	}
	
	/**
	 * 导出专利列表
	 */
	@RequestMapping(value = "/exportTemplate", method = RequestMethod.GET)
	public Result export(HttpServletResponse response, String sign){
        Result res = new Result();
        AttachmentType attachmentType = AttachmentType.getField(sign);
        if (attachmentType == AttachmentType.NEW_PATENT_TEMPLATE) {
            String fileName = "";
            Attachment af = attachmentService.selectByReceivbles(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.NEW_PATENT_TEMPLATE.getDesc() + suffix;
                downloadFile(response, fileName, path);
            }
        } else {
            res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
        }
        return res;
    }
	
	/**
	 * 	Excel批量导入专利
     * 
     * @return
     */
    @RequestMapping(value = "/import" , method = RequestMethod.POST)
    public Result importTemplate(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) {
    	Result res=new Result();
    	//判断文件是否存在
        if(null == file){
      	  res.getError().add(buildError("文件不存在！","文件不存在！"));
      	  return res;
        }
    	String fileName = file.getOriginalFilename();
    	if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
        	  res.getError().add(buildError("格式不正确","格式不正确"));
        	  return res;
          }
    	patentNewService.pushImportTemplate(file);
         res.data(1); 
    	return res;
    }
    
    
    /**
     * 专利缴费详情
     * @param id
     * @return
     */
    @RequestMapping(value = "/patentPaymentDetails",method = RequestMethod.GET)
    public Result patentPaymentDetails(Integer id) {
    	Result res =new Result();
    	if (id==null) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"编号"));
			return res;
		}
    	res.data(patentNewService.pushPatentPaymentDetails(id));
    	return res;
    }
    
    /**
     * 批量操作
     * @param ids
     * @param type 0 标记已通知 1批量发邮件 2转给营销员
     * @return
     */
    @RequestMapping(value = "/updateBatch",method = RequestMethod.POST)
    public Result updateBatch(String ids,Integer type,String aid) {
    	Result res =new Result();
    	if (ids==null) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"编号"));
			return res;
		}
    	if (type==null) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"操作类型"));
			return res;
		}
    	res.data(patentNewService.updateBatch(ids, type,aid));
    	return res;
    }
    
	
}
