package com.seeyon.apps.src_contract.lease.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
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_contract.lease.dao.ILeaseContractDao;
import com.seeyon.apps.src_contract.lease.kit.PropKit;
import com.seeyon.apps.src_contract.lease.param.LeaseContractParam;
import com.seeyon.apps.src_contract.lease.util.FormExportUtil;
import com.seeyon.apps.src_contract.lease.util.HeaderUtil;
import com.seeyon.apps.src_contract.lease.util.ProtUtil;
import com.seeyon.apps.src_contract.lease.util.RentCalculationUtil;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.services.ServiceException;
import com.seeyon.v3x.services.form.FormFactory;
import com.seeyon.v3x.services.form.bean.FormExport;
import com.seeyon.v3x.services.form.bean.SubordinateFormExport;
import com.seeyon.v3x.services.form.bean.ValueExport;

public class LeaseContractServlet extends HttpServlet{

private EnumManager enumManagerNew;
	
	public void setEnumManagerNew(EnumManager enumManagerNew) {
		this.enumManagerNew = enumManagerNew;
	}
	public EnumManager getEnumManager() {
		if (this.enumManagerNew == null) {
	        this.enumManagerNew = ((EnumManager)AppContext.getBean("enumManagerNew"));
	      }
	  return enumManagerNew;
	}
	
	private FormFactory formFactory;
	
	public FormFactory getFormFactory() {
		if (formFactory == null) {
			formFactory = (FormFactory) AppContext.getBean("formFactory");
		}
		return formFactory;
	}
	
	public void setFormFactory(FormFactory formFactory) {
		this.formFactory = formFactory;
	}
	
private ILeaseContractDao leaseContractDao;
	
	public ILeaseContractDao getLeaseContractDao() {
		if (leaseContractDao == null) {
			leaseContractDao = (ILeaseContractDao) AppContext.getBean("leaseContractDao");
		}
		return leaseContractDao;
	}
	
	public void setLeaseContractDao(ILeaseContractDao leaseContractDao) {
		this.leaseContractDao = leaseContractDao;
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException{
//		获取请求参数
		ServletOutputStream servletout = response.getOutputStream();
		InputStream servletin = request.getInputStream();
		byte[] bytes = new byte[request.getContentLength()];
		servletin.read(bytes);
//		将钉钉传递的参数转换成String格式
		String str = new String(bytes, "utf-8");
		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]);
			}
		}
		System.out.println(paramMap);
		Map<String,Object> map  = new HashMap<>();
		String contractCode = paramMap.get("contractCode").toString();
//		删除合同编号为租赁合同的主表和明细表数据
		if("".equals(contractCode)) {
			map.put("isSucceed", "200");
			map.put("msg","请填写合同编号");
		}else {
			try {
				int i = getLeaseContractDao().daleteFZLeaseSub(contractCode);
				Thread.sleep(1000);
				int n = getLeaseContractDao().daleteFZLease(contractCode);
			} catch (BusinessException | SQLException | InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		JSONObject jsonObject = LeaseContractParam.getPaymentplandetailParam(paramMap);
    	System.out.println(jsonObject);
		JSONObject headerer = HeaderUtil.getHeader();
    	JSONObject res = ProtUtil.doPost(jsonObject, PropKit.getProp(PropKit.PAYMENTPLANDETAILURL), headerer);
		System.out.println(res);
		if(!res.isEmpty()) {
			String  isStatus =  res.get("status").toString();
			if(!"1".equals(isStatus)) {
				map.put("isSucceed", "200");
				map.put("msg","租金明细生成失败:"+res.getString("msg"));
				String s = JSONObject.toJSONString(map);
//			将验证信息回传给钉钉进行校验
				byte[] buf = s.getBytes("UTF-8");
				servletout.write(buf);
				servletout.flush();
				servletout.close();
				return ;
			}
		}else {
			map.put("isSucceed", "200");
			map.put("msg","租金明细生成失败请联系管理员处理");
			String s = JSONObject.toJSONString(map);
//		将验证信息回传给钉钉进行校验
			byte[] buf = s.getBytes("UTF-8");
			servletout.write(buf);
			servletout.flush();
			servletout.close();
			return ;
		}
		RentCalculationUtil rentCalculationUtil = new RentCalculationUtil();
		List<Map<String,Object>> sublist = new ArrayList<Map<String,Object>>();
		sublist = rentCalculationUtil.handleCollectionSub(res.getJSONArray("data"));
		Map<String,Object> mainmap = new HashMap<String,Object>();
		mainmap.put("单据编号", paramMap.get("contractCode"));
		
		FormExportUtil formExportUtil = new FormExportUtil();
		FormExport formExport = new FormExport();
		List<SubordinateFormExport> subordinateFormExports = formExportUtil.setSubordinateFormValue(sublist);
		List<ValueExport> valueExports = formExportUtil.setFormValue(mainmap);
		formExport.setSubordinateForms(subordinateFormExports);
    	formExport.setValues(valueExports);
    	try {
//			getFormFactory().importBusinessFormData("shenxian", "FZZJJS",
//					formExport, new String[] {});
			getFormFactory().importBusinessFormData("oatest2", "FZZJJS",
					formExport, new String[] {});
		} catch (ServiceException e) {
			e.printStackTrace();
			map.put("isSucceed", "200");
			map.put("msg","租金明细生成失败请联系管理员处理");
		}
		if(sublist.size()>0) {
			//成功计算租金，则删除当前存在的租金计算数据
			map.put("isSucceed", "200");
			map.put("msg","计算成功");
		}else {
			//租金计算失败，则创建返回数据，提示前台
			map.put("isSucceed", "200");
			map.put("msg","计算失败，请检查合同主体数据");
		}
		
		String s = JSONObject.toJSONString(map);
//		将验证信息回传给钉钉进行校验
		byte[] buf = s.getBytes("UTF-8");
		servletout.write(buf);
		servletout.flush();
		servletout.close();
	  }
	

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

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