package com.zjrs.ggfw.sggfw.blo.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yinhai.bcpcs.BcpRequest;
import com.yinhai.bcpcs.BcpResponse;
import com.yinhai.bcpcs.DefaultBcpClient;
import com.yinhai.bcpcs.IBcpClient;
import com.yinhai.bcpcs.exceptions.ClientException;
import com.yinhai.bcpcs.profile.DefaultProfile;
import com.yinhai.bcpcs.profile.IClientProfile;
import jakarta.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import com.zjrs.ggfw.sggfw.blo.RlzyscSjsbBLO;
import com.zjrs.ggfw.sggfw.entity.*;
import com.zjrs.ggfw.sggfw.po.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class RlzyscSjsbBLOImpl implements RlzyscSjsbBLO {

    private static final Logger LOG = LoggerFactory.getLogger(RlzyscSjsbBLOImpl.class);

    @Value("${sjsb.host:http://test.gdhrss.nwmh:8080/bcp}")
    private String host;

    @Value("${sjsb.systemkey:zj_rlzyscpt}")
    private String systemkey;

    @Value("${sjsb.servicekey:HZ_GGSB_IN}")
    private String servicekey;

    @Value("${sjsb.privatekey:certification_zj_rlzyscpt.keystore}")
    private String privatekey;

    @Resource
    private RsrlzyJkIddzMapper rsrlzyJkIddzMapper;

    @Resource
    private GrQzyxMapper grQzyxMapper;

    @Resource
    private SjsbPushDataLogMapper sjsbPushDataLogMapper;

    @Resource
    private SjsbPushDataMapper sjsbPushDataMapper;

    @Resource
    private ZphxxSbMapper zphxxSbMapper;

    @Resource
    private GrJlxxSbMapper grJlxxSbMapper;

    @Resource
    private GrQzdjMapper grQzdjMapper;

    @Resource
    private DwzpxxSbMapper dwzpxxSbMapper;

    @Resource
    private DwjbxxMapper dwjbxxMapper;

    @Resource
    private GrJbxxMapper grJbxxMapper;

    @Override
    public void grJlxxSb(String OperType) {

        List<GrJlxxPO> gzjyWsbList = new ArrayList<>();
        if (OperType.equals("UPD")){
            gzjyWsbList = this.grJlxxSbMapper.xyUpdateGzjyList(); //需更新列表
        }else if (OperType.equals("INS")){
             gzjyWsbList = this.grJlxxSbMapper.getGzjyWsbList();//上报
        }else{
            gzjyWsbList = this.grJlxxSbMapper.xyDelGzjyList();//删除
        }

        for (GrJlxxPO gzjyPO : gzjyWsbList) {
          try {
              IClientProfile profile = DefaultProfile.getProfile(host, systemkey, servicekey, true, privatekey);
              BcpRequest request = new BcpRequest();
              Map<String, Object> p = new HashMap<String, Object>();
              List list = new ArrayList<>();
              String tId = "";
              String grgzjyZtid = "";
              List<RsrlzyJkIddzPO> existIddzPO = new ArrayList<>();
              QueryWrapper<RsrlzyJkIddzPO> queryWrapper = new QueryWrapper<>();
              queryWrapper.eq("SID", gzjyPO.getAAC001());
              gzjyPO.setAAC001(tId);
              if (StringUtils.isNotBlank(gzjyPO.getAAC006())) {
                  String aac006 = gzjyPO.getAAC006();//出生日期
                  String year = aac006.substring(0, 4);
                  String month = aac006.substring(4, 6);
                  String day = aac006.substring(6, 8);
                  String newaac006 = year + "-" + month + "-" + day;//转换成所需格式yyyy-MM-dd
                  gzjyPO.setAAC006(newaac006);
              }
              if (StringUtils.isNotBlank(gzjyPO.getBCC309())) {
                  String kssj = gzjyPO.getBCC309().replaceAll("-", "");
                  gzjyPO.setBCC309(kssj.substring(0, 6));//yyyyMM
              }
              if (StringUtils.isNotBlank(gzjyPO.getBCC310())) {
                  String jssj = gzjyPO.getBCC310().replaceAll("-", "");
                  gzjyPO.setBCC310(jssj.substring(0, 6));//yyyyMM
              }
              if (OperType.equals("DEL")) {
                  gzjyPO.setAAE100("0");//将状态设置为无效
                  gzjyPO.setBPE900("DEL");
              } else if (OperType.equals("UPD")) {
                  gzjyPO.setBPE900("UPD");
              }
              if (gzjyPO.getAAC058().equals("01")) {  //证件类型为身份证时默认国籍为中国
                  gzjyPO.setAAC161("CHN");
              }
              list.add(gzjyPO);
              Map<String, Object> map2 = new HashMap<>();
              map2.put("dataset", list);
              p.put("userId", "4408");
              request.setInput(new Object[]{p});
              SjsbPushDatasLogPO sjsbPushDatasLogPO = new SjsbPushDatasLogPO();//记录日志表
              sjsbPushDatasLogPO.setUrl(host);
              sjsbPushDatasLogPO.setCs(JSONObject.toJSONString(p));
              IBcpClient client = new DefaultBcpClient(profile, request);
              BcpResponse<Map> response = null;
              try {
                  response = client.getResponse(Map.class);
              } catch (ClientException e) {
                  sjsbPushDatasLogPO.setRtn(e.getErrMsg());//记录错误信息
                  sjsbPushDataLogMapper.insert(sjsbPushDatasLogPO);
                  e.printStackTrace();
              }
              boolean isInvokeSuccess = response.isInvokeSuccess();
              Map data = null;
              if (isInvokeSuccess) {
                  data = response.getInvokeData();
                  String data2 = (String) data.get("data");
                  if (data2.equals("{}")) { //字段校验通过时，data无数据返回才真正上报成功
                      //上报成功才记录对照表
                      if (OperType.equals("INS")) {
                          if (existIddzPO.size() == 0) {
                              RsrlzyJkIddzPO rsrlzyJkIddzPO = new RsrlzyJkIddzPO();
                              this.rsrlzyJkIddzMapper.saveRsrlzyJkIddz(rsrlzyJkIddzPO);
                          }
                      }

                      SjsbPushDatasPO sjsbPushDatasPO = new SjsbPushDatasPO();//保存为正式表
                      sjsbPushDatasPO.setXgsj(gzjyPO.getBAE005());
                      if (OperType.equals("INS")) {
                          sjsbPushDatasPO.setDatatype("01");
                          this.sjsbPushDataMapper.insert(sjsbPushDatasPO);
                      } else if (OperType.equals("UPD")) {
                          UpdateWrapper<SjsbPushDatasPO> updateWrapper = new UpdateWrapper<>();
                          updateWrapper.eq("SID", gzjyPO.getACC0B0());
                          this.sjsbPushDataMapper.update(sjsbPushDatasPO, updateWrapper);
                      }else{
                          sjsbPushDatasPO.setTsyxbz("0");
                          UpdateWrapper<SjsbPushDatasPO> updateWrapper = new UpdateWrapper<>();
                          updateWrapper.eq("SID", gzjyPO.getACC0B0());
                          this.sjsbPushDataMapper.update(sjsbPushDatasPO, updateWrapper);
                      }

                      sjsbPushDatasLogPO.setRtn(JSONObject.toJSONString(data));//记录成功信息
                      sjsbPushDatasLogPO.setJg("1");//成功
                  } else {
                      sjsbPushDatasLogPO.setRtn(JSONObject.toJSONString(data));//记录错误信息
                      sjsbPushDatasLogPO.setJg("0");//失败
                  }
              } else {
                  String errorMsg = response.getErrorMessage();
                  LOG.info(errorMsg);
                  sjsbPushDatasLogPO.setRtn(errorMsg);//记录错误信息
                  sjsbPushDatasLogPO.setJg("0");//失败
              }
              this.sjsbPushDataLogMapper.insert(sjsbPushDatasLogPO);
          }catch(Exception e){
              LOG.info(e.getMessage());
              e.printStackTrace();
          }
        }

        List<GrJlxxPO> jyjlWsbList = this.grJlxxSbMapper.getJyjlWsbList();
        for (GrJlxxPO jyjlPO : jyjlWsbList) {
            try {
                IClientProfile profile = DefaultProfile.getProfile(host, systemkey, servicekey, true, privatekey);
                BcpRequest request = new BcpRequest();
                Map<String, Object> p = new HashMap<String, Object>();
                List list = new ArrayList<>();
                String tId = "";
                String grjyjlztid = "";
                List<RsrlzyJkIddzPO> existIddzPO = new ArrayList<>();
                QueryWrapper<RsrlzyJkIddzPO> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("SID", jyjlPO.getAAC001());
                existIddzPO = this.rsrlzyJkIddzMapper.selectList(queryWrapper);
                if (existIddzPO.size() != 0) { //在对照表中存在，直接取
                    tId = existIddzPO.get(0).getTid();
                    grjyjlztid = jyjlPO.getAAC001();
                } else {
                    tId = this.rsrlzyJkIddzMapper.getTId();
                    grjyjlztid = jyjlPO.getAAC001();
                }
                jyjlPO.setAAC001(tId);
                if (OperType.equals("DEL")) {
                } else if (OperType.equals("UPD")) {
                    jyjlPO.setBPE900("UPD");
                }
                if (jyjlPO.getAAC058().equals("01")) {  //证件类型为身份证时默认国籍为中国
                    jyjlPO.setAAC161("CHN");
                }
                list.add(jyjlPO);
                Map<String, Object> map2 = new HashMap<>();
                map2.put("dataset", list);
                request.setInput(new Object[]{p});
                SjsbPushDatasLogPO sjsbPushDatasLogPO = new SjsbPushDatasLogPO();//记录日志表
                sjsbPushDatasLogPO.setUrl(host);
                sjsbPushDatasLogPO.setSid(jyjlPO.getACC0B0());
                sjsbPushDatasLogPO.setDatatype("01");
                sjsbPushDatasLogPO.setCs(JSONObject.toJSONString(p));
                BcpResponse<Map> response = null;

                boolean isInvokeSuccess = response.isInvokeSuccess();
                Map data = null;

                if (isInvokeSuccess) {
                    data = response.getInvokeData();
                    String data2 = (String) data.get("data");
                    if (data2.equals("{}")) {//字段校验通过时，data无数据返回才真正上报成功
                        //上报成功才记录对照表
                        if (OperType.equals("INS")) {
                            if (existIddzPO.size() == 0) {
                                RsrlzyJkIddzPO rsrlzyJkIddzPO = new RsrlzyJkIddzPO();
                                rsrlzyJkIddzPO.setTid(tId);
                                rsrlzyJkIddzPO.setSid(grjyjlztid);
                                this.rsrlzyJkIddzMapper.saveRsrlzyJkIddz(rsrlzyJkIddzPO);
                            }
                        }

                        SjsbPushDatasPO sjsbPushDatasPO = new SjsbPushDatasPO();//保存为正式表
                        sjsbPushDatasPO.setXgsj(jyjlPO.getBAE005());
                        
                        sjsbPushDatasLogPO.setRtn(JSONObject.toJSONString(data));//记录成功信息
                        sjsbPushDatasLogPO.setJg("1");//成功
                    } else {
                        sjsbPushDatasLogPO.setRtn(JSONObject.toJSONString(data));//记录错误信息
                        sjsbPushDatasLogPO.setJg("0");//失败
                    }
                } else {
                    String errorMsg = response.getErrorMessage();
                    LOG.info(errorMsg);
                    sjsbPushDatasLogPO.setRtn(errorMsg);//记录错误信息
                    sjsbPushDatasLogPO.setJg("0");//失败
                }
                this.sjsbPushDataLogMapper.insert(sjsbPushDatasLogPO);
            }catch (Exception e){
                e.printStackTrace();
                LOG.info(e.getMessage());
            }
        }

    }

    @Override
    public void grQzdjSb(String OperType) {
       List<GrQzdjPO> wsbList = new ArrayList<>();
        if (OperType.equals("UPD")){
            wsbList = this.grQzdjMapper.xyUpdateQzdjList();
        }else if (OperType.equals("INS")){
            wsbList = this.grQzdjMapper.getWsbList();
        }else{
            wsbList = this.grQzdjMapper.xyDelQzdjList();
        }
        for (GrQzdjPO grQzdjPO : wsbList) {
            try{
            IClientProfile profile = DefaultProfile.getProfile(host, systemkey,servicekey, true, privatekey);
            BcpRequest request = new BcpRequest();
            Map<String, Object> p = new HashMap<String, Object>();
            List list = new ArrayList<>();
            String tId = "";
            String grZtid = "";
            List<RsrlzyJkIddzPO> existIddzPO  = new ArrayList<>();
                QueryWrapper<RsrlzyJkIddzPO> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("SID",grQzdjPO.getAAC001());
                existIddzPO = this.rsrlzyJkIddzMapper.selectList(queryWrapper);

                grQzdjPO.setAAE043(grQzdjPO.getAAE043().substring(0,10));
            if (grQzdjPO.getAAC058().equals("01")){  //证件类型为身份证时默认国籍为中国
                grQzdjPO.setAAC161("CHN");
            }
            list.add(grQzdjPO);
            Map<String, Object> map2 = new HashMap<>();
            map2.put("dataset", list);
            p.put("userId","4408");
            request.setInput(new Object[]{p});
            SjsbPushDatasLogPO sjsbPushDatasLogPO = new SjsbPushDatasLogPO();//记录日志表
            sjsbPushDatasLogPO.setUrl(host);
            sjsbPushDatasLogPO.setSid(grQzdjPO.getACC200());
            sjsbPushDatasLogPO.setDatatype("02");
            sjsbPushDatasLogPO.setCs(JSONObject.toJSONString(p));
            IBcpClient client = new DefaultBcpClient(profile, request);
            BcpResponse<Map> response = null;
            boolean isInvokeSuccess = response.isInvokeSuccess();
            Map data = null;
            if (isInvokeSuccess) {
                data = response.getInvokeData();
                String data2 =  (String)data.get("data");
                if (data2.equals("{}")){ //字段校验通过时，data无数据返回才真正上报成功
                    SjsbPushDatasPO sjsbPushDatasPO = new SjsbPushDatasPO();//保存为正式表
                    sjsbPushDatasPO.setXgsj(grQzdjPO.getBAE005());
                    sjsbPushDatasLogPO.setRtn(JSONObject.toJSONString(data));//记录成功信息
                    sjsbPushDatasLogPO.setJg("1");//成功
                }else {
                    sjsbPushDatasLogPO.setRtn(JSONObject.toJSONString(data));//记录错误信息
                    sjsbPushDatasLogPO.setJg("0");//失败
                }
            } else {
                String errorMsg = response.getErrorMessage();
                LOG.info(errorMsg);
                sjsbPushDatasLogPO.setRtn(errorMsg);//记录错误信息
                sjsbPushDatasLogPO.setJg("0");//失败
            }
            this.sjsbPushDataLogMapper.insert(sjsbPushDatasLogPO);
            }catch (Exception e){
                LOG.info(e.getMessage());
                e.printStackTrace();
            }
        }


    }

    @Override
    public void grQzyxSb(String OperType) {
        List<GrQzyxPO> WsbList = new ArrayList<>();
        if (OperType.equals("INS")){
            WsbList =  this.grQzyxMapper.getWsbList();//获取未上报的数据
        }else if (OperType.equals("DEL")){
            WsbList =  this.grQzyxMapper.xyDelGrqzyxList();
        }else{
            WsbList =  this.grQzyxMapper.xyUpdateGrqzyxList();
        }
        for (GrQzyxPO grQzyxPO : WsbList){
            try{ //上报数据
            List sbList = new ArrayList();
            SjsbPushDatasLogPO sjsbPushDatasLogPO = new SjsbPushDatasLogPO();//记录日志表
            IClientProfile profile = DefaultProfile.getProfile(host, systemkey,servicekey, true, privatekey);
            BcpRequest request = new BcpRequest();
            Map<String, Object> p = new HashMap<String, Object>();
            Map<String,Object> map2 = new HashMap<>();
            grQzyxPO.setAAE043(grQzyxPO.getAAE043().substring(0,10));//yyyy-MM-dd
            sbList.add(grQzyxPO);
            map2.put("dataset",sbList);
            p.put("userId", "4408");
            request.setInput(new Object[] { p });
            sjsbPushDatasLogPO.setUrl(host);
            sjsbPushDatasLogPO.setCs(JSONObject.toJSONString(map2));
            IBcpClient client = new DefaultBcpClient(profile, request);
            BcpResponse<Map> response = null;
            try {
                response = client.getResponse(Map.class);
            } catch (ClientException e) {
                e.printStackTrace();
                sjsbPushDataLogMapper.insert(sjsbPushDatasLogPO);
            }
            boolean isInvokeSuccess = response.isInvokeSuccess();
            Map data =null ;
            if (isInvokeSuccess) {
                data = response.getInvokeData();
            } else {
                String errorMsg = response.getErrorMessage();
                LOG.info(errorMsg);
                sjsbPushDatasLogPO.setRtn(errorMsg);//记录错误信息
                sjsbPushDatasLogPO.setJg("0");//失败
            }
            sjsbPushDataLogMapper.insert(sjsbPushDatasLogPO);
            }catch (Exception e){
                LOG.info(e.getMessage());
                e.printStackTrace();
            }
        }
    }

    @Override
    public void dwZpxxSb(String OperType) {
            List<DwZpxxPO> wsbList = new ArrayList<>();
        String tId = "";
        String dwztid = "";
            for (DwZpxxPO dwZpxxPO : wsbList) {
                try {
                IClientProfile profile = DefaultProfile.getProfile(host, systemkey, servicekey, true, privatekey);
                BcpRequest request = new BcpRequest();
                Map<String, Object> p = new HashMap<String, Object>();
                List list = new ArrayList<>();
                List<RsrlzyJkIddzPO> existIddzPO = new ArrayList<>();
                QueryWrapper<RsrlzyJkIddzPO> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("SID", dwZpxxPO.getAAB001());
                dwZpxxPO.setAAB001(tId);
                Calendar calendar2 = Calendar.getInstance();
                SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");                
                calendar2.add(Calendar.MONTH, 6);
                String six_month_after = sdf2.format(calendar2.getTime());
                dwZpxxPO.setACE014(six_month_after);//有效日期
                list.add(dwZpxxPO);
                Map<String, Object> map2 = new HashMap<>();
                map2.put("dataset", list);
                p.put("userId", "4408");
                request.setInput(new Object[]{p});

                SjsbPushDatasLogPO sjsbPushDatasLogPO = new SjsbPushDatasLogPO();//记录日志表
                sjsbPushDatasLogPO.setUrl(host);
                sjsbPushDatasLogPO.setSid(dwZpxxPO.getACB200());
                sjsbPushDatasLogPO.setCs(JSONObject.toJSONString(p));
                this.sjsbPushDataLogMapper.insert(sjsbPushDatasLogPO);
                }catch (Exception e){
                    LOG.info(e.getMessage());
                    e.printStackTrace();
                }
            }
    }

    @Override
    public void zphxxSb(String OperType) {
        List<ZphxxPO> zphxxList = new ArrayList<>();
        for (ZphxxPO zphxxpo : zphxxList){
            try{
            IClientProfile profile = DefaultProfile.getProfile(host, systemkey,servicekey, true, privatekey);
            BcpRequest request = new BcpRequest();
            Map<String, Object> p = new HashMap<String, Object>();
            List list  = new ArrayList<>();
            Map<String,Object> map = new HashMap<>();
            list.add(zphxxpo);
            Map<String,Object> map2 = new HashMap<>();
            map2.put("dataset",list);
            p.put("userId", "4408");

            SjsbPushDatasLogPO sjsbPushDatasLogPO = new SjsbPushDatasLogPO();//记录日志表
            sjsbPushDatasLogPO.setUrl(host);
            sjsbPushDatasLogPO.setSid(zphxxpo.getACB330());
            sjsbPushDatasLogPO.setDatatype("05");
            request.setInput(new Object[] { p });

            BcpResponse<Map> response = null;
            this.sjsbPushDataLogMapper.insert(sjsbPushDatasLogPO);
            }catch (Exception e){
                LOG.info(e.getMessage());
                e.printStackTrace();
            }
        }

    }

    @Override
    public void xyUpdateOrDelGrJbxx(String OperType) { //更新个人基本信息
        List<GrJbxxPO> grjbxxList = new ArrayList<>();
        if (OperType.equals("INS")){
            grjbxxList = this.grJbxxMapper.getXsbGrJbxx();
        }else{
            grjbxxList = this.grJbxxMapper.xyUpdateGrjbxx();
        }
        String tId = "";
        String grZtid = "";
        for (GrJbxxPO po : grjbxxList){
            try{
            IClientProfile profile = DefaultProfile.getProfile(host, systemkey,servicekey, true, privatekey);
            BcpRequest request = new BcpRequest();
            Map<String, Object> p = new HashMap<String, Object>();
            List list  = new ArrayList<>();
            tId = po.getTID();
            grZtid = po.getAAC001();
            po.setTID(null); //不让tId传送至省接口
            po.setAAC001(tId);//将对照表ID
            list.add(po);
            Map<String,Object> map2 = new HashMap<>();
            map2.put("dataset",list);
            p.put("userId", "4408");
            request.setInput(new Object[] { p });

            SjsbPushDatasLogPO sjsbPushDatasLogPO = new SjsbPushDatasLogPO();//记录日志表
            sjsbPushDatasLogPO.setUrl(host);
            sjsbPushDatasLogPO.setSid(grZtid);
            sjsbPushDatasLogPO.setCs(JSONObject.toJSONString(p));
            IBcpClient client = new DefaultBcpClient(profile, request);
            BcpResponse<Map> response = null;
            try {
                response = client.getResponse(Map.class);
            } catch (ClientException e) {
                e.printStackTrace();
            }
            this.sjsbPushDataLogMapper.insert(sjsbPushDatasLogPO);
            }catch (Exception e){
                LOG.info(e.getMessage());
                e.printStackTrace();
            }
        }

    }

    @Override
    public void xyUpdateOrDelDwJbxx(String OperType){
        List<DwjbxxPO> dwjbxxList = new ArrayList<>();
        if (OperType.equals("INS")){
            dwjbxxList = this.dwjbxxMapper.getXsbDwJbxx();
        }else{
            dwjbxxList = this.dwjbxxMapper.xyUpdateDwjbxx();
        }
        String tId = "";
        String dwZtid = "";
        for (DwjbxxPO po : dwjbxxList){
            try{
                Boolean Iddzbflzg = false;
            IClientProfile profile = DefaultProfile.getProfile(host, systemkey,servicekey, true, privatekey);
            BcpRequest request = new BcpRequest();
            Map<String, Object> p = new HashMap<String, Object>();
            List list  = new ArrayList<>();
            dwZtid = po.getAAB001();
            po.setTID(null); //不让tId传送至省接口
            po.setAAB001(tId);//将对照表ID
            list.add(po);
            Map<String,Object> map2 = new HashMap<>();
            map2.put("dataset",list);
            p.put("userId", "4408");
            request.setInput(new Object[] { p });

            SjsbPushDatasLogPO sjsbPushDatasLogPO = new SjsbPushDatasLogPO();//记录日志表
            sjsbPushDatasLogPO.setUrl(host);
            sjsbPushDatasLogPO.setSid(dwZtid);
            sjsbPushDatasLogPO.setDatatype("06");
            sjsbPushDatasLogPO.setCs(JSONObject.toJSONString(p));
            this.sjsbPushDataLogMapper.insert(sjsbPushDatasLogPO);
            }catch (Exception e){
                LOG.info(e.getMessage());
                e.printStackTrace();
            }
        }
    }
}
