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

import cn.hutool.core.date.DateTime;
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.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.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("reviewInformationTaskImpl")
public class ReviewInformationTaskImpl 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", "1",task.getExcuteParam());
        //组装审查数据推送一体化平台
        this.reviewData(informationEntities);
    }

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

    }

    private void reviewData(List<InformationEntity> informationEntities) {
        ArameterEntity arameterEntity = new ArameterEntity();
        if (!informationEntities.isEmpty()) {
            List<CallRecordEntity> callRecordEntities = new ArrayList<>();
            List<InformationEntity> collect = informationEntities.parallelStream().map(e -> {
                HashMap<String, Object> dataMap = new HashMap<>(16);
                dataMap.put("operateType", "1");
                HashMap<String, Object> targetConditionDefMap = new HashMap<>(16);
                targetConditionDefMap.put("provinceAreaCode", e.getAreaCode());
                targetConditionDefMap.put("deptCode", e.getDeptCode());
                targetConditionDefMap.put("areaCode", e.getAreaCode());
                dataMap.put("targetConditionDef", targetConditionDefMap);

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

                HashMap<String, Object> valueMap = new HashMap<>(16);
                HashMap<String, Object> rlogisticsinfoMap = new HashMap<>(16);
                rlogisticsinfoMap.put("nodeType", e.getNodeType());
                /*
                 * 测试数据--start
                 * */
                rlogisticsinfoMap.put("addUserId", "HCPSH_ZSJ");
                rlogisticsinfoMap.put("curHandlerName", "郑世杰");
                rlogisticsinfoMap.put("nodeIdCard", "51372319980502619x");
                rlogisticsinfoMap.put("nodePhone", "17158320000");
                rlogisticsinfoMap.put("nodeRegionId", e.getAreaCode());
                rlogisticsinfoMap.put("nodeOrganId", "513723199805026192");
                rlogisticsinfoMap.put("addOrganId", e.getDeptCode());
                rlogisticsinfoMap.put("addOrganName", "测试单位名称，正式上线后改动");
                /*
                 * 测试数据-finsh
                 * */
                rlogisticsinfoMap.put("auditAdvice", "1");
                rlogisticsinfoMap.put("auditRemark", "同意");
                rlogisticsinfoMap.put("genTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(e.getGenTime()));
                rlogisticsinfoMap.put("completeTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(e.getCompleteTime()));
                valueMap.put("rprojectruntask", rlogisticsinfoMap);
                dataMap.put("value", valueMap);
                String post = "";
//                JSONObject ifResultInfo = null;
                CallRecordEntity recordEntity = new CallRecordEntity();
                try {
                    ArameterEntity extCache = arameterService.getExtCache(e.getSystemCode());
//                    post = HttpUtil.post(extCache.getReviewAdress(), JSONObject.toJSONString(dataMap));
//                    ifResultInfo = JSONObject.parseObject(post).getJSONObject("ifResultInfo");
                    //ifResultInfo.getString("code")
                    if ("200".equals("200")) {
                        e.setBizStatus(NodeTypeEnum.决定.getDesc());
                        e.setNodeType(NodeTypeEnum.决定.getCode());
                        e.setProcessStatusName("决定");
                        //默认区间3~20分钟
                        e.setCreateTime(DateByAffairUtils.getTimeByAddRandomDouble(DateTime.now(), null, null));
//                        recordEntity = recordInterfaceExchangeRecord(post, ifResultInfo, e, dataMap);
                        log.info("推送一体化审查数据成功，");
                    } else {
                        //推送失败后，设置标识符，不在重复推送
                        e.setIsReport("0");
                        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) {
                    //推送失败后，设置标识符，不在重复推送
                    e.setIsReport("0");
                    if (0 == e.getFailTimes()) {
                        e.setFailTimes(1);
                    } else {
                        e.setFailTimes(e.getFailTimes() + 1);
                    }
//                    e.setFailReason(ifResultInfo.getString("message"));
                    log.error("省一体化审查数据推送失败：连接异常" + post);
                    recordEntity.setInterfaceCallStatus("500");
//                    recordEntity = recordInterfaceExchangeRecord(post, ifResultInfo, e, dataMap);
                    //记录接口交换记录
                    callRecordEntities.add(recordEntity);
                    return e;
                }
            }).collect(Collectors.toList());
            informationService.update(collect, 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;
    }

}
