package com.bailuntec.job;

import com.alibaba.fastjson.JSON;
import com.bailuntec.domain.ManageCostInfo;
import com.bailuntec.domain.constant.CommonConstant;
import com.bailuntec.domain.entity.DcBaseFinanceManagecost;
import com.bailuntec.domain.entity.JobPointLog;
import com.bailuntec.domain.example.DcBaseFinanceManagecostExample;
import com.bailuntec.mapper.DcBaseFinanceManagecostMapper;
import com.bailuntec.support.PointJob;
import com.bailuntec.utils.OkHttpUtil;
import com.bailuntec.utils.PropertiesUtil;
import com.bailuntec.utils.SessionUtil;
import com.dangdang.ddframe.job.api.ShardingContext;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;
import java.util.List;

@Slf4j
public class ManageCostJob extends PointJob {

    private OkHttpClient okHttpClient = OkHttpUtil.getInstance();
    private PropertiesUtil propertiesUtil = PropertiesUtil.getInstance("const");

    @Override
    public void executeJob(ShardingContext shardingContext, JobPointLog jobPointLog) {
        LinkedHashMap<String, String> map = new LinkedHashMap<>(4);
        map.put("o", "0");
        map.put("startDate", DateTimeFormatter.ofPattern(CommonConstant.TIME_FORMAT).format(jobPointLog.getStartTime().minusHours(3L)));
        map.put("endDate", DateTimeFormatter.ofPattern(CommonConstant.TIME_FORMAT).format(jobPointLog.getEndTime()));

            Response response = null;
            String palResultStr = null;
            try {
                Request request = new Request.Builder()
                        .get()
                        .url(OkHttpUtil.attachHttpGetParams(propertiesUtil.getPropertyAsString("MANAGECOST_URL"), map))
                        .addHeader("Content-Type", "application/json")
                        .build();
                response = okHttpClient.newCall(request).execute();
                palResultStr = response.body().string();
            } catch (IOException e) {
                throw new RuntimeException(map + "请求管理成本接口同步百伦接口失败" + response, e);
            } finally {
                if (response != null) {
                    response.close();
                }
            }
            if (StringUtils.isNoneBlank(palResultStr)) {
                ManageCostInfo manageCostInfo = JSON.parseObject(palResultStr, ManageCostInfo.class);
                if (manageCostInfo != null && manageCostInfo.isSuccess() && manageCostInfo.getData().size() > 0) {
                    List<DcBaseFinanceManagecost> dcBaseFinanceManagecostList = manageCostInfo.getData();
                    for(DcBaseFinanceManagecost dcBaseFinanceManagecost : dcBaseFinanceManagecostList) {
                        try {
                            DcBaseFinanceManagecostMapper dcBaseFinanceManagecostMapper = SessionUtil.getSession().getMapper(DcBaseFinanceManagecostMapper.class);
                            dcBaseFinanceManagecost.setGmtModifyTime(LocalDateTime.now());
                           int result = dcBaseFinanceManagecostMapper.updateByExampleSelective(dcBaseFinanceManagecost, DcBaseFinanceManagecostExample.newAndCreateCriteria().andNoEqualTo(dcBaseFinanceManagecost.getNo()).andCostIdEqualTo(dcBaseFinanceManagecost.getCostId()).andCostId1EqualTo(dcBaseFinanceManagecost.getCostId1()).example());
                           if(result == 0) {
                               dcBaseFinanceManagecost.setGmtModifyTime(null);
                               dcBaseFinanceManagecostMapper.insertSelective(dcBaseFinanceManagecost);
                           }
                        } catch (Exception e) {
                            log.warn("Mybatis 操作失败!", e);
                            throw new RuntimeException("MyBatis 操作失败!");
                        }finally {
                            SessionUtil.closeSession();
                        }
                    }
                }
            } else {
                throw new RuntimeException("调用管理成本接口同步百伦流水失败, 响应为null, 请求参数" + map.toString());
            }
        jobPointLog.setPageIndex(0);
        jobPointLog.setStartTime(jobPointLog.getEndTime());
        jobPointLog.setEndTime(jobPointLog.getEndTime().plusDays(jobPointLog.getIntervalTime()).isAfter(LocalDateTime.now()) ? LocalDateTime.now() : jobPointLog.getEndTime().plusDays(jobPointLog.getIntervalTime()));

    }
}
