package com.bailuntec.job;

import com.alibaba.fastjson.JSON;
import com.bailuntec.domain.CostInfo;
import com.bailuntec.domain.constant.CommonConstant;
import com.bailuntec.domain.entity.DcBaseFinanceFee;
import com.bailuntec.domain.entity.JobPointLog;
import com.bailuntec.domain.example.DcBaseFinanceFeeExample;
import com.bailuntec.mapper.DcBaseFinanceFeeMapper;
import com.bailuntec.mapper.JobPointLogMapper;
import com.bailuntec.support.PointJob;
import com.bailuntec.utils.ExceptionUtil;
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 FeeJob 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("pageSize", jobPointLog.getPageSize().toString());
        map.put("startDate", DateTimeFormatter.ofPattern(CommonConstant.TIME_FORMAT).format(jobPointLog.getStartTime().minusHours(3L)));
        map.put("endDate", DateTimeFormatter.ofPattern(CommonConstant.TIME_FORMAT).format(jobPointLog.getEndTime()));
        do {
            map.put("pageIndex", jobPointLog.getPageIndex().equals(0) ? "1" : jobPointLog.getPageIndex().toString());
            Response response = null;
            String palResultStr = null;
            try {
                Request request = new Request.Builder()
                        .get()
                        .url(OkHttpUtil.attachHttpGetParams(propertiesUtil.getPropertyAsString("FEE_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)) {
                CostInfo costInfo = JSON.parseObject(palResultStr, CostInfo.class);
                if (jobPointLog.getPageIndex().equals(0)) {
                    jobPointLog.setPageIndex(costInfo.getData().getPages() + 1);
                }
                if (costInfo != null && costInfo.getData().getList().size() > 0) {
                    List<DcBaseFinanceFee> costDtoList = costInfo.getData().getList();
                    for (DcBaseFinanceFee dcBaseFinanceFee : costDtoList) {
                        try {
                            DcBaseFinanceFeeMapper dcBaseFinanceFeeMapper = SessionUtil.getSession().getMapper(DcBaseFinanceFeeMapper.class);
                            dcBaseFinanceFee.setBjModified(LocalDateTime.now());
                            int result = dcBaseFinanceFeeMapper.updateByExampleSelective(dcBaseFinanceFee, DcBaseFinanceFeeExample.newAndCreateCriteria().andCostNoEqualTo(dcBaseFinanceFee.getCostNo()).example());
                            if (result == 0) {
                                dcBaseFinanceFee.setBjModified(null);
                                dcBaseFinanceFeeMapper.insertSelective(dcBaseFinanceFee);
                            }
                        } catch (Exception e) {
                            throw new RuntimeException("BeanUtils.copyProperties失败");
                        } finally {
                            SessionUtil.closeSession();
                        }
                    }
                }
                log.info("sync finance_fee success");
            } else {
                throw new RuntimeException("调用费用接口同步百伦流水失败, 响应为null, 请求参数" + map.toString());
            }
            try {
                JobPointLogMapper mapper = SessionUtil.getSession().getMapper(JobPointLogMapper.class);
                mapper.upsertSelective(jobPointLog);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(ExceptionUtil.transform(e), e);
            } finally {
                SessionUtil.closeSession();
            }
            jobPointLog.setPageIndex(jobPointLog.getPageIndex() - 1);
        } while (0 < jobPointLog.getPageIndex());

        jobPointLog.setPageIndex(0);
        jobPointLog.setStartTime(jobPointLog.getEndTime());
        jobPointLog.setEndTime(jobPointLog.getEndTime().plusDays(jobPointLog.getIntervalTime()).isAfter(LocalDateTime.now()) ? LocalDateTime.now() : jobPointLog.getEndTime().plusDays(jobPointLog.getIntervalTime()));
    }
}
