package cn.com.countrygarden.bi.main.service.dataMigration.impl;

import cn.com.countrygarden.bi.main.constant.dataMigration.ParamConstant;
import cn.com.countrygarden.bi.main.dao.dataMigration.HiPsndocTrainMapper;
import cn.com.countrygarden.bi.main.model.hi_psndoc_train;
import cn.com.countrygarden.bi.main.service.dataMigration.HiPsndocTrainService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by ADMS on 2018/7/17.
 */
@Service
public class HiPsndocTrainServiceImpl implements HiPsndocTrainService {
    protected final org.slf4j.Logger logger = LoggerFactory.getLogger(HiPsndocTrainServiceImpl.class);
    @Autowired
    private HiPsndocTrainMapper hiPsndocTrainMapper;
    @Value("${schedule.url.BdPsndoc}")
    private String bdPsndocUrl;

    public JSONObject getAllReturnInfo(String url, int pageIndex, int pageSize){
        String allInfo = testPost(url, pageIndex, pageSize);
        JSONObject jsonAllInfo = JSON.parseObject(allInfo);
        return jsonAllInfo;
    }

    @Override
    public int getTotal() {
        JSONObject allReturnInfo = getAllReturnInfo(bdPsndocUrl, 1, 1);
        String totalStr = allReturnInfo.getString("total");
        int i = Integer.parseInt(totalStr);
        return i;
    }

    @Override
    public Long getTableMaxId() {
        Long max = hiPsndocTrainMapper.getMaxId();
        return max;
    }

    @Override
    public Long getTableMinId() {
        Long min = hiPsndocTrainMapper.getMinId();
        return min;
    }

    @Override
    // 52 个字段 53
    public List<hi_psndoc_train> ncToDup(int pageIndex, int pageSize) {
        List<hi_psndoc_train> hiPsndocTrains = new ArrayList<>();
        try {
            JSONObject allReturnInfo = getAllReturnInfo(bdPsndocUrl, pageIndex, pageSize);
            JSONObject data = (JSONObject) allReturnInfo.get("data");
            JSONArray trains = data.getJSONArray("train");
            if (trains != null) {
                for (int i = 0; i < trains.size(); i++) {
                    JSONObject jo = (JSONObject)trains.getJSONObject(i);
                    hi_psndoc_train hit=new hi_psndoc_train();
                    hit.setASS_OPTION(jo.getString("ass_option"));
                    hit.setASS_RESULT(jo.getString("ass_result"));
                    hit.setASSIST_UNIT(jo.getString("assist_unit"));
                    hit.setBEGINDATE(jo.getString("begindate"));
                    hit.setCERTIFICATE_DATE(jo.getString("certificate_date"));
                    hit.setCERTIFICATE_UNIT(jo.getString("certificate_unit"));
                    hit.setCONTCODE(jo.getString("contcode"));
                    hit.setCREATIONTIME(jo.getString("creationtime"));
                    hit.setCREATOR(jo.getString("creator"));
                    hit.setENDDATE(jo.getString("enddate"));
                    hit.setENTREPRENEUR(jo.getString("entrepreneur"));
                    hit.setISALLDUTY(jo.getString("isallduty"));
                    hit.setLASTFLAG(jo.getString("lastflag"));
                    hit.setMEMO(jo.getString("memo"));
                    hit.setMODIFIEDTIME(jo.getString("modifiedtime"));
                    hit.setMODIFIER(jo.getString("modifier"));
                    hit.setPK_ACT(jo.getString("pk_act"));
                    hit.setPK_GROUP(jo.getString("pk_group"));
                    hit.setPK_ORG(jo.getString("pk_org"));
                    hit.setPK_PSNDOC(jo.getString("pk_psndoc"));
                    hit.setPK_PSNDOC_SUB(jo.getString("pk_psndoc_sub"));
                    hit.setPK_PSNJOB(jo.getString("pk_psnjob"));
                    hit.setPK_PSNORG(jo.getString("pk_psnorg"));
                    hit.setPURVEYOR(jo.getString("purveyor"));
                    hit.setRECORDNUM(jo.getString("recordnum"));
                    hit.setSIGNON_DT(jo.getString("signon_dt"));
                    hit.setTRA_MODE(jo.getString("tra_mode"));
                    hit.setTRA_RESULT(jo.getString("tra_result"));
                    hit.setTRA_TIME(jo.getString("tra_time"));
                    hit.setTRA_TYPE(jo.getString("tra_type"));
                    hit.setTRAIM(jo.getString("traim"));
                    hit.setTRM_CERTIF_CODE(jo.getString("trm_certif_code"));
                    hit.setTRM_CERTIF_NAME(jo.getString("trm_certif_name"));
                    hit.setTRM_LOCATION(jo.getString("trm_location"));
                    hit.setTS(jo.getString("ts"));
                    hit.setGLBDEF2(jo.getString("glbdef2"));
                    hit.setGLBDEF3(jo.getString("glbdef3"));
                    hit.setGLBDEF4(jo.getString("glbdef4"));
                    hit.setRN(jo.getString("rn"));
                    hit.setTRA_CONTENT(jo.getString("tra_content"));
                    hit.setTRA_COST(jo.getString("tra_cost"));
                    hit.setABSENCE_COUNT(jo.getString("absence_count"));
                    hit.setACT_CODE(jo.getString("act_code"));
                    hit.setACT_NAME(jo.getString("act_name"));
                    hit.setACT_NAME2(jo.getString("act_name2"));
                    hit.setACT_NAME3(jo.getString("act_name3"));
                    hit.setACT_NAME4(jo.getString("act_name4"));
                    hit.setACT_NAME5(jo.getString("act_name5"));
                    hit.setACT_NAME6(jo.getString("act_name6"));
                    hit.setDR(jo.getString("dr"));

                    int taketrm_method=0;
                    if(jo.getString("taketrm_method")!=null){
                        taketrm_method=Integer.parseInt(jo.getString("taketrm_method"));
                    }
                    hit.setTAKETRM_METHOD(taketrm_method);

                    int source_type=0;
                    if(jo.getString("source_type")!=null) {
                        source_type=Integer.parseInt(jo.getString("source_type"));
                    }
                    hit.setSOURCE_TYPE(source_type);

                    int glbdef1=0;
                    if(jo.getString("glbdef1")!=null) {
                        glbdef1=Integer.parseInt(jo.getString("glbdef1"));
                    }
                    hit.setGLBDEF1(glbdef1);
                    hiPsndocTrains.add(hit);
                }
            }
        } catch (Exception e){
            e.printStackTrace();
            logger.error("失败页码{},失败原因{}",pageIndex,e.getMessage());
        }
        return hiPsndocTrains;
    }

