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.BdTypeMapper;
import cn.com.countrygarden.bi.main.model.dataMigration.BdType;
import cn.com.countrygarden.bi.main.service.dataMigration.BdTypeService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
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 BdTypeServiceImpl implements BdTypeService {
    protected final org.slf4j.Logger logger = LoggerFactory.getLogger(BdTypeServiceImpl.class);
    @Autowired
    private BdTypeMapper bdTypeMapper;
    
    @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 = bdTypeMapper.getMaxId();
        return max;
    }

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

    @Override
    public List<BdType> ncToDup(int pageIndex, int pageSize) {
        List<BdType> bdTypes = new ArrayList<>();
        try {
            JSONObject allReturnInfo = getAllReturnInfo(bdPsndocUrl, pageIndex, pageSize);
            JSONObject data = (JSONObject) allReturnInfo.get("data");
            JSONArray psnjobs = data.getJSONArray("org");
            if (psnjobs != null) {
                for (int i = 0; i < psnjobs.size(); i++) {
                    JSONObject jo = (JSONObject)psnjobs.getJSONObject(i);
                    BdType bdType = new BdType();

                    //modify 2019/4/17 Li.ning
                    //因NC组织结构修改调整，物业服务公司部分组织单位上移，为不影响现有功能(去fuor_tissue)，上移部分手动下移
                    //解决：判断是否为物业服务公司并且five是否有值：无值：从one开始取值，有值：从two开始取
                    String three = jo.getString("three");
                    if("301".equals(three) && StringUtils.isBlank(jo.getString("six"))){
                        bdType.setOne(jo.getString("one"));
                        bdType.setPkGroup(jo.getString("pk_group"));
                        bdType.setTwo(jo.getString("two"));
                        bdType.setTwoTissue(jo.getString("two_tissue"));
                        bdType.setThree(jo.getString("three"));
                        bdType.setThreeTissue (jo.getString("three_tissue"));
                        bdType.setFour(jo.getString("four"));
                        bdType.setFourTissue(jo.getString("four_tissue"));
                        bdType.setFive(jo.getString("five"));
                        bdType.setPkOrg(jo.getString("five_tissue"));
                        bdType.setOneBranch(jo.getString("one_branch"));
                        bdType.setPkDept(jo.getString("pk_dept"));
                        bdType.setTwoBranch(jo.getString("two_branch"));
                        bdType.setTwoName(jo.getString("two_name"));
                        bdType.setThreeBranch(jo.getString("three_branch"));
                        bdType.setThreeName(jo.getString("three_name"));
                        bdType.setFourBranch(jo.getString("four_branch"));
                        bdType.setFourName(jo.getString("four_name"));
                    }else {
                        bdType.setOne(jo.getString("two"));
                        bdType.setPkGroup(jo.getString("two_tissue"));
                        bdType.setTwo(jo.getString("three"));
                        bdType.setTwoTissue(jo.getString("three_tissue"));
                        bdType.setThree(jo.getString("four"));
                        bdType.setThreeTissue(jo.getString("four_tissue"));
                        bdType.setFour(jo.getString("five"));
                        bdType.setFourTissue(jo.getString("five_tissue"));
                        bdType.setFive(jo.getString("six"));
                        bdType.setPkOrg(jo.getString("pk_org"));
                        bdType.setOneBranch(jo.getString("one_branch"));
                        bdType.setPkDept(jo.getString("pk_dept"));
                        bdType.setTwoBranch(jo.getString("two_branch"));
                        bdType.setTwoName(jo.getString("two_name"));
                        bdType.setThreeBranch(jo.getString("three_branch"));
                        bdType.setThreeName(jo.getString("three_name"));
                        bdType.setFourBranch(jo.getString("four_branch"));
                        bdType.setFourName(jo.getString("four_name"));
                    }
                    bdTypes.add(bdType);
                }
            }
        } catch (Exception e){
            logger.error("失败页码{},失败原因{}",pageIndex,e.getMessage());
            e.printStackTrace();
        }
        return bdTypes;
    }

    @Override
    public void insertErrorInfo(Integer tem, String msg) {
        bdTypeMapper.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();
            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:queryOrgDeptInfo>");
        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:queryOrgDeptInfo>");
        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("queryOrgDeptInfoResponse");
        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() {
        bdTypeMapper.truncateTable();
    }

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

    @Override
    public void truncateMidTable() {
        bdTypeMapper.truncateTableBdTypeBak();
    }

}