package nc.bs.my.arap;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import nc.bs.arap.constant.PropertyNCBilltypeConstant;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.NCLocator;
import nc.itf.arap.pay.IArapPayBillQueryService;
import nc.jdbc.framework.processor.BeanListProcessor;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.vo.arap.basebill.BaseAggVO;
import nc.vo.arap.pay.AggPayBillVO;
import nc.vo.bd.defdoc.DefdocVO;
import nc.vo.pub.AggregatedValueObject;
import nc.vo.pub.BusinessException;
import uap.json.JSONObject;

public class MyYfApproveStatusUtil {

	String url = "";
	String apikey = "";

	public void doAction(AggregatedValueObject[] bills) throws BusinessException {
		// 1.获取操作数据
		Object[] aggPayBillVOs = (Object[]) (bills);
		if (aggPayBillVOs == null) {
			return;
		}
		DefdocVO[] mdmservice = getQueryDefdoc("my_service");
		if (mdmservice != null) {
			for (DefdocVO doc : mdmservice) {
				if ("status_url".equals(doc.getCode())) {
					url = doc.getShortname();
				} else if ("status_apikey".equals(doc.getCode())) {
					apikey = doc.getShortname();
				}
			}
		}
		// 2.组装接口报文
		for (Object vo : aggPayBillVOs) {
			BaseAggVO pbaggvo = (BaseAggVO) vo;
			String def81 = pbaggvo.getHeadVO().getDef81();// 是否上共享
			String def82 = pbaggvo.getHeadVO().getDef82();// 是否上线前审批
			if ("Y".equals(def81) && "Y".equals(def82)) {
			} else {
				continue;
			}
			// 获取文件路径名
			JSONObject parm = new JSONObject();
			// 只有明源应付单执行接口
			if (PropertyNCBilltypeConstant.F1W02BILLTYPE.equals(pbaggvo.getHeadVO().getPk_tradetype())) {
				String def1 = pbaggvo.getHeadVO().getDef1();
				if (def1 != null) {
					IArapPayBillQueryService serivce = NCLocator.getInstance().lookup(IArapPayBillQueryService.class);
					AggPayBillVO[] aggVOs = serivce.queryBillsByWhereSQL("def1='" + def1 + "' and dr=0");
					if (aggVOs != null && aggVOs.length > 0) {
						String top_billid = aggVOs[0].getItems()[0].getTop_billid();
						if (top_billid == null) {
							parm.put("BusinessType", 102);
							parm.put("BillCode", pbaggvo.getHeadVO().getDef40()); // 明源系统的主键guid
						} else {
							return;
						}
					} else {
						parm.put("BusinessType", 101);
						parm.put("BillCode", pbaggvo.getHeadVO().getDef1()); // 明源系统的主键guid
					}
					String fileUrl = toFileUrl(pbaggvo);
					parm.put("FileUrl", fileUrl);
					parm.put("ApproveStatus", "已审核"); // 返回明源的操作状态
					// 调用接口
					try {
						String jiekou = httpURLConnectionPOST(parm.toString(), url);
						com.alibaba.fastjson.JSONObject jsonObj = JSON.parseObject(jiekou);
						if (jsonObj != null) {
							// 调用接口成功或者失败
							Integer code = jsonObj.getInteger("Code");
							if (1 == code) {
								throw new BusinessException(jsonObj.getString("Msg"));
							}
						}
					} catch (Exception e) {
						throw new BusinessException("调用明源失败:" + e.getMessage() + "");
					}
				}
			}
			// }
		}

	}

	private String toFileUrl(BaseAggVO vo) throws BusinessException {
		List<Map<String, String>> query = (List<Map<String, String>>) dao
				.executeQuery("select vdef1,appcode  from  erm_bgyimageconfig where transtype ='"
						+ vo.getHeadVO().getPk_tradetype() + "'", new MapListProcessor());
		StringBuffer url = new StringBuffer();
		if (query == null || query.size() <= 0) {
			throw new BusinessException("获取应付审批封面地址失败,交易类型为：" + vo.getHeadVO().getPk_tradetype() + "，请联系用友顾问!");
		}
		url.append(query.get(0).get("vdef1") + "?");
		url.append("appcode=" + query.get(0).get("appcode") + "");
		url.append("&Oids=" + vo.getHeadVO().getPrimaryKey());

		String fileUrl = url.toString();
		return fileUrl;
	}

	public String httpURLConnectionPOST(String parm, String posturl) throws Exception {
		URL url = new URL(posturl);

		HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 此时cnnection只是为一个连接对象,待连接中

		// 设置连接输出流为true,默认false
		connection.setDoOutput(true);

		// 设置连接输入流为true
		connection.setDoInput(true);

		// 设置请求方式为post
		connection.setRequestMethod("POST");

		// post请求缓存设为false
		connection.setUseCaches(false);

		// 设置该HttpURLConnection实例是否自动执行重定向
//		connection.setInstanceFollowRedirects(true);

		connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");

		connection.setRequestProperty("apikey", "rJ2KtOYzg6eiqWDcfyb5u6V7dOfieY8q");

		// 建立连接 (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
		connection.connect();

		// 创建输入输出流,用于往连接里面输出携带的参数
		DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());

		dataout.write(parm.getBytes("UTF-8"));
		// 输出完成后刷新并关闭流
		dataout.flush();
		dataout.close();
		BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
		String line;
		StringBuilder sb = new StringBuilder(); // 用来存储响应数据

		// 循环读取流,若不到结尾处
		while ((line = bf.readLine()) != null) {
//			sb.append(bf.readLine());
			sb.append(line);// .append(System.getProperty("line.separator"));
		}
		bf.close();
		connection.disconnect(); // 销毁连接
		if (sb != null && !"".equals(sb)) {
			return sb.toString();
		}
		return null;
	}

	public DefdocVO[] getQueryDefdoc(String defdoclistcode) throws BusinessException {
		String sql = "select * from bd_defdoc where pk_defdoclist=(select pk_defdoclist from bd_defdoclist where code='"
				+ defdoclistcode + "') and dr=0";
		java.util.List<DefdocVO> classvo = (List<DefdocVO>) dao.executeQuery(sql,
				new BeanListProcessor(DefdocVO.class));
		if (classvo != null && classvo.size() > 0) {
			return classvo.toArray(new DefdocVO[0]);
		}
		return null;
	}

	BaseDAO dao = new BaseDAO();

}
