package cn.gtmap.estateplat.config.service.impl;

import cn.gtmap.estateplat.core.support.mybatis.mapper.EntityMapper;
import cn.gtmap.estateplat.core.support.mybatis.mapper.Example;
import cn.gtmap.estateplat.model.server.core.*;
import cn.gtmap.estateplat.config.core.service.*;
import cn.gtmap.estateplat.config.service.ArchivePostService;
import cn.gtmap.estateplat.config.utils.ArchiveModel;
import cn.gtmap.estateplat.config.utils.Constants;
import cn.gtmap.estateplat.config.utils.PlatformUtil;
import cn.gtmap.estateplat.utils.Charsets;
import com.google.common.collect.Lists;
import com.gtis.common.util.UUIDGenerator;
import com.gtis.config.AppConfig;
import com.gtis.fileCenter.service.NodeService;
import com.gtis.web.SessionUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * .
 * <p/>
 *
 * @author <a href="mailto:zhaodongdong@gtmap.cn">zdd</a>
 * @version V1.0, 15-4-25
 */
@Service
public class ArchivePostServiceImpl implements ArchivePostService {
    @Autowired
    NodeService nodeService;

    @Autowired
    QllxService qllxService;

    @Autowired
    BdcZsService bdcZsService;
    @Autowired
    BdcdyService bdcdyService;
    @Autowired
    BdcQlrService bdcQlrService;
    @Autowired
    BdcZdGlService bdcZdGlService;
    @Autowired
    BdcGdxxService bdcGdxxService;
    @Autowired
    BdcSpxxService bdcSpxxService;
    @Autowired
    EntityMapper entityMapper;
    @Autowired
    private HttpClient httpClient;

    @Autowired
    private PlatformUtil platformUtil;

    @Autowired
    private BdcSjclService bdcSjclService;


    @Override
    public BdcGdxx postBdcXmInfo(BdcXm bdcXm) {
        String userName = SessionUtil.getCurrentUser() != null ? SessionUtil.getCurrentUser().getUsername() : "";
        return postBdcXmInfo(bdcXm, userName);
    }

