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.BdPsndocMapper;
import cn.com.countrygarden.bi.main.dao.dataMigration.HiPsndocWorkMapper;
import cn.com.countrygarden.bi.main.model.hi_psndoc_work;
import cn.com.countrygarden.bi.main.service.dataMigration.HiPsndocWorkService;
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.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 HiPsndocWorkServiceImpl implements HiPsndocWorkService {
    protected final org.slf4j.Logger logger = LoggerFactory.getLogger(HiPsndocWorkServiceImpl.class);
    @Autowired
    private BdPsndocMapper psndocMapper;
    @Autowired
    private HiPsndocWorkMapper hiPsndocWorkMapper;

    @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 = hiPsndocWorkMapper.getMaxId();
        return max;
    }

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

    @Override
    // 44 45
    public List<hi_psndoc_work> ncToDup(int pageIndex, int pageSize) {
        JSONObject allReturnInfo = getAllReturnInfo(bdPsndocUrl, pageIndex, pageSize);
        JSONObject data = (JSONObject) allReturnInfo.get("data");
        JSONArray psndoc = data.getJSONArray("work");
        List<hi_psndoc_work> works = new ArrayList<hi_psndoc_work>();
        try {
            if (psndoc != null) {
                for (int i = 0; i < psndoc.size(); i++) {
                    JSONObject jo = (JSONObject) psndoc.getJSONObject(i);
                    hi_psndoc_work hi = new hi_psndoc_work();
                    hi.setBEGINDATE(jo.getString("begindate"));
                    hi.setBG_CHECK(jo.getString("bg_check"));
                    hi.setCERTIFIER(jo.getString("certifier"));
                    hi.setCERTIPHONE(jo.getString("certiphone"));
                    hi.setCREATIONTIME(jo.getString("creationtime"));
                    hi.setCREATOR(jo.getString("creator"));
                    hi.setDIMISSION_REASON(jo.getString("dimission_reason"));
                    hi.setENDDATE(jo.getString("enddate"));
                    hi.setLASTFLAG(jo.getString("lastflag"));
                    hi.setLINKPHONE(jo.getString("linkphone"));
                    hi.setMEMO(jo.getString("memo"));
                    hi.setMODIFIEDTIME(jo.getString("modifiedtime"));
                    hi.setMODIFIER(jo.getString("modifier"));
                    hi.setPK_GROUP(jo.getString("pk_group"));
                    hi.setPK_ORG(jo.getString("pk_org"));
                    hi.setPK_PSNDOC(jo.getString("pk_psndoc"));
                    hi.setPK_PSNDOC_SUB(jo.getString("pk_psndoc_sub"));
                    hi.setPK_PSNJOB(jo.getString("pk_psnjob"));
                    hi.setPK_PSNORG(jo.getString("pk_psnorg"));
                    hi.setRECORDNUM(jo.getString("recordnum"));
                    hi.setTS(jo.getString("ts"));
                    hi.setWORK_ADDR(jo.getString("work_addr"));
                    hi.setWORKACHIVE(jo.getString("workachive"));
                    hi.setWORKCORP(jo.getString("workcorp"));
                    hi.setWORKDEPT(jo.getString("workdept"));
                    hi.setWORKDUTY(jo.getString("workduty"));
                    hi.setWORKJOB(jo.getString("workjob"));
                    hi.setWORKPOST(jo.getString("workpost"));
                    hi.setGLBDEF1(jo.getString("glbdef1"));
                    hi.setGLBDEF2(jo.getString("glbdef2"));
                    hi.setGLBDEF3(jo.getString("glbdef3"));
                    hi.setGLBDEF4(jo.getString("glbdef4"));
                    hi.setGLBDEF5(jo.getString("glbdef5"));
                    hi.setGLBDEF6(jo.getString("glbdef6"));
                    hi.setGLBDEF7(jo.getString("glbdef7"));
                    hi.setGLBDEF8(jo.getString("glbdef8"));
                    hi.setGLBDEF9(jo.getString("glbdef9"));
                    hi.setGLBDEF10(jo.getString("glbdef10"));
                    hi.setGLBDEF11(jo.getString("glbdef11"));
                    hi.setGLBDEF12(jo.getString("glbdef12"));
                    hi.setGLBDEF13(jo.getString("glbdef13"));
                    hi.setGLBDEF14(jo.getString("glbdef14"));
                    hi.setRN(jo.getString("rn"));
                    hi.setDR(jo.getString("dr"));
                    works.add(hi);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("失败页码{},失败原因{}", pageIndex, e.getMessage());
        }
        return works;
    }

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

    String testPost(String urlStr, int pageIndex, int pageSize) {
        String message = null;
        URL url = null;
        OutputStreamWriter out = null;
        try {
            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) {
            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:queryPsnWorkInfo>");
        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:queryPsnWorkInfo>");
        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("queryPsnWorkInfoResponse");
        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() {
        hiPsndocWorkMapper.truncateTable();
    }

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