package com.mortals.xhx.modules.information.task;

import cn.hutool.core.date.DateTime;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.service.ITask;
import com.mortals.framework.service.ITaskExcuteService;
import com.mortals.framework.util.StringUtils;
import com.mortals.xhx.common.code.ApplicantTypeEnums;
import com.mortals.xhx.common.code.NodeTypeEnum;
import com.mortals.xhx.common.utils.DateByAffairUtils;
import com.mortals.xhx.common.utils.SnowFlakeUtil;
import com.mortals.xhx.modules.arameter.model.ArameterEntity;
import com.mortals.xhx.modules.arameter.model.ArameterQuery;
import com.mortals.xhx.modules.arameter.service.ArameterService;
import com.mortals.xhx.modules.call.model.CallRecordEntity;
import com.mortals.xhx.modules.call.service.CallRecordService;
import com.mortals.xhx.modules.information.model.InformationEntity;
import com.mortals.xhx.modules.information.service.InformationService;
import com.mortals.xhx.modules.service.QueryInformationServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author liaoxin
 * @Date: 2021-08-2021/8/3-16:28
 * @Description:办件数据推送省一体化平台(申请并受理)
 */
@Slf4j
@Component("applyAndAcceptInformationTaskImpl")
public class ApplyAndAcceptInformationTaskImpl implements ITaskExcuteService {
    @Autowired
    private InformationService informationService;

    @Autowired
    private CallRecordService callRecordService;

    @Autowired
    private ArameterService arameterService;

    @Autowired
    private QueryInformationServiceImpl queryInformationService;

    @Override
    public void excuteTask(ITask task) throws AppException {
        //1.查询上月的表是否存在未推送的数据
        List<InformationEntity> informationEntities =
                queryInformationService.queryDataThatHasNotBeenPushed(NodeTypeEnum.受理.getCode(), "1", "0",task.getExcuteParam());
        //组装申请并受理数据推送一体化平台
        this.applyAndAccept(informationEntities);
    }


    @Override
    public void stopTask(ITask task) throws AppException {

    }

    private void applyAndAccept(List<InformationEntity> informationEntities) {
        if (!informationEntities.isEmpty()) {
            List<CallRecordEntity> callRecordEntities = new ArrayList<>();
            List<InformationEntity> entities = informationEntities.parallelStream().map(e -> {
                ArameterEntity extCache = new ArameterEntity();
                extCache.setSysCode(e.getSystemCode());
                extCache = arameterService.find(extCache).get(0);
                Map<String, Object> dataMap = assembleData(e);
                String post = "";
                JSONObject ifResultInfo = null;
                CallRecordEntity recordEntity = new CallRecordEntity();
                try {
                    post = HttpUtil.post(extCache.getAcceptAdress(), JSONObject.toJSONString(dataMap));
                    if(StringUtils.isEmpty(post)){
                        e.setIsSuccess("0");
                        return e;
                    }
                    ifResultInfo = JSONObject.parseObject(JSONObject.parseObject(post).getString("ifResultInfo"));
                    log.info("响应值" + ifResultInfo);
                    if ("200".equals(ifResultInfo.getString("code"))) {
                        e.setIsReport("1");
                        e.setIsSuccess("1");
                        e.setOfficeCode(ifResultInfo.getJSONObject("data").getString("code"));
                        e.setBizStatus(NodeTypeEnum.审查.getDesc());
                        e.setNodeType(NodeTypeEnum.审查.getCode());
                        //默认区间3~20分钟
                        e.setCreateTime(DateByAffairUtils.getTimeByAddRandomDouble(DateTime.now(), null, null));
                        e.setProcessStatusName("审查");
                        recordEntity=recordInterfaceExchangeRecord(post,ifResultInfo,e,dataMap);
                        log.info("推送省一体化申请并受理成功，办件编码：" + ifResultInfo.getJSONObject("data").getString("code"));
                    } else {
                        e.setIsReport("1");
                        if (0 == e.getFailTimes()) {
                            e.setFailTimes(1);
                        } else {
                            e.setFailTimes(e.getFailTimes() + 1);
                        }
                        recordEntity.setInterfaceCallStatus("500");
                        recordEntity=recordInterfaceExchangeRecord(post,ifResultInfo,e,dataMap);
                        e.setFailReason(ifResultInfo.getString("message"));
                        log.info("省一体化申请并受理数据推送失败：" + ifResultInfo.getString("message"));
                    }

                    callRecordEntities.add(recordEntity);
                    return e;

                } catch (Exception ex) {
                    ex.printStackTrace();
                    e.setIsReport("0");
                    if (0 == e.getFailTimes()) {
                        e.setFailTimes(1);
                    } else {
                        e.setFailTimes(e.getFailTimes() + 1);
                    }
                    e.setFailReason(ifResultInfo.getString("message"));
                    log.error("省一体化申请并受理数据推送失败：连接异常" + ex.getMessage());
                    recordEntity.setInterfaceCallStatus("500");
                    recordEntity=recordInterfaceExchangeRecord(post,ifResultInfo,e,dataMap);
                    //记录接口交换记录
                    callRecordEntities.add(recordEntity);
                    return e;

                }
            }).collect(Collectors.toList());
            informationService.update(entities,null);
            //记录接口交换记录
            callRecordService.save(callRecordEntities,null);

        } else {
            log.info("没有从办件表中获取到申请并受理数据");
        }
    }

    private CallRecordEntity recordInterfaceExchangeRecord(String post, JSONObject ifResultInfo, InformationEntity e, Map<String, Object> dataMap) {
        CallRecordEntity recordEntity = new CallRecordEntity();
        recordEntity.setId(SnowFlakeUtil.get().nextId());
        recordEntity.setPieceId(e.getId());
        recordEntity.setCurrentStepName("申请并受理");
        recordEntity.setCurrentStepCode(NodeTypeEnum.受理.getCode());
        recordEntity.setIncomingMessage(JSONObject.toJSONString(dataMap));
        if (StringUtils.isNotEmpty(post)){
            recordEntity.setReturnMessage(JSONObject.toJSONString(post));
        recordEntity.setInterfaceCallStatus(ifResultInfo.getString("code"));
        }
        recordEntity.setInterfaceCallTime(DateTime.now());
        recordEntity.setSystemCode(e.getSystemCode());
        return  recordEntity;
    }

    private Map<String, Object> assembleData(InformationEntity informationEntity) {
        Map<String, Object> dataMap = new HashMap<>(16);
        dataMap.put("operateType", "1");

        HashMap<String, Object> targetConditionDefMap = new HashMap<>(16);
        targetConditionDefMap.put("provinceAreaCode", informationEntity.getAreaCode());
        targetConditionDefMap.put("deptCode", informationEntity.getDeptCode());
        targetConditionDefMap.put("areaCode", informationEntity.getAreaCode());
        dataMap.put("targetConditionDef", targetConditionDefMap);

        HashMap<String, Object> baseInfoMap = new HashMap<>(16);
        baseInfoMap.put("reCode", informationEntity.getEventCode());
        baseInfoMap.put("bizStatus", informationEntity.getBizStatus());
        baseInfoMap.put("sysCode", informationEntity.getSystemCode());
        dataMap.put("baseInfo", baseInfoMap);

        HashMap<String, Object> valueMap = new HashMap<>(16);
        HashMap<String, Object> infoMap = new HashMap<>(16);
        infoMap.put("affairName", informationEntity.getAffairName());
        infoMap.put("eventCode", informationEntity.getEventCode());
        infoMap.put("applyType", informationEntity.getApplyType());
        infoMap.put("bizStatus", informationEntity.getBizStatus());
        infoMap.put("doThingProperty", informationEntity.getDoThingProperty());
        infoMap.put("isCharge", informationEntity.getIsCharge());
        infoMap.put("applyNum", informationEntity.getApplyNum());
        infoMap.put("applicantType", informationEntity.getApplicantAttributes());
        if (ApplicantTypeEnums.LEGAL.getCode() == informationEntity.getApplicantAttributes()) {
            infoMap.put("mainProperty", informationEntity.getApplicantAttributes());
            infoMap.put("legalPerson", informationEntity.getOrganizationName());
            infoMap.put("legalPersonIDCard", informationEntity.getOrganizationCardNumber());
        }
        infoMap.put("cardType", informationEntity.getApplicantCardType());
        infoMap.put("applicantIdCard", informationEntity.getApplicantCardNumbe());
        infoMap.put("applicantName", informationEntity.getApplicantName());
        infoMap.put("applicantAddress", "地址不详，未提供");
        infoMap.put("applicantPhone", informationEntity.getApplicantPhoneNumber());
        infoMap.put("applicantSex", informationEntity.getApplicantSex());
        infoMap.put("contactName", informationEntity.getContactName());
        infoMap.put("contactSex", informationEntity.getApplicantSex());
        infoMap.put("contactIdCard", informationEntity.getContactIdCard());
        infoMap.put("contactCardType", informationEntity.getContactCardType());
        infoMap.put("contactPhone", informationEntity.getContactPhone());
        HashMap<String, Object> rlogisticsinfoMap = new HashMap<>(16);
        rlogisticsinfoMap.put("pickupType", informationEntity.getPickupType());
        infoMap.put("rlogisticsinfo", rlogisticsinfoMap);
        HashMap<String, Object> rprojectruntaskMap = new HashMap<>(16);
        rprojectruntaskMap.put("nodeType", informationEntity.getNodeType());
        rprojectruntaskMap.put("addUserId", "-1");
        rprojectruntaskMap.put("curHandlerName", "");
        rprojectruntaskMap.put("auditAdvice", "1");
        rprojectruntaskMap.put("auditRemark", "同意");
        rprojectruntaskMap.put("genTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(informationEntity.getGenTime()));
        rprojectruntaskMap.put("completeTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(informationEntity.getCompleteTime()));
        valueMap.put("rprojectsl", infoMap);
        valueMap.put("rprojectruntask", rprojectruntaskMap);
        dataMap.put("value", valueMap);
        return dataMap;
    }


}
