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.model.bd_psndoc;
import cn.com.countrygarden.bi.main.service.dataMigration.BdPsndocService;
import cn.com.countrygarden.bi.main.service.dataMigration.DispatchRecordService;
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.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by ADMS on 2018/7/17.
 */
@Service
public class BdPsndocServiceImpl implements BdPsndocService {
    protected final org.slf4j.Logger logger = LoggerFactory.getLogger(BdPsndocServiceImpl.class);
    @Autowired
    private BdPsndocMapper psndocMapper;
    @Value("${schedule.url.BdPsndoc}")
    private String bdPsndocUrl;
    @Autowired
    private DispatchRecordService dispatchRecordService;

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

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

    @Override
    public void updateBusnessData(Long startId, Long endId) {
        psndocMapper.updateAll(startId, endId);
    }

    @Override
    public void insertWillAdd(Long startId, Long endId) {
        psndocMapper.insertWillAdd(startId, endId);
    }

    @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 List<bd_psndoc> ncToDup(int pageIndex, int pageSize) {
        List<bd_psndoc> bdPsndocs = new ArrayList<bd_psndoc>();
        try {
            JSONObject allReturnInfo = getAllReturnInfo(bdPsndocUrl, pageIndex, pageSize);
            JSONObject data = (JSONObject) allReturnInfo.get("data");
            JSONArray psndoc = data.getJSONArray("psndoc");
            if (psndoc != null) {
                for (int i = 0; i < psndoc.size(); i++) {
                    JSONObject jo = (JSONObject) psndoc.getJSONObject(i);
                    bd_psndoc bd = new bd_psndoc();
                    bd.setADDR(jo.getString("addr"));
                    bd.setBIRTHDATE(jo.getString("birthdate"));
                    bd.setCODE(jo.getString("code"));
                    bd.setCREATIONTIME(jo.getString("creationtime"));
                    bd.setCREATOR(jo.getString("creator"));
                    bd.setEMAIL(jo.getString("email"));
                    bd.setHOMEPHONE(jo.getString("homephone"));
                    bd.setID(jo.getString("id"));
                    bd.setIDTYPE(jo.getString("idtype")); // todo
                    bd.setISSHOPASSIST(jo.getString("isshopassist"));
                    bd.setJOINWORKDATE(jo.getString("joinworkdate"));
                    bd.setMNECODE(jo.getString("mnecode"));
                    bd.setMOBILE(jo.getString("mobile"));
                    bd.setMODIFIEDTIME(jo.getString("modifiedtime"));
                    bd.setMODIFIER(jo.getString("modifier"));
                    bd.setNAME(jo.getString("name"));
                    bd.setNAME2(jo.getString("name2"));
                    bd.setNAME3(jo.getString("name3"));
                    bd.setNAME4(jo.getString("name4"));
                    bd.setNAME5(jo.getString("name5"));
                    bd.setNAME6(jo.getString("name6"));
                    bd.setOFFICEPHONE(jo.getString("officephone"));
                    bd.setPK_GROUP(jo.getString("pk_group"));
                    bd.setPK_ORG(jo.getString("pk_org"));
                    bd.setPK_PSNDOC(jo.getString("pk_psndoc"));
                    bd.setUSEDNAME(jo.getString("usedname"));
                    bd.setBLOODTYPE(jo.getString("bloodtype"));
                    bd.setCENSUSADDR(jo.getString("censusaddr"));
                    bd.setCHARACTERRPR(jo.getString("characterrpr"));
                    bd.setCOUNTRY(jo.getString("country"));
                    bd.setDIE_DATE(jo.getString("die_date"));
                    bd.setDIE_REMARK(jo.getString("die_remark"));
                    bd.setEDU(jo.getString("edu"));
                    bd.setFAX(jo.getString("fax"));
                    bd.setFILEADDRESS(jo.getString("fileaddress"));
                    bd.setHEALTH(jo.getString("health"));
                    bd.setISHISKEYPSN(jo.getString("ishiskeypsn"));
                    bd.setJOINPOLITYDATE(jo.getString("joinpolitydate"));
                    bd.setMARITAL(jo.getString("marital"));
                    bd.setMARRIAGEDATE(jo.getString("marriagedate"));
                    bd.setNATIONALITY(jo.getString("nationality"));
                    bd.setNATIVEPLACE(jo.getString("nativeplace"));
                    bd.setPENELAUTH(jo.getString("penelauth"));
                    bd.setPERMANRESIDE(jo.getString("permanreside"));
                    bd.setPK_DEGREE(jo.getString("pk_degree"));
                    bd.setPK_HRORG(jo.getString("pk_hrorg"));
                    bd.setPOLITY(jo.getString("polity"));
                    bd.setPOSTALCODE(jo.getString("postalcode"));
                    bd.setPROF(jo.getString("prof"));
                    bd.setRETIREDATE(jo.getString("retiredate"));
                    bd.setSECRET_EMAIL(jo.getString("secret_email"));
                    bd.setSHORTNAME(jo.getString("shortname"));
                    bd.setTITLETECHPOST(jo.getString("titletechpost"));
                    bd.setFIRSTNAME(jo.getString("firstname"));
                    bd.setLASTNAME(jo.getString("lastname"));
                    bd.setISCADRE(jo.getString("iscadre"));
                    bd.setISHISLEADER(jo.getString("ishisleader"));
                    bd.setAGE(jo.getString("age"));
                    bd.setWORKAGE(jo.getString("workage"));
                    bd.setGLBDEF1(jo.getString("glbdef1"));
                    bd.setGLBDEF2(jo.getString("glbdef2"));
                    bd.setGLBDEF3(jo.getString("glbdef3"));
                    bd.setGLBDEF4(jo.getString("glbdef4"));
                    bd.setGLBDEF5(jo.getString("glbdef5"));
                    bd.setGLBDEF6(jo.getString("glbdef6"));
                    bd.setGLBDEF7(jo.getString("glbdef7"));
                    bd.setGLBDEF8(jo.getString("glbdef8"));
                    bd.setGLBDEF9(jo.getString("glbdef9"));
                    bd.setGLBDEF10(jo.getString("glbdef10"));
                    bd.setGLBDEF11(jo.getString("glbdef11"));
                    bd.setGLBDEF12(jo.getString("glbdef12"));
                    bd.setGLBDEF13(jo.getString("glbdef13"));
                    bd.setGLBDEF14(jo.getString("glbdef14"));
                    bd.setGLBDEF15(jo.getString("glbdef15"));
                    bd.setGLBDEF16(jo.getString("glbdef16"));
                    bd.setGLBDEF17(jo.getString("glbdef17"));
                    bd.setGLBDEF18(jo.getString("glbdef18"));
                    bd.setGLBDEF19(jo.getString("glbdef19"));
                    bd.setGLBDEF20(jo.getString("glbdef20"));
                    bd.setGLBDEF21(jo.getString("glbdef21"));
                    bd.setGLBDEF22(jo.getString("glbdef22"));
                    bd.setGLBDEF23(jo.getString("glbdef23"));
                    bd.setGLBDEF24(jo.getString("glbdef24"));
                    bd.setGLBDEF25(jo.getString("glbdef25"));
                    bd.setGLBDEF26(jo.getString("glbdef26"));
                    bd.setGLBDEF27(jo.getString("glbdef27"));
                    bd.setGLBDEF28(jo.getString("glbdef28"));
                    bd.setGLBDEF29(jo.getString("glbdef29"));
                    bd.setGLBDEF30(jo.getString("glbdef30"));
                    bd.setRN(jo.getString("rn"));
                    bd.setDR(jo.getString("dr"));
                    //分布式
                    int dataoriginflag = 0;
                    if (jo.getString("dataoriginflag") != null) {
                        dataoriginflag = Integer.parseInt(jo.getString("dataoriginflag"));
                    }
                    bd.setDATAORIGINFLAG(dataoriginflag);

                    //启用状态
                    int enablestate = 0;
                    if (jo.getString("sex") != null) {
                        enablestate = Integer.parseInt(jo.getString("enablestate"));
                    }
                    bd.setENABLESTATE(enablestate);

                    //性别
                    int sex = 0;
                    if (jo.getString("sex") != null) {
                        sex = Integer.parseInt(jo.getString("sex"));
                    }
                    bd.setSEX(sex);
                    //时间转换
                    Date ts = null;
                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    if (jo.getString("ts") != null) {
                        ts = df.parse(jo.getString("ts"));
                    }
                    bd.setTS(ts);
                    //照片
                   /* byte[] photo = null;
                    String pho = jo.getString("photo");
                    if (pho != null) {
                        photo = pho.getBytes();
                    }*/

                    /*byte[] previewphoto = null;
                    String pre = jo.getString("previewphoto");
                    if (pre != null) {
                        previewphoto = pre.getBytes();
                    }*/
                    //bd.setPHOTO(photo);
                    //bd.setPREVIEWPHOTO(previewphoto);
                    bdPsndocs.add(bd);
                }
            }
        } catch (Exception e){
            logger.error("失败页码{},失败原因{}",pageIndex,e.getMessage());
        }
        return bdPsndocs;
    }

    @Override
    public void insertErrorInfo(Integer tem, String msg) {
        psndocMapper.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("Content-Type", "text/xml");
            out = new OutputStreamWriter(con
                    .getOutputStream(), "UTF-8");
            String xmlInfo = getXmlInfo(pageIndex, pageSize);
            out.write(xmlInfo/*new String(xmlInfo.getBytes("ISO-8859-1"))*/);
            out.flush();
            out.close();
            BufferedReader br = new BufferedReader(new InputStreamReader(con
                    .getInputStream(),"UTF-8"));

            message = br.lines().collect(Collectors.joining());
            message = getPdfInfo(message); // xml
        } 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:queryPsnInfo>");
        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:queryPsnInfo>");
        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("queryPsnInfoResponse");
        Element e = respone.element("return");
        pdInfo= e.getTextTrim();
        return pdInfo;
    }
    @Override
    public void truncateTableBdPsndocBak(){
        psndocMapper.truncateTableBdPsndocBak();
    }
}

