package com.seeyon.apps.src_ordinary.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.src_ordinary.dao.IOrdinaryDao;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager;
import com.seeyon.ctp.organization.manager.OrgManagerDirect;
import jodd.util.StringUtil;

public class OrdinaryCodeServlet extends HttpServlet{

    private volatile boolean running;
	
	private IOrdinaryDao ordinaryDao;
	public void setOrdinaryDao(IOrdinaryDao ordinaryDao) {
		this.ordinaryDao = ordinaryDao;
	}
	public IOrdinaryDao getOrdinaryDao() {
		if (this.ordinaryDao == null) {
	        this.ordinaryDao = ((IOrdinaryDao)AppContext.getBean("ordinaryDao"));
	      }
	  return ordinaryDao;
	}
	
	private OrgManagerDirect orgManagerDirect;
	
	public OrgManagerDirect getOrgManagerDirect() {
		  if (this.orgManagerDirect == null) {
		        this.orgManagerDirect = ((OrgManagerDirect)AppContext.getBean("orgManagerDirect"));
		      }
		  return orgManagerDirect;
	}
	
	public void setOrgManagerDirect(OrgManagerDirect orgManagerDirect) {
		this.orgManagerDirect = orgManagerDirect;
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException{
//		获取请求参数
		ServletOutputStream servletout = response.getOutputStream();
		InputStream servletin = request.getInputStream();
		byte[] bytes = new byte[request.getContentLength()];
		System.out.println(request.getContentLength());
		String dataid = request.getParameter("dataid");
		String unitCode = request.getParameter("unitCode");
		String oanum = request.getParameter("oanum");
		servletin.read(bytes);
//		将钉钉传递的参数转换成String格式
		String str = new String(bytes, "utf-8");
		System.out.println(str);
		String[] strs = str.split("&");
//		将String转换成json
		Map<String,Object> paramMap = new HashMap<String, Object>();
		for(int i = 0 ; i < strs.length ; i++) {
			String[] param = strs[i].split("=");
			if(param.length != 1 ) {
				paramMap.put(param[0], param[1]);
			}
		}
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
		String datestr = sdf.format(date);

		if(StringUtil.isEmpty(unitCode)){
			unitCode = paramMap.get("unitCode").toString();
		}
		if(StringUtil.isEmpty(oanum)){
			oanum = paramMap.get("oanum").toString();
		}

//		String unitCode = paramMap.get("unitCode").toString();
//		String oanum = paramMap.get("oanum").toString();
//		unitCode = unitCode+datestr.substring(0,6);
		unitCode = unitCode+"_"+datestr;
		if(running) {
			System.out.println("业务繁忙，重新生成");
			Map<String,Object> map  = new HashMap<>();
			map.put("isSucceed", "500");
			map.put("msg","业务繁忙，请重新生成");
//			r = false;
			String s = JSONObject.toJSONString(map);
//			将验证信息回传给钉钉进行校验
			byte[] buf = s.getBytes("UTF-8");
			servletout.write(buf);
			servletout.flush();
			servletout.close();
			return ;
    	}
		try {
			running = true;
			List<String> contractCodes = getOrdinaryDao().getOrdinaryCodes(unitCode);
			String code = "";
			if(contractCodes.size()>0) {
				for(int i = 1 ;i <1000;i++) {
					String sum = String.format("%03d", i);
					if(!contractCodes.contains(sum)) {
						code = unitCode+sum;
						break;
					}
				}
			}else {
	//			当前没有查询到此公司下存在合同编号生成合同编号001
				code = unitCode+"001";
			}
	//		变更数据库编码信息
			int contractsize = getOrdinaryDao().updateOrdinaryCodes(code,oanum);
			Map<String,Object> map  = new HashMap<>();
			if(contractsize==1) {
				System.out.println("生成成功"+code);
				map.put("isSucceed", "200");
				map.put("newCode",code);
			}else {
				map.put("isSucceed", "500");
				map.put("msg","生成失败，请在合同核定时生成合同编号。");
			}
			String s = JSONObject.toJSONString(map);
			//		将验证信息回传给钉钉进行校验
			byte[] buf = s.getBytes("UTF-8");
			servletout.write(buf);
			servletout.flush();
			servletout.close();
		}catch(Exception e){
			System.out.println(e);
		}finally {
    		this.running = false;
    	}
	  }
	

	  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		  doGet(request,response);
	  }
	  
	  
	  public void init() throws ServletException { }

	  public void destroy() {
	    super.destroy();
	  }
}