    /**
     * 将不动产登记项目信息归档到档案系统，主要用于没用用户信息的自动归档
     *
     * @param bdcXm    不动产登记项目信息
     * @param userName 归档人
     * @return BdcGdxx 归档信息
     */
    @Override
    public BdcGdxx postBdcXmInfo(BdcXm bdcXm, String userName) {
        String archiveUrl = AppConfig.getProperty("archive.url");
        String xml = "";
        Document document = null;
        BdcGdxx bdcGdxx = null;
        if (bdcXm != null && StringUtils.isNotBlank(bdcXm.getProid())) {
            String wfProid = platformUtil.getPfProidByWiid(bdcXm.getWiid());
            String proid = bdcXm.getProid();

            //zdd 处理项目权利以及证书信息
            QllxVo qllxVo = qllxService.makeSureQllx(bdcXm);
            qllxVo = qllxService.queryQllxVo(qllxVo, bdcXm.getProid());
            List<BdcZs> bdcZsList = bdcZsService.queryBdcZsByProid(proid);
            BdcSpxx bdcSpxx = bdcSpxxService.getBdcSpxxByProid(proid);
            /**
             * @author bianwen
             * @description 将spxx表中的代码转换为名称
             */
//            if (bdcSpxx != null){
//                bdcSpxx=bdcZdGlService.changeDmToMc(bdcSpxx);
//            }

            List<BdcQlr> bdcQlrList = bdcQlrService.queryBdcQlrByProid(proid);

            //zdd  根据权利类型找到对应的档案业务名称
            List<BdcZdQllx> bdcZdQllxList = bdcZdGlService.getBdcZdQllxList();
            String archiveName = "";
            if (bdcZdQllxList != null && bdcZdQllxList.size() > 0) {
                for (BdcZdQllx bdcZdQllx : bdcZdQllxList) {
                    if (bdcZdQllx.getDm().equals(bdcXm.getQllx())) {
                        archiveName = bdcZdQllx.getArchiveName();
                    }
                }
            }
            if (StringUtils.isNotBlank(archiveName)) {
                String mlh = "";
                String zslx = "zs";
                if (CollectionUtils.isNotEmpty(bdcZsList)) {
                    if (StringUtils.equals(bdcZsList.get(0).getZstype(), Constants.BDCQZM_BH_FONT)) {
                        zslx = "zms";
                    }
                }
                Example example = new Example(BdcXtDamlh.class);
                example.createCriteria().andEqualTo("zslx", zslx).andEqualTo("bdclx", bdcXm.getBdclx());
                List<BdcXtDamlh> bdcXtDamlhList = entityMapper.selectByExample(BdcXtDamlh.class, example);
                if (CollectionUtils.isNotEmpty(bdcXtDamlhList)) {
                    mlh = bdcXtDamlhList.get(0).getMlh();
                }
                List<BdcSjcl> bdcSjclList = bdcSjclService.getBdcSjclByproid(bdcXm.getProid());
                /**
                 * @author bianwen
                 * @description bdcxm表中的qllx转换为名称
                 */

                if (StringUtils.isNotBlank(bdcXm.getQllx())) {
                    BdcZdQllx bdcZdQllx = bdcZdGlService.getBdcZdQllxByDm(bdcXm.getQllx());
                    if (StringUtils.isNotBlank(bdcZdQllx.getMc())) {
                        bdcXm.setQllx(bdcZdQllx.getMc());
                    }
                }

                document = ArchiveModel.createFwbdcXml(document, nodeService, bdcXm, qllxVo, bdcSpxx, bdcQlrList, bdcZsList, archiveName, mlh, bdcSjclList, wfProid);
                xml = document.asXML();

                bdcGdxx = bdcGdxxService.selectBdcGdxx(bdcXm);

                String gdInterface = archiveUrl + "/gateway.action";
                String gdUpdateInterface = archiveUrl + "/gateway!update.action";
                String gdOutInterface = archiveUrl + "/gateway!out.action";
                if (StringUtils.isNotEmpty(xml)) {
                    CloseableHttpClient closeableHttpClient;
                    CloseableHttpResponse closeableHttpResponse = null;
                    if (bdcGdxx == null || (bdcGdxx != null && StringUtils.isBlank(bdcGdxx.getDaid()))) {
                        try {
                            bdcGdxx = new BdcGdxx();
                            bdcGdxx.setGdxxid(UUIDGenerator.generate18());
                            bdcGdxx.setXmid(bdcXm.getProid());
                            bdcGdxx.setGdrq(new Date());
                            bdcGdxx.setGdr(userName);

                            closeableHttpClient = (CloseableHttpClient) httpClient;
                            HttpPost httpPost = new HttpPost(gdInterface);
                            List<NameValuePair> params = Lists.newArrayList();
                            params.add(new BasicNameValuePair("data", xml));
                            httpPost.setEntity(new UrlEncodedFormEntity(params, Charsets.CHARSET_UTF8));
                            closeableHttpResponse = closeableHttpClient.execute(httpPost);
                            if (closeableHttpResponse.getStatusLine().getStatusCode() == 200) {
                                String responseXml = EntityUtils.toString(closeableHttpResponse.getEntity());
                                if (StringUtils.isNotBlank(responseXml)) {
                                    bdcGdxx = bdcGdxxService.initBdcGdxx(bdcGdxx, responseXml);
                                }
                            }

                            bdcGdxxService.insertBdcGdxx(bdcGdxx);
                        } catch (SocketTimeoutException eTimeOut) {
                            eTimeOut.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            if (closeableHttpResponse != null) {
                                try {
                                    closeableHttpResponse.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    } else {
                        closeableHttpClient = (CloseableHttpClient) httpClient;
                        HttpPost httpPost = new HttpPost(gdUpdateInterface);
                        List<NameValuePair> params = Lists.newArrayList();
                        params.add(new BasicNameValuePair("data", xml));
                        httpPost.setEntity(new UrlEncodedFormEntity(params, Charsets.CHARSET_UTF8));
                        try {
                            closeableHttpResponse = closeableHttpClient.execute(httpPost);
                        } catch (IOException e) {
                            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                        }
                        if (closeableHttpResponse.getStatusLine().getStatusCode() == 200) {
                            try {
                                String responseXml = EntityUtils.toString(closeableHttpResponse.getEntity());
                            } catch (IOException e) {
                                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                            }
                        }
                    }
                }
            }
        }
        return bdcGdxx;
    }

    /**
     * @param
     * @return
     * @author bianwen
     * @description 批量归档
     */
    @Override
    public List<BdcGdxx> postPlBdcXmInfo(List<BdcXm> bdcXmList, String userName) {
        Document document = null;
        String wfProid = platformUtil.getPfProidByWiid(bdcXmList.get(0).getWiid());
        for (int i = 0; i < bdcXmList.size(); i++) {
            BdcXm bdcXm = bdcXmList.get(i);
            if (bdcXm != null && StringUtils.isNotBlank(bdcXm.getProid())) {
                String proid = bdcXm.getProid();

                //zdd 处理项目权利以及证书信息
                QllxVo qllxVo = qllxService.makeSureQllx(bdcXm);
                qllxVo = qllxService.queryQllxVo(qllxVo, bdcXm.getProid());
                List<BdcZs> bdcZsList = bdcZsService.queryBdcZsByProid(proid);
                BdcSpxx bdcSpxx = bdcSpxxService.getBdcSpxxByProid(proid);
//                /**
//                 * @author bianwen
//                 * @description  将spxx表中的代码转换为名称
//                 */
//                if (bdcSpxx != null){
//                    bdcSpxx=bdcZdGlService.changeDmToMc(bdcSpxx);
//                }
                List<BdcQlr> bdcQlrList = bdcQlrService.queryBdcQlrByProid(proid);

                //zdd  根据权利类型找到对应的档案业务名称
                List<BdcZdQllx> bdcZdQllxList = bdcZdGlService.getBdcZdQllxList();
                String archiveName = "";
                if (bdcZdQllxList != null && bdcZdQllxList.size() > 0) {
                    for (BdcZdQllx bdcZdQllx : bdcZdQllxList) {
                        if (bdcZdQllx.getDm().equals(bdcXm.getQllx())) {
                            archiveName = bdcZdQllx.getArchiveName();
                        }
                    }
                }
                if (StringUtils.isNotBlank(archiveName)) {
                    String mlh = "";
                    String zslx = "zs";
                    if (CollectionUtils.isNotEmpty(bdcZsList)) {
                        if (StringUtils.equals(bdcZsList.get(0).getZstype(), Constants.BDCQZM_BH_FONT)) {
                            zslx = "zms";
                        }
                    }
                    Example example = new Example(BdcXtDamlh.class);
                    example.createCriteria().andEqualTo("zslx", zslx).andEqualTo("bdclx", bdcXm.getBdclx());
                    List<BdcXtDamlh> bdcXtDamlhList = entityMapper.selectByExample(BdcXtDamlh.class, example);
                    if (CollectionUtils.isNotEmpty(bdcXtDamlhList)) {
                        mlh = bdcXtDamlhList.get(0).getMlh();
                    }

                    List<BdcSjcl> bdcSjclList = bdcSjclService.getBdcSjclByproid(bdcXm.getProid());
                    if (CollectionUtils.isEmpty(bdcSjclList)) {
                        bdcSjclList = bdcSjclService.getBdcSjclByproid(wfProid);
                    }
                    /**
                     * @author bianwen
                     * @description bdcxm表中的qllx转换为名称
                     */

                    if (StringUtils.isNotBlank(bdcXm.getQllx())) {
                        BdcZdQllx bdcZdQllx = bdcZdGlService.getBdcZdQllxByDm(bdcXm.getQllx());
                        if (StringUtils.isNotBlank(bdcZdQllx.getMc())) {
                            bdcXm.setQllx(bdcZdQllx.getMc());
                        }
                    }

                    document = ArchiveModel.createFwbdcXml(document, nodeService, bdcXm, qllxVo, bdcSpxx, bdcQlrList, bdcZsList, archiveName, mlh, bdcSjclList, wfProid);
                }
            }

        }
        List<BdcGdxx> bdcGdxxList = null;
        if (document != null) {
            String xml = document.asXML();
            bdcGdxxList = archiveInterfaceCallPl(xml, userName);
        }
        return bdcGdxxList;
    }

    private List<BdcGdxx> archiveInterfaceCallPl(String xml, String userName) {
        String archiveUrl = AppConfig.getProperty("archive.url");
        List<BdcGdxx> bdcGdxxList = new ArrayList<BdcGdxx>();

        CloseableHttpClient closeableHttpClient;
        CloseableHttpResponse closeableHttpResponse = null;

        String gdInterface = archiveUrl + "/gateway.action";
        if (StringUtils.isNotBlank(gdInterface) && StringUtils.isNotBlank(xml)) {
            try {
                closeableHttpClient = (CloseableHttpClient) httpClient;
                HttpPost httpPost = new HttpPost(gdInterface);
                List<NameValuePair> params = Lists.newArrayList();
                params.add(new BasicNameValuePair("data", xml));
                httpPost.setEntity(new UrlEncodedFormEntity(params, Charsets.CHARSET_UTF8));
                closeableHttpResponse = closeableHttpClient.execute(httpPost);
                if (closeableHttpResponse.getStatusLine().getStatusCode() == 200) {
                    String responseXml = EntityUtils.toString(closeableHttpResponse.getEntity());
                    if (StringUtils.isNotBlank(responseXml)) {
                        bdcGdxxList = bdcGdxxService.initPlBdcGdxx(responseXml);
                    }
                }
                if (CollectionUtils.isNotEmpty(bdcGdxxList)) {
                    for (int i = 0; i < bdcGdxxList.size(); i++) {
                        BdcGdxx bdcGdxx = bdcGdxxList.get(i);
                        bdcGdxx.setGdr(userName);
                        bdcGdxxService.insertBdcGdxx(bdcGdxx);
                    }
                }
            } catch (SocketTimeoutException eTimeOut) {
                eTimeOut.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (closeableHttpResponse != null) {
                    try {
                        closeableHttpResponse.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return bdcGdxxList;
    }
}
