package com.dhcc.finance.main.service.impl;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.dhcc.common.constant.FinanceStatusCode;
import com.dhcc.common.constant.SysConstants;
import com.dhcc.common.constant.SysStatusCode;
import com.dhcc.common.model.CurrencyMeta;
import com.dhcc.common.model.SysUserInfo;
import com.dhcc.common.model.response.RestfulResponse;
import com.dhcc.common.util.CacheDataUtil;
import com.dhcc.common.util.SnowflakeIdWorker;
import com.dhcc.finance.constant.FinanceDictConsts;
import com.dhcc.finance.main.dao.CwNcAdvanceHisMapper;
import com.dhcc.finance.main.dao.CwNcAdvanceMapper;
import com.dhcc.finance.main.domain.CwNcAdvance;
import com.dhcc.finance.main.model.CwNcAdvanceInfo;
import com.dhcc.finance.main.model.CwNcRequestModel;
import com.dhcc.finance.main.service.CwNcAdvanceService;
import com.dhcc.finance.util.MetaDataUtil;

import brave.Tracer;
import lombok.extern.slf4j.Slf4j;
@Service
@Slf4j
public class CwNcAdvanceServiceImpl implements CwNcAdvanceService {
	
	@Autowired
	private CwNcAdvanceMapper cwNcAdvanceMapper;
	
	@Autowired
	private CwNcAdvanceHisMapper cwNcAdvanceHisMapper;
	
	 @Autowired
	 private Tracer tracer;
	 
	 @Autowired
	 private StringRedisTemplate stringRedisTemplate;
	 