    @Override
    public void insertErrorInfo(Integer tem, String msg) {
        hiPsndocTrainMapper.insertErrorInfo(tem, msg);
    }

    String testPost(String urlStr, int pageIndex, int pageSize) {
        String message = null;
        OutputStreamWriter out = null;
        try {
            URL url = new URL(urlStr);
            URLConnection con = url.openConnection();
            con.setDoOutput(true);
//            con.setRequestProperty("Pragma:", "no-cache");
//            con.setRequestProperty("Cache-Control", "no-cache");
            con.setRequestProperty("Content-Type", "text/xml");
            //con.readdHeader("Accept", "application/json");
            out = new OutputStreamWriter(con
                    .getOutputStream(), "UTF-8");
            String xmlInfo = getXmlInfo(pageIndex, pageSize);
            out.write(xmlInfo/*new String(xmlInfo.getBytes("ISO-8859-1"))*/);
            out.flush();
            BufferedReader br = new BufferedReader(new InputStreamReader(con
                    .getInputStream(),"UTF-8"));

            message = br.lines().collect(Collectors.joining());
            //message.getBytes("ISO-8859-1");
            //message = new String(message.getBytes("UTF-8"));
            message = getPdfInfo(message); // xml
           /* String line = "";
            for (line = br.readLine(); line != null; line = br.readLine()) {
                System.out.println("================>" + line);
            }*/
        } catch (Exception e) {
            logger.error("失败页码{},失败原因post{}", pageIndex, e.getMessage());
            e.printStackTrace();
        }  finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return message;
    }

    /**
     * 请求参数内容
     * @param pageIndex
     * @param pageSize
     * @return
     */
    private String getXmlInfo(int pageIndex, int pageSize) {
        StringBuilder sb = new StringBuilder();
        sb.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:pm=\"http://www.getpostman.com/\">");
        sb.append(" <soapenv:Header></soapenv:Header>");
        sb.append("  <soapenv:Body>");
        sb.append(" <pm:queryPsnTrainInfo>");
        sb.append("   <").append(ParamConstant.PARAM1).append(">").append(pageIndex).append("</").append(ParamConstant.PARAM1).append(">");
        sb.append("   <").append(ParamConstant.PARAM2).append(">").append(pageSize).append("</").append(ParamConstant.PARAM2).append(">");
        sb.append(" </pm:queryPsnTrainInfo>");
        sb.append(" </soapenv:Body>");
        sb.append("</soapenv:Envelope>");
        return sb.toString();
    }

    private String getPdfInfo(String requestInfo) throws ParserConfigurationException, DocumentException {
        String pdInfo = null;
        // 将文件保存到指定目录下
           /* String savePath = "D:/request.xml";
            FileWriter fw = new FileWriter(savePath);
            fw.write(requestInfo);
            fw.flush();
            fw.close();*/
        // 获取指定节点的内容
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        DocumentBuilder builder = factory.newDocumentBuilder();
        //Document doc = builder.parse(new File(savePath));
        Document doc = DocumentHelper.parseText(requestInfo);
        Element root = doc.getRootElement();
        Element body = root.element("Body");
        Element respone = body.element("queryPsnTrainInfoResponse");
        Element e = respone.element("return");
        pdInfo= e.getTextTrim();
        return pdInfo;
    }

    @Override
    public boolean verifyData(Long startId, Long endId, int totalStandard) {
        // 空校验
        if (startId == null || endId == null){
            return false;
        }
        // 数量校验
        long totalRel = endId - startId;
        if (totalRel < totalStandard) {
            return false;
        }
        return true;
    }

    @Override
    public void truncateTable() {
        hiPsndocTrainMapper.truncateTable();
    }

    @Override
    public void midToBusness(Long startId, Long endId) {
        hiPsndocTrainMapper.midToBusness(startId, endId);
    }
}