package com.chinaweal.aiccs.crgs.movein.job;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chinaweal.aiccs.aiccs.abnormal.entity.EBaseinfo;
import com.chinaweal.aiccs.aiccs.abnormal.service.EBaseinfoService;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.crgs.movein.entity.TbZcEntityMovein;
import com.chinaweal.aiccs.crgs.movein.service.TbZcEntityMoveinService;
import com.chinaweal.aiccs.crgs.moveinDetails.entity.*;
import com.chinaweal.aiccs.crgs.moveinDetails.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

@Slf4j
@Component("downLoadTask")
public class DownLoadTask {

    /**
     * 对象及setter方法
     */
    private static final Map<Class<?>, Map<String, Method>> SETTER_METHOD = new HashMap<>();

    /**
     * TableId注解对象
     */
    private static final Map<Class<?>, Map<String, TableField>> TABLEFIELD_MAP = new HashMap<>();

    /**
     * TableField注解对象
     */
    private static final Map<Class<?>, Map<String, TableId>> TABLEID_MAP = new HashMap<>();

    @Autowired
    private MoveinCasePubBaseinfoService moveinCasePubBaseinfoService;
    @Autowired
    private CasePubPartyinfoService casePubPartyinfoService;
    @Autowired
    private CasePubAlterService casePubAlterService;
    @Autowired
    private CasePubDocService casePubDocService;
    @Autowired
    private MoveInAnBaseinfoService qrAnBaseinfoService;
    @Autowired
    private AnSubcapitalService anSubcapitalService;
    @Autowired
    private AnForinvestmentService anForinvestmentService;
    @Autowired
    private AnWebsiteinfoService anWebsiteinfoService;
    @Autowired
    private AnAlterstockinfoService anAlterstockinfoService;
    @Autowired
    private AnForguaranteeinfoService anForguaranteeinfoService;
    @Autowired
    private AnUpdateinfoService anUpdateinfoService;
    @Autowired
    private AnSupBaseinfoService anSupBaseinfoService;
    @Autowired
    private AnSocsecinfoService anSocsecinfoService;
    @Autowired
    private AnOverduepayService anOverduepayService;
    @Autowired
    private EBaseinfoService eBaseinfoService;
    @Autowired
    private TbZcEntityMoveinService tbZcEntityMoveinService;
    @Autowired
    private MoveinEBaseinfoService moveinEBaseinfoService;
    @Autowired
    private EAlterRecoderService eAlterRecoderService;
    @Autowired
    private EPubSpotcheckService ePubSpotcheckService;
    @Autowired
    private MoveinDrRaninsresService moveinDrRaninsresService;
    @Autowired
    private AoOpanomalyService aoOpanomalyService;
    @Autowired
    private MoveinAoOpaDetailService moveinAoOpaDetailService;
    @Autowired
    private AoOpanomalyInvService aoOpanomalyInvService;
    @Autowired
    private EImPermitService eImPermitService;
    @Autowired
    private EImPrmtaltService eImPrmtaltService;
    @Autowired
    private EImInvestmentService eImInvestmentService;
    @Autowired
    private EImInvprodetailService eImInvprodetailService;
    @Autowired
    private EImInvactdetailService eImInvactdetailService;
    @Autowired
    private MoveinEImInvupdateService moveinEImInvupdateService;
    @Autowired
    private EImIppldgService eImIppldgService;
    @Autowired
    private EImIppldgaltService eImIppldgaltService;
    @Autowired
    private EImCaseService eImCaseService;
    @Autowired
    private EImCasaltService eImCasaltService;
    @Autowired
    private EImInvsraltService eImInvsraltService;
    @Autowired
    private ELiIlldishonestyService eLiIlldishonestyService;
    @Autowired
    private MoveinELiIlldisdetailService moveinELiIlldisdetailService;
    @Autowired
    private MoveInEOtPermitService moveInEOtPermitService;
    @Autowired
    private EOtPrmtaltService eOtPrmtaltService;
    @Autowired
    private MoveinEOtCaseService moveinEOtCaseService;
    @Autowired
    private EOtCasaltService eOtCasaltService;
    @Autowired
    private EOtSpotcheckService eOtSpotcheckService;

    @Value("${zg.movein.downLoadUrl}")
    private String downloadPath;

    @Value("${zg.movein.temporaryFilePath}")
    private String temporaryFilePath;

    /**
     * 查询迁入企业并更新
     */
    private void task() {
        log.info("开始下载迁入企业年报，行政处罚数据" + new Date());
        Long start = System.currentTimeMillis();
        List<TbZcEntityMovein> tbZcEntityMoveins = tbZcEntityMoveinService.queryAllInfo();
        for (TbZcEntityMovein tbZcEntityMovein : tbZcEntityMoveins) {
            LambdaQueryWrapper<EBaseinfo> wrapper = new LambdaQueryWrapper();
            wrapper.eq(EBaseinfo::getPripid, tbZcEntityMovein.getPripid());
            EBaseinfo eBaseinfo = eBaseinfoService.getOne(wrapper);
            try {
                // 访问接口
                String fileStr = getFromUri(eBaseinfo.getUniscid());
                // 解析生成临时文件
                String decompressionPath = createTemporaryFile(fileStr, eBaseinfo.getUniscid());
                // 解析入库
                insertData(decompressionPath, eBaseinfo);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Long end = System.currentTimeMillis();
        log.info("下载迁入企业年报，行政处罚数据结束，耗时{} ms", end - start);
    }

    /**
     * 解析xml并入库
     */
    public void insertData(String decompressionPath, EBaseinfo eBaseinfo) throws Exception {
        if (StringUtils.isBlank(decompressionPath)) return;
        File realFile = new File(decompressionPath);
        File[] subfiles = realFile.listFiles();

        for (File fileEach : subfiles) {
            //      48 和 0 字节不解析
            if (fileEach.length() == 48 || fileEach.length() == 0) {
                fileEach.delete();
                continue;
            }
            //入库
            SAXReader reader = new SAXReader();
            Document doc = reader.read(fileEach);
            Element root = doc.getRootElement();
            if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("CASE_PUB_BASEINFO")) {
//                System.out.println(fileEach.getName()+"==="+fileEach.length());
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    MoveinCasePubBaseinfo bean = new MoveinCasePubBaseinfo();
                    bean = beanHandle(bean, row);
                    bean.setPripid(eBaseinfo.getPripid());
                    bean.setRegNo(eBaseinfo.getRegno());
                    bean.setUniscid(eBaseinfo.getUniscid());
                    bean.setEntname(eBaseinfo.getEntname());
                    moveinCasePubBaseinfoService.saveOrUpdate(bean);
//                    System.out.println("S_EXT_FROMNODE:" + row.elementText("S_EXT_FROMNODE"));
//                    System.out.println("ALTAF:" + row.elementText("ALTAF"));
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("CASE_PUB_PARTYINFO")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    CasePubPartyinfo bean = new CasePubPartyinfo();
                    bean = beanHandle(bean, row);
                    casePubPartyinfoService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("CASE_PUB_ALTER")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    CasePubAlter bean = new CasePubAlter();
                    bean = beanHandle(bean, row);
                    casePubAlterService.saveOrUpdate(bean);
//                    System.out.println(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("CASE_PUB_DOC")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    CasePubDoc bean = new CasePubDoc();
                    bean = beanHandle(bean, row);
                    casePubDocService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("AN_BASEINFO")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    MoveInAnBaseinfo bean = new MoveInAnBaseinfo();
                    bean = beanHandle(bean, row);
                    qrAnBaseinfoService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("AN_SUBCAPITAL")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    AnSubcapital bean = new AnSubcapital();
                    bean = beanHandle(bean, row);
                    anSubcapitalService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("AN_FORINVESTMENT")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    AnForinvestment bean = new AnForinvestment();
                    bean = beanHandle(bean, row);
                    anForinvestmentService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("AN_WEBSITEINFO")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    AnWebsiteinfo bean = new AnWebsiteinfo();
                    bean = beanHandle(bean, row);
                    anWebsiteinfoService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("AN_ALTERSTOCKINFO")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    AnAlterstockinfo bean = new AnAlterstockinfo();
                    bean = beanHandle(bean, row);
                    anAlterstockinfoService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("AN_FORGUARANTEEINFO")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    AnForguaranteeinfo bean = new AnForguaranteeinfo();
                    bean = beanHandle(bean, row);
                    anForguaranteeinfoService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("AN_UPDATEINFO")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    AnUpdateinfo bean = new AnUpdateinfo();
                    bean = beanHandle(bean, row);
                    anUpdateinfoService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("AN_SUP_BASEINFO")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    AnSupBaseinfo bean = new AnSupBaseinfo();
                    bean = beanHandle(bean, row);
                    anSupBaseinfoService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("AN_SOCSECINFO")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    AnSocsecinfo bean = new AnSocsecinfo();
                    bean = beanHandle(bean, row);
                    anSocsecinfoService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("AN_OVERDUEPAY")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    AnOverduepay bean = new AnOverduepay();
                    bean = beanHandle(bean, row);
                    anOverduepayService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("E_BASEINFO")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    MoveinEBaseinfo bean = new MoveinEBaseinfo();
                    bean = beanHandle(bean, row);
                    moveinEBaseinfoService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("E_ALTER_RECODER")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    EAlterRecoder bean = new EAlterRecoder();
                    bean = beanHandle(bean, row);
                    eAlterRecoderService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("E_PUB_SPOTCHECK")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    EPubSpotcheck bean = new EPubSpotcheck();
                    bean = beanHandle(bean, row);
                    ePubSpotcheckService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("DR_RANINSRES")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    MoveinDrRaninsres bean = new MoveinDrRaninsres();
                    bean = beanHandle(bean, row);
                    moveinDrRaninsresService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("AO_OPANOMALY")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    AoOpanomaly bean = new AoOpanomaly();
                    bean = beanHandle(bean, row);
                    aoOpanomalyService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("AO_OPA_DETAIL")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    MoveinAoOpaDetail bean = new MoveinAoOpaDetail();
                    bean = beanHandle(bean, row);
                    moveinAoOpaDetailService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("AO_OPANOMALY_INV")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    AoOpanomalyInv bean = new AoOpanomalyInv();
                    bean = beanHandle(bean, row);
                    aoOpanomalyInvService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("E_IM_PERMIT")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    EImPermit bean = new EImPermit();
                    bean = beanHandle(bean, row);
                    eImPermitService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("E_IM_PRMTALT")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    EImPrmtalt bean = new EImPrmtalt();
                    bean = beanHandle(bean, row);
                    eImPrmtaltService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("E_IM_INVESTMENT")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    EImInvestment bean = new EImInvestment();
                    bean = beanHandle(bean, row);
                    eImInvestmentService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("E_IM_INVPRODETAIL")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    EImInvprodetail bean = new EImInvprodetail();
                    bean = beanHandle(bean, row);
                    eImInvprodetailService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("E_IM_INVACTDETAIL")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    EImInvactdetail bean = new EImInvactdetail();
                    bean = beanHandle(bean, row);
                    eImInvactdetailService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("E_IM_INVUPDATE")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    MoveinEImInvupdate bean = new MoveinEImInvupdate();
                    bean = beanHandle(bean, row);
                    moveinEImInvupdateService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("E_IM_IPPLDG")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    EImIppldg bean = new EImIppldg();
                    bean = beanHandle(bean, row);
                    eImIppldgService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("E_IM_IPPLDGALT")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    EImIppldgalt bean = new EImIppldgalt();
                    bean = beanHandle(bean, row);
                    eImIppldgaltService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("E_IM_CASE")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    EImCase bean = new EImCase();
                    bean = beanHandle(bean, row);
                    eImCaseService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("E_IM_CASALT")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    EImCasalt bean = new EImCasalt();
                    bean = beanHandle(bean, row);
                    eImCasaltService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("E_IM_INVSRALT")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    EImInvsralt bean = new EImInvsralt();
                    bean = beanHandle(bean, row);
                    eImInvsraltService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("E_IM_CASE")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    EImCase bean = new EImCase();
                    bean = beanHandle(bean, row);
                    eImCaseService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("E_LI_ILLDISHONESTY")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    ELiIlldishonesty bean = new ELiIlldishonesty();
                    bean = beanHandle(bean, row);
                    eLiIlldishonestyService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("E_LI_ILLDISDETAIL")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    MoveinELiIlldisdetail bean = new MoveinELiIlldisdetail();
                    bean = beanHandle(bean, row);
                    moveinELiIlldisdetailService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("E_OT_PERMIT")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    MoveInEOtPermit bean = new MoveInEOtPermit();
                    bean = beanHandle(bean, row);
                    moveInEOtPermitService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("E_OT_PRMTALT")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    EOtPrmtalt bean = new EOtPrmtalt();
                    bean = beanHandle(bean, row);
                    eOtPrmtaltService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("E_OT_CASE")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    MoveinEOtCase bean = new MoveinEOtCase();
                    bean = beanHandle(bean, row);
                    moveinEOtCaseService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("E_OT_CASALT")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    EOtCasalt bean = new EOtCasalt();
                    bean = beanHandle(bean, row);
                    eOtCasaltService.saveOrUpdate(bean);
                }
            } else if (fileEach.getName().endsWith(".xml") && fileEach.getName().startsWith("E_OT_SPOTCHECK")) {
                Element row;
                for (Iterator domI = root.elementIterator("row"); domI.hasNext(); ) { //可能存在多条记录
                    row = (Element) domI.next();
                    EOtSpotcheck bean = new EOtSpotcheck();
                    bean = beanHandle(bean, row);
                    eOtSpotcheckService.saveOrUpdate(bean);
                }
            }
            fileEach.delete();
        }
        realFile.delete();
    }

    /**
     * xml映射到实体类中
     *
     * @param obj
     * @param row
     * @param <T>
     * @return
     */
    private <T> T beanHandle(T obj, Element row) {
        Class clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        Map<String, TableField> tableFieldMap = getTableField(clazz);
        Map<String, TableId> tableIdMap = getTableld(clazz);
        Map<String, Method> methodMap = getBeanSetter(clazz);
        for (Field field : fields) {
            Method method = methodMap.get(field.getName());
            TableId tableId = tableIdMap.get(field.getName());
            if (tableId != null) {
                String str = tableId.value();
                if (StringUtils.isNotBlank(str)) {
                    String rs = row.elementText(str);
                    if (StringUtils.isNotBlank(rs)) {
                        try {
                            setterInvoke(obj, method, rs);
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } else {
                TableField tableField = tableFieldMap.get(field.getName());
                if (tableField == null) continue; //不带注解，跳过set值
                String str = tableField.value();
                if (StringUtils.isNotBlank(str)) {
                    String rs = row.elementText(str);
                    if (StringUtils.isNotBlank(rs)) {
                        try {
                            setterInvoke(obj, method, rs);
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return obj;
    }

    /**
     * 生成临时文件
     *
     * @param fileStr
     */
    public String createTemporaryFile(String fileStr, String uniscid) throws Exception {
        if (StringUtils.isBlank(fileStr) || StringUtils.isBlank(uniscid)) return "";

        String temporaryPath = temporaryFilePath + uniscid + ".zip";  //输出zip路径文件
        String decompressionPath = temporaryFilePath + uniscid + File.separator; //解压目录
//        System.out.println("temporaryPath======" + temporaryPath);
//        System.out.println("decompressionPath======" + decompressionPath);

        byte[] bytes = Base64.getDecoder().decode(fileStr);
        File file = new File(temporaryPath);
        if (!file.exists()) {
            file.getParentFile().mkdirs();//创建文件父类文件夹路径
        }
        try (FileOutputStream fos = new FileOutputStream(file);
             BufferedOutputStream bos = new BufferedOutputStream(fos)) {
            bos.write(bytes);
        }

        // 解压
        ZipFile zipFile = new ZipFile(file, Charset.forName("GBK"));
        try (ZipInputStream zin = new ZipInputStream(new FileInputStream(file))) {
            ZipEntry entry;
            while (((entry = zin.getNextEntry()) != null) && !entry.isDirectory()) {//如果entry不为空，并不在同一个目录下
                File tmp = new File(decompressionPath + entry.getName());//解压出的文件路径
                if (!tmp.exists()) {//如果文件不存在
                    tmp.getParentFile().mkdirs();//创建文件父类文件夹路径
                    OutputStream os = new FileOutputStream(tmp);//将文件目录中的文件放入输出流

                    InputStream in = zipFile.getInputStream(entry);
                    int count = 0;
                    while ((count = in.read()) != -1) {//如有输入流可以读取到数值
                        os.write(count);//输出流写入
                    }
                    os.close();
                    in.close();
                }
                zin.closeEntry();
                System.out.println(entry.getName() + "解压成功");
            }
        }
        zipFile.close();
        // 删除压缩包
        file.delete();
        return decompressionPath;
    }

    /**
     * 请求下载接口
     *
     * @param uniscid
     * @return
     * @throws Exception
     */
    public String getFromUri(String uniscid) {
        String fileStr = "";
        if (StringUtils.isBlank(uniscid)) return fileStr;
        //拼接xml请求,带有请求头
        String soapRequestData = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservice.bo.enterprisemigration.datacollection.unieap.neusoft.com/\">\n" +
                "   <soapenv:Header/>\n" +
                "   <soapenv:Body>\n" +
                "      <web:downloadFile>\n" +
                "         <web:arg0></web:arg0>\n" +
                "         <web:arg1>" + uniscid + "</web:arg1>\n" +
                "         <web:arg2></web:arg2>\n" +
                "      </web:downloadFile>\n" +
                "   </soapenv:Body>\n" +
                "</soapenv:Envelope>";

        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpPost postMethod = new HttpPost(downloadPath);
            postMethod.setHeader("Content-Type", "text/xml; charset=utf-8");
            postMethod.setEntity(new StringEntity(soapRequestData, StandardCharsets.UTF_8));

            CloseableHttpResponse response = client.execute(postMethod);
            int statusCode = response.getStatusLine().getStatusCode();
            String soapResponseData = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);

//            String soapResponseData = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
//                    "   <soap:Body>" +
//                    "      <ns1:downloadFileResponse xmlns:ns1=\"http://webservice.bo.enterprisemigration.datacollection.unieap.neusoft.com/\">\n" +
//                    "         <ns1:return>{\"pkgValidateResult\":\"success\",\"errorMsg\":\"下载成功！\",\"fileStr\":\" \"}</ns1:return>" +
//                    "      </ns1:downloadFileResponse>" +
//                    "   </soap:Body>" +
//                    "</soap:Envelope>";
//            int statusCode = 200;


            //200说明正常返回数据
            if (statusCode == 200) {
                int z = soapResponseData.indexOf("<ns1:return>");
                int j = soapResponseData.indexOf("</ns1:return>");

                String returnStr = soapResponseData.substring(z + "<ns1:return>".length(), j);
                Map<String, String> map = JSONObject.parseObject(returnStr, Map.class);
                if (map.get("pkgValidateResult").equals("success")) {
                    fileStr = map.get("fileStr");
                } else {
                    log.info("{}主体请求下载接口失败，返回结果：{}", uniscid, map.get("pkgValidateResult") + "======" + map.get("errorMsg"));
                }
            } else {
                log.info("{}主体请求下载接口失败，状态值：{}", uniscid, statusCode);
            }
            return fileStr;
        } catch (Exception e) {
            e.printStackTrace();
            return fileStr;
        }
    }

    private Map<String, TableField> getTableField(Class<?> clazz) {
        Map<String, TableField> map = TABLEFIELD_MAP.get(clazz);
        if (map == null) {
            map = new HashMap<>();
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                TableField t = field.getDeclaredAnnotation(TableField.class);
                if (t != null) {
                    map.put(field.getName(), t);
                }
            }
            TABLEFIELD_MAP.put(clazz, map);
        }
        return map;
    }

    private Map<String, TableId> getTableld(Class<?> clazz) {
        Map<String, TableId> map = TABLEID_MAP.get(clazz);
        if (map == null) {
            map = new HashMap<>();
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                TableId t = field.getDeclaredAnnotation(TableId.class);
                if (t != null) {
                    map.put(field.getName(), t);
                }
            }
            TABLEID_MAP.put(clazz, map);
        }
        return map;
    }

    private Map<String, Method> getBeanSetter(Class<?> clazz) {
        Map<String, Method> methodMap = SETTER_METHOD.get(clazz);
        if (methodMap == null) {
            Method[] methods = clazz.getMethods();
            methodMap = new HashMap<String, Method>();
            SETTER_METHOD.put(clazz, methodMap);
            for (Method method : methods) {
                String methodName = method.getName();
                if (method.getParameterTypes().length == 1 && methodName.indexOf("set") == 0) {
                    String fieldName = methodName.substring(3, 4).toLowerCase() + methodName.substring(4);
                    methodMap.put(fieldName, method);
                }
            }
        }
        return methodMap;
    }

    private <T> void setterInvoke(T target, Method setter, Object value) throws InvocationTargetException, IllegalAccessException {
        Class<?> type = setter.getParameterTypes()[0];
        Class<?> valueType = value.getClass();
        if (type.equals(valueType)) {
            setter.invoke(target, value);
        } else if (valueType.equals(String.class)) {
            String valueStr = ((String) value).trim();
            if (type.equals(Integer.class)) {
                if (valueStr.length() > 0) setter.invoke(target, Integer.parseInt(valueStr));
            } else if (type.equals(Date.class)) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    setter.invoke(target, sdf.parse(valueStr));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            } else if (type.equals(LocalDate.class)) {
                String time = (String) value;
                if (time.length() >= 19) {
                    time = time.substring(0, 19);
                    DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    try {
                        setter.invoke(target, LocalDate.parse(time, sdf));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else if (type.equals(LocalDateTime.class)) {
                String time = (String) value;
                if (time.length() >= 19) {
                    time = time.substring(0, 19);
                    DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    try {
                        setter.invoke(target, LocalDateTime.parse(time, sdf));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else if (type.equals(BigDecimal.class)) {
                String str = (String) value;
                if (StringUtils.isNotBlank(str)) setter.invoke(target, new BigDecimal(str));
            }
        }
    }

    public static void main(String[] args) throws Exception {

        Field[] fields = AnUpdateinfo.class.getDeclaredFields();
        for (Field field : fields) {
            System.out.println(field.getName());
        }

//        MoveinCasePubBaseinfo moveinCasePubBaseinfo = new MoveinCasePubBaseinfo();
//        DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//       // 19  21
//        System.out.println("2021-12-03 18:30:43".length());
//        System.out.println("2021-12-03 18:30:43".substring(0,19)+"");
//        moveinCasePubBaseinfo.setPendecissdate(LocalDate.parse("2021-12-03 18:30:43.0".substring(0,19),sdf));
//        System.out.println(moveinCasePubBaseinfo.getPendecissdate()+"/////////////////");
//        moveinCasePubBaseinfo.setCreateTime(LocalDateTime.parse("2021-12-03 18:30:43.0".substring(0,19),sdf));
//        System.out.println(moveinCasePubBaseinfo.getCreateTime()+"===111111111111111111111111");
//
//        Class clazz = MoveinCasePubBaseinfo.class;
//        Field f = MoveinCasePubBaseinfo.class.getDeclaredField("caseid");
//        TableField t = f.getDeclaredAnnotation(TableField.class);
//        TableId t2 = f.getDeclaredAnnotation(TableId.class);
//        System.out.println("t2"+ t2.value());
//        System.out.println(t);
//        Method[] methods = clazz.getMethods();
//        for (Method method : methods) {
//            String methodName = method.getName();
//            if (method.getParameterTypes().length == 1 && methodName.indexOf("set") == 0) {
//                String fieldName = methodName.substring(3, 4).toLowerCase() + methodName.substring(4);
//                System.out.println(fieldName+"======"+method.getName());
//            }
//        }
    }
}
