package com.dxhy.core.task;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.controller.AbstractController;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.core.dao.ConfirmDao;
import com.dxhy.core.dao.GsClientMapper;
import com.dxhy.core.entity.EsOutput;
import com.dxhy.core.entity.GsClient;
import com.dxhy.core.entity.PoCommonResponseParam;
import com.dxhy.core.job.entity.SNSAPObject;
import com.dxhy.core.job.entity.ScheduleJobEntity;
import com.dxhy.core.job.service.InvoiceInterfaceService;
import com.dxhy.core.job.service.ScheduleJobService;
import com.dxhy.core.util.HttpUtils;
import com.dxhy.core.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author fth
 * @date 2018年04月13日 下午10:57:22
 */
@SuppressWarnings({"rawtypes", "DuplicatedCode"})
@Component("sdnyClientTask")
@Slf4j
public class SdnyClientTask extends AbstractController {

    private static final String LOGGER_MSG = "(SAP获取公司client)";

    @Value("${sdny.snYxUrl}")
    private String snYxUrl;

    @Value("${po.userName}")
    private String userName;

    @Value("${po.password}")
    private String password;

    @Resource
    private GsClientMapper gsClientMapper;

    @Resource
    private InvoiceInterfaceService invoiceInterfaceService;
    @Resource
    private ConfirmDao confirmDao;
    @Resource
    private ScheduleJobService scheduleJobService;

    /**
     * 核心线程池大小
     */
    private int corePoolSize = 10;
    /**
     * 最大线程池大小
     */

    private int maximumPoolSize = 20;

    /**
     * @throws InterruptedException 异常
     * @Desc 发票获取接口
     */

    public void getSdnyClient() throws InterruptedException {
        log.info("获取山东能源Client定时任务开始");
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        ScheduleJobEntity scheduleJobEntity = scheduleJobService.queryByBeanName("sdnyClientTask", "getSdnyClient");
        if (scheduleJobEntity != null && "0".equals(scheduleJobEntity.getJobStatus())) {
            try {
                scheduleJobEntity.setJobStatus("1");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
                // 准备请求参数
                // 需判断 设置不认证状态

                List<GsClient> list = new ArrayList<>();
                long startTime = System.currentTimeMillis();
                SNSAPObject object = new SNSAPObject();
                object.setSYSID("FPXT");
                object.setIFYWID("FI846");
                object.setBSKEY(UUID.randomUUID().toString().replace("-", ""));
                object.setZFILED5("200");
                object.setZDATA("");

                //推送到SAP
                log.info("推送山能数据:{}", JSONObject.toJSONString(object));
                JSONObject request = new JSONObject();
                request.put("IS_INPUT", object);

                log.info("{}获取公司client入参:{}", LOGGER_MSG, request.toJSONString());
                String result = HttpUtils.sendPo(snYxUrl, request.toJSONString(), userName, password);
                log.info("{}获取公司client出参:{}", LOGGER_MSG, result);
                PoCommonResponseParam poCommonResponseParam = JsonUtils.getInstance().parseObject(result, PoCommonResponseParam.class);
                EsOutput es_output = poCommonResponseParam.getES_OUTPUT();
                String ztype = es_output.getZTYPE();
                String zmessage = es_output.getZMESSAGE();
                Object zdata = es_output.getZDATA();
                if ("s".equals(ztype)) {
                    List<Map<String, String>> gsClientList = JsonUtils.getInstance().parseObject(zdata.toString(), List.class);
                    gsClientList.stream().forEach(f -> {
                        GsClient gsClient = new GsClient();
                        gsClient.setGsdm(ObjectUtil.isNull(f.get("BUKRS")) ? "" : f.get("BUKRS").toString());
                        gsClient.setGsmc(ObjectUtil.isNull(f.get("BUTXT")) ? "" : f.get("BUTXT").toString());
                        gsClient.setClient(ObjectUtil.isNull(f.get("MANDT")) ? "" : f.get("MANDT").toString());
                        gsClient.setCreateTime(new Date());
                        list.add(gsClient);
                    });
                } else {
                    log.error("{}client:{},获取公司client出错:{}", LOGGER_MSG, "200", zmessage);
                }
                log.info("{}删除gs_client表数据", LOGGER_MSG);
                gsClientMapper.deleteAll();
                log.info("{}插入gs_client表", LOGGER_MSG);
                gsClientMapper.insertList(list);
                long endTime = System.currentTimeMillis();
                log.debug("{}任务结束，耗时:{}", LOGGER_MSG, endTime - startTime);

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                log.info("获取山东能源Client定时任务--重置执行状态");
                scheduleJobEntity.setJobStatus("0");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
            }
        }
    }

}