package com.bailuntec.job;

import com.alibaba.fastjson.JSON;
import com.bailuntec.domain.DcBaseFinanceCashierInfo;
import com.bailuntec.domain.FinanceCashierdetail;
import com.bailuntec.domain.WithdrawInfo;
import com.bailuntec.domain.constant.CommonConstant;
import com.bailuntec.domain.entity.DcBaseFinanceCashier;
import com.bailuntec.domain.entity.DcBaseFinanceCashierdetail;
import com.bailuntec.domain.entity.JobPointLog;
import com.bailuntec.mapper.DcBaseFinanceCashierMapper;
import com.bailuntec.mapper.DcBaseFinanceCashierdetailMapper;
import com.bailuntec.support.CallBailunSystem;
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.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;

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

@Slf4j
public class CashWithdrawDetail 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("begintime", DateTimeFormatter.ofPattern(CommonConstant.TIME_FORMAT).format(jobPointLog.getStartTime().minusHours(3L)));
        map.put("endtime", 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("WITHDRAW_DETAIL"), 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)) {
                WithdrawInfo withdrawInfo = JSON.parseObject(palResultStr, WithdrawInfo.class);
                if (withdrawInfo != null && withdrawInfo.getList() != null && withdrawInfo.getList().size() > 0) {
                    for(DcBaseFinanceCashierdetail dcBaseFinanceCashierdetail : withdrawInfo.getList()) {
                        DcBaseFinanceCashierdetailMapper dcBaseFinanceCashierdetailMapper = SessionUtil.getSession().getMapper(DcBaseFinanceCashierdetailMapper.class);
                        try {
                            BigDecimal exchangeRate = CallBailunSystem.getExchangeRate((dcBaseFinanceCashierdetail.getToCurrencyName() == null ? "CNY" : dcBaseFinanceCashierdetail.getToCurrencyName()), "CNY", LocalDateTime.now());
                            dcBaseFinanceCashierdetail.setOtherToCnyExchangeRate(exchangeRate);
                            dcBaseFinanceCashierdetail.setOtherToCnyMoney(exchangeRate.multiply(dcBaseFinanceCashierdetail.getDaozhangMoney() == null ? BigDecimal.ZERO : dcBaseFinanceCashierdetail.getDaozhangMoney()));
                            dcBaseFinanceCashierdetailMapper.upsertSelective(dcBaseFinanceCashierdetail);
                        } catch (Exception e) {
                            log.error(dcBaseFinanceCashierdetail.toString());
                            throw new RuntimeException(e);
                        }finally {
                            SessionUtil.closeSession();
                        }

                    }
                } else {
                    log.warn("请求结果：" + palResultStr + "请求参数：" + map.toString());
                    break;
                }
            } else {
                throw new RuntimeException("调用流水接口同步百伦流水失败, 响应为null, 请求参数" + map.toString());
            }
            jobPointLog.setPageIndex(jobPointLog.getPageIndex() + 1);
        } while (true);
        jobPointLog.setPageIndex(0);
        jobPointLog.setStartTime(jobPointLog.getEndTime());
        jobPointLog.setEndTime(jobPointLog.getEndTime().plusDays(jobPointLog.getIntervalTime()).isAfter(LocalDateTime.now()) ? LocalDateTime.now() : jobPointLog.getEndTime().plusDays(jobPointLog.getIntervalTime()));

    }
}