	 @Value("${dhcc.nc.pushAdvanceInterface}")
	 private String pushAdvanceInterface;// nc接口
	/**
	 * 功能描述:查询NC垫付款明细列表
	 * @param xtxmbh
	 * @param begindate
	 * @param enddate
	 * @return RestfulResponse<PageInfo<CwNcAdvance>,CurrencyMeta>
	 *@author likai
	 *@data 2020年4月30日上午11:02:41
	 *修改日志
	 */
	@Override
	public RestfulResponse<List<CwNcAdvance>, CurrencyMeta> searchNcAdvance(String param, String begindate,
			String enddate) {
	    List<CwNcRequestModel> cwNcRequestModels = JSONArray.parseArray(param,CwNcRequestModel.class);
	    if (StringUtils.isBlank(cwNcRequestModels.get(0).getBegindate())) {
	        cwNcRequestModels.get(0).setBegindate("1999-01-01");
	    }
	    if (StringUtils.isBlank(cwNcRequestModels.get(0).getEnddate())) {
	        cwNcRequestModels.get(0).setEnddate("9999-12-31");
	    }
	    String params = JSON.toJSON(cwNcRequestModels).toString();
	    log.info(params);
	    int sysint_basews03 = 1000 * 60 * 30;// 接口最大等待时间

        String sysinit_basews01 = pushAdvanceInterface;//接口地址

        StringBuffer strbuf = new StringBuffer();
        String back =null;
        try {
            URL realURL = new URL(sysinit_basews01);
            HttpURLConnection connection = (HttpURLConnection) realURL
                    .openConnection();
//  Logger.debug("连接已开启");
            connection.setConnectTimeout(sysint_basews03);
//  Logger.debug("设置连接时间:" + sysint_basews03);
            connection.setRequestProperty("Content-type", "application/xml;charset=UTF-8");
            connection.setRequestProperty("Accept-Charset", "UTF-8");
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
           
            OutputStream os = connection.getOutputStream();
            
            
            String soap = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:iqu=\"http://itf.gl.nc/IQueryBalanceItf\">\r\n" + 
                    "   <soapenv:Header/>\r\n" + 
                    "   <soapenv:Body>\r\n" + 
                    "      <iqu:queryPrjBalance>\r\n" + 
                    "         <!--Optional:-->\r\n" + 
                    "         <string>"+params+"</string>\r\n" + 
                    "      </iqu:queryPrjBalance>\r\n" + 
                    "   </soapenv:Body>\r\n" + 
                    "</soapenv:Envelope>";
            os.write(soap.getBytes());
            os.close();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"UTF-8"));        
            String line;
            while ((line = in.readLine()) != null) {
                back += line;
            }
            log.info(back); // 响应结果   
            /*InputStream inputStream = connection.getInputStream();
             tempBytes = new byte[inputStream.available()];
            inputStream.read(tempBytes);
            log.info("tempBytes<><>"+new String(tempBytes));
            */
            in.close();
            connection.disconnect();
            System.out.println("<----------------------");
           
        } catch (Exception e) {
            System.out.println("<><><><><><><><><><" + e.getMessage());
        }
		// TODO Auto-generated method stub
		//1.调用nc接口，获取返回值
      //   back = new String(tempBytes);
         int strStartIndex = back.indexOf("<return>")+8;
         int strEndIndex = back.indexOf("</return>");
         String result = back.substring(strStartIndex, strEndIndex);
         log.info("result-----"+result);
         if (!StringUtils.isNoneBlank(result)|| result.length() <=0) {
          // 清空NC垫付款明细表（临时表）
             cwNcAdvanceMapper.truncateNcAdvance();
             return new RestfulResponse<List<CwNcAdvance>, CurrencyMeta>(SysConstants.CODE.SUCCESS,
                     FinanceStatusCode.RES_VALUE_NULL.message(), MetaDataUtil.getMeta(tracer,FinanceStatusCode.RES_VALUE_NULL));
         }
         /*JSONArray jsonArray= JSONArray.parseArray(back);
         log.info("jsonArray-------"+jsonArray);
         JSONObject jSONObject = JSONObject.parseObject(back);
         log.info("jSONObject----------"+jSONObject);*/
		List<CwNcAdvanceInfo> cwNcAdvanceInfos= JSONArray.parseArray(result,CwNcAdvanceInfo.class);
	    List<CwNcAdvance> cwNcAdvances = new ArrayList<CwNcAdvance>();
	    SysUserInfo sysUserInfo = CacheDataUtil.<SysUserInfo>getCacheBean(stringRedisTemplate,
                SysConstants.REDIS_KEY_PREFIX.SYS_USER_INFO, SysUserInfo.class);
	    String user = "";
	    if (sysUserInfo != null) {
	        user = sysUserInfo.getUserId();
	    }
	    Date date = new Date();
	    String batchNo = SnowflakeIdWorker.getInstance().nextIdString(); //获取批次号
	    for(int i =0;i<cwNcAdvanceInfos.size(); i++) {
	    	CwNcAdvance cwNcAdvance = new CwNcAdvance();
	    	
	    	cwNcAdvance.setBatchNo(batchNo);
	    	String id = SnowflakeIdWorker.getInstance().nextIdString(); //获取id
	    	cwNcAdvance.setId(id);
	    	
	    	cwNcAdvance.setProjectId(cwNcAdvanceInfos.get(i).getXtxmbh());
	    	cwNcAdvance.setProjectName(cwNcAdvanceInfos.get(i).getXtxmqc());
	    	cwNcAdvance.setAccountNo(cwNcAdvanceInfos.get(i).getBankc());
	    	cwNcAdvance.setAdvanceAmount(cwNcAdvanceInfos.get(i).getJocc());
	    	cwNcAdvance.setReturnAmount(cwNcAdvanceInfos.get(i).getDocc());
	    	cwNcAdvance.setRemuneration(cwNcAdvanceInfos.get(i).getDocc());
	    	cwNcAdvance.setCreateUser(user);
	    	cwNcAdvance.setUseState(FinanceDictConsts.Syzt.EFFECTIVE);
	    	cwNcAdvance.setUpdateUser(user);
	    	cwNcAdvance.setCreateTime(date);
	    	cwNcAdvance.setUpdateTime(date);
	    	cwNcAdvance.setRemark("");
	    	cwNcAdvances.add(cwNcAdvance);
	    }
	    // 批量新增NC垫付款明细
	    cwNcAdvanceHisMapper.batchInsertNcAdvanceHis();
	    // 清空NC垫付款明细表（临时表）
	    cwNcAdvanceMapper.truncateNcAdvance();
	    // 将从nc接口查出的数据批量新增到NC垫付款明细表（临时表）中
	    int res = cwNcAdvanceMapper.batchInsertNcAdvance(cwNcAdvances);
	    if (res <=0) {
	    	return new RestfulResponse<List<CwNcAdvance>, CurrencyMeta> (SysConstants.CODE.FAIL,
                    SysConstants.DEFAULT_MESSAGE.OPERATION_FAIL, MetaDataUtil.getMeta(tracer,SysStatusCode.OPERATION_SUCCESS));
	    }
	   /* List<CwNcAdvance> ncAdvances =cwNcAdvanceMapper.selectNcAdvance();
	    if (ncAdvances.size() <= 0 || ncAdvances == null ) {
	    	return new RestfulResponse<List<CwNcAdvance>, CurrencyMeta> (SysConstants.CODE.FAIL,
                    SysConstants.DEFAULT_MESSAGE.OPERATION_FAIL, MetaDataUtil.getMeta(tracer,SysStatusCode.OPERATION_SUCCESS));
	    }*/
	    
	    return new RestfulResponse<List<CwNcAdvance>, CurrencyMeta>(SysConstants.CODE.SUCCESS,
                SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS, MetaDataUtil.getMeta(tracer,SysStatusCode.OPERATION_SUCCESS));
	}

}
