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.HiPsnJobMapper;
import cn.com.countrygarden.bi.main.model.dataMigration.HiPsnjob;
import cn.com.countrygarden.bi.main.service.dataMigration.HiPsnJobService;
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;

/**
 * queryPsnJobInfo
 */
@Service
public class HiPsnJobServiceImpl implements HiPsnJobService {
    protected final org.slf4j.Logger logger = LoggerFactory.getLogger(HiPsnJobServiceImpl.class);
    @Autowired
    private HiPsnJobMapper hiPsnJobMapper;
    
    @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 = hiPsnJobMapper.getMaxId();
        return max;
    }

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

    @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() {
        hiPsnJobMapper.truncateTable();
    }

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

    @Override
    public List<HiPsnjob> ncToDup(int pageIndex, int pageSize) {
        List<HiPsnjob> bdPsndocs = new ArrayList<>();
        try {
            JSONObject allReturnInfo = getAllReturnInfo(bdPsndocUrl, pageIndex, pageSize);
            JSONObject data = (JSONObject) allReturnInfo.get("data");
            JSONArray psnjobs = data.getJSONArray("psnjob");
            if (psnjobs != null) {
                for (int i = 0; i < psnjobs.size(); i++) {
                    JSONObject jo = (JSONObject)psnjobs.getJSONObject(i);
                    HiPsnjob hij=new HiPsnjob();
                    hij.setWORKTYPE(jo.getString("worktype"));
                    hij.setPK_JOBGRADE(jo.getString("pk_jobgrade"));
                    hij.setJOBMODE(jo.getString("jobmode"));
                    hij.setMEMO(jo.getString("memo"));
                    hij.setORIBILLTYPE(jo.getString("oribilltype"));
                    hij.setDR(jo.getString("dr"));
                    hij.setORIBILLPK(jo.getString("oribillpk"));
                    hij.setOCCUPATION(jo.getString("occupation"));
                    hij.setLASTFLAG(jo.getString("lastflag"));
                    hij.setPK_DEPT(jo.getString("pk_dept"));
                    hij.setJOBGLBDEF1(jo.getString("jobglbdef1"));
                    hij.setJOBGLBDEF2(jo.getString("jobglbdef2"));
                    hij.setJOBGLBDEF4(jo.getString("jobglbdef4"));
                    hij.setJOBGLBDEF5(jo.getString("jobglbdef5"));
                    hij.setRECORDNUM(jo.getString("recordnum"));
                    hij.setMODIFIEDTIME(jo.getString("modifiedtime"));
                    hij.setPK_ORG(jo.getString("pk_org"));
                    hij.setASSGID(jo.getString("assgid"));
                    hij.setCREATIONTIME(jo.getString("creationtime"));
                    hij.setCREATOR(jo.getString("creator"));
                    hij.setPK_PSNCL(jo.getString("pk_psncl"));
                    hij.setPK_GROUP(jo.getString("pk_group"));
                    hij.setRN(jo.getString("rn"));
                    hij.setCLERKCODE(jo.getString("clerkcode"));
                    hij.setENDFLAG(jo.getString("endflag"));
                    hij.setTRNSREASON(jo.getString("trnsreason"));
                    hij.setPK_PSNDOC(jo.getString("pk_psndoc"));
                    hij.setPK_HRORG(jo.getString("pk_hrorg"));
                    hij.setPK_PSNJOB(jo.getString("pk_psnjob"));
                    hij.setMODIFIER(jo.getString("modifier"));
                    hij.setBEGINDATE(jo.getString("begindate"));
                    hij.setPK_POSTSERIES(jo.getString("pk_postseries"));
                    hij.setPK_POST(jo.getString("pk_post"));
                    hij.setSHOWORDER( jo.getString("showorder"));
                    hij.setPK_HRGROUP(jo.getString("pk_hrgroup"));
                    hij.setPOSTSTAT(jo.getString("poststat"));
                    hij.setTRIAL_FLAG(jo.getString("trial_flag"));
                    hij.setTRIAL_TYPE(jo.getString("trial_type"));
                    hij.setISMAINJOB(jo.getString("ismainjob"));
                    hij.setPK_PSNORG(jo.getString("pk_psnorg"));
                    hij.setTRNSTYPE(jo.getString("trnstype"));
                    hij.setTS(jo.getString("ts"));
                    hij.setPK_DEPT_V(jo.getString("pk_dept_v"));
                    hij.setPK_JOB(jo.getString("pk_job"));
                    hij.setPK_JOB_TYPE(jo.getString("pk_job_type"));
                    hij.setPK_JOBRANK(jo.getString("pk_jobrank"));
                    hij.setSERIES(jo.getString("series"));
                    hij.setJOBGLBDEF3(jo.getString("jobglbdef3"));
                    hij.setJOBGLBDEF6(jo.getString("jobglbdef6"));
                    hij.setPK_ORG_V(jo.getString("pk_org_v"));
                    hij.setJOBGLBDEF8(jo.getString("jobglbdef8"));
                    hij.setJOBGLBDEF9(jo.getString("jobglbdef9"));
                    hij.setJOBGLBDEF7(jo.getString("jobglbdef7"));
                    hij.setJOBGLBDEF10(jo.getString("jobglbdef10"));
                    hij.setJOBGLBDEF11(jo.getString("jobglbdef11"));
                    hij.setDEPOSEMODE(jo.getString("deposemode"));
                    hij.setENDDATE(jo.getString("enddate"));
                    hij.setIndocflag(jo.getString("indocflag"));

                    int dataoriginflag=0;
                    if(jo.getString("dataoriginflag")!=null){
                        dataoriginflag =Integer.parseInt(jo.getString("dataoriginflag"));
                    }
                    hij.setDATAORIGINFLAG(dataoriginflag);

                    int trnsevent=0;
                    if(jo.getString("trnsevent")!=null) {
                        trnsevent=Integer.parseInt(jo.getString("trnsevent"));
                    }
                    hij.setTRNSEVENT(trnsevent);

                    int psntype=0;
                    if(jo.getString("psntype")!=null){
                        psntype=Integer.parseInt(jo.getString("psntype"));
                    }
                    hij.setPSNTYPE(psntype);
                    bdPsndocs.add(hij);
                }
            }
        } catch (Exception e){
            logger.error("失败页码{},失败原因{}",   pageIndex,  e.getMessage());
        }
        return bdPsndocs;
    }

    @Override
    public void insertErrorInfo(Integer tem, String msg) {
        hiPsnJobMapper.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:queryPsnJobInfo>");
        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:queryPsnJobInfo>");
        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();

        //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("queryPsnJobInfoResponse");
        Element e = respone.element("return");
        pdInfo= e.getTextTrim();
        return pdInfo;
    }

    /**
     * 清空中间表数据
     * @author ferren
     * @date 2019/7/3 15:01
     * @param
     * @return void
     */
    @Override
    public void truncateTableHiPsnjobBak(){
        hiPsnJobMapper.truncateTableHiPsnjobBak();
    }
}

