package nc.bs.tianwen.wuye;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.exception.ExceptionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import nc.bs.framework.common.NCLocator;
import nc.itf.uap.IUAPQueryBS;
import nc.net.servlet.IReturnStatus;
import nc.net.servlet.SapToNcEsbJsonServlet;
import nc.util.uap.twxt.WYTwxtUtil;
import nc.vo.arap.receivable.ReceivableBillVO;
import nc.vo.esb.BillExistResultInfo;
import nc.vo.esb.BillExistResultVO;
import nc.vo.pub.BusinessException;
import nc.vo.tmpub.util.SqlUtil;
import nc.vo.twxt.log.WYTwxtLogVO;

/**
 * 
 * @author guojx
 * @Date 20220712
 * @see 中台单据查询接口
 */
public class TWCheckBillExistServlet extends SapToNcEsbJsonServlet {

	BillExistResultInfo<BillExistResultVO> resultInfoVO = new BillExistResultInfo<BillExistResultVO>();
	BillExistResultVO resultvo = new BillExistResultVO();
	JSONObject jsonobj = null;
	List<String> ids = null;

	private Collection<ReceivableBillVO> handleCheckExist(List<String> ids) throws BusinessException {
		return NCLocator.getInstance().lookup(IUAPQueryBS.class).retrieveByClause(ReceivableBillVO.class,
				SqlUtil.buildSqlForIn("def1", ids.toArray(new String[0])));
	}

	private void handleOutlook(Collection<ReceivableBillVO> vos, List<String> ids) throws Exception {
		Long[] exist = vos.stream().map(ReceivableBillVO::getDef1).map(Long::valueOf).collect(Collectors.toList())
				.toArray(new Long[0]);
		resultvo.setIds(exist);
		resultvo.setMessage("查询成功");
		resultvo.setCode(IReturnStatus.SUCCEED);
		resultvo.setError(null);
		resultInfoVO.setResultInfo(resultvo);
	}

	private List<String> handleIds(JSONArray array) {
		List<String> ids = (List<String>) array.toJavaList(Object.class).stream().map(item -> {
			if (item == null || "null".equals(item)) {
				return null;
			} else {
				return item.toString();
			}
		}).distinct().collect(Collectors.toList());
		ids.removeAll(Collections.singleton(null));
		return ids;
	}

	@Override
	public void execFunction(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		try {
			jsonobj = this.findPostJsonValue(request);
			JSONArray array = jsonobj.getJSONArray("ids");
			ids = this.handleIds(array);
			Collection<ReceivableBillVO> vos = this.handleCheckExist(ids);
			this.handleOutlook(vos, ids);
		} catch (Exception e) {
			resultvo.setIds(null);
			resultvo.setMessage("查询失败 ");
			resultvo.setCode(IReturnStatus.ERROR);
			resultvo.setError(ExceptionUtils.getFullStackTrace(e));
			resultInfoVO.setResultInfo(resultvo);
		} finally {
			sendResponse(response, com.alibaba.fastjson.JSONObject.toJSONString(resultInfoVO));
			WYTwxtLogVO logVO = new WYTwxtLogVO();
			logVO.setNc_id("ids:" + ids.toString());
			logVO.setBillno("");
			logVO.setTranstypecode("checkbillexist");
			logVO.setItfcode("Boss-NCC-checkbillexist");
			logVO.setItfname("【物业boss接口】中台应收单查询接口");
			logVO.setBilldata(jsonobj == null ? "" : jsonobj.toString());
			logVO.setRsdata(com.alibaba.fastjson.JSONObject.toJSONString(resultInfoVO));
			logVO.setMsg(null);
			logVO.setIssuccess(IReturnStatus.SUCCEED.equals(resultvo.getCode()) ? "Y" : "N");
			WYTwxtUtil.getIWuYeTwxtLogService().insertLog_RequiresNew(logVO);
		}
	}

	public void sendResponse(final HttpServletResponse response, String responseMsg) {
		PrintWriter out = null;
		try {
			response.setHeader("Content-type", "application/json;charset=UTF-8");
			out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
			out.write(responseMsg);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

	private JSONObject findPostJsonValue(final HttpServletRequest request) throws Exception {
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream(), "utf-8"));
			StringBuffer sb = new StringBuffer();
			String temp = null;
			while ((temp = br.readLine()) != null) {
				sb.append(temp);
			}
			return JSON.parseObject(sb.toString());
		} catch (Exception e) {
			throw e;
		} finally {
			try {
				if (br != null)
					br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
