package com.bailuntec.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bailuntec.domain.constant.CommonConstant;
import com.bailuntec.domain.entity.DcBaseCrmRefund;
import com.bailuntec.domain.entity.JobPointLog;
import com.bailuntec.domain.pojo.RefundDetails;
import com.bailuntec.domain.pojo.RefundItem;
import com.bailuntec.mapper.DcBaseCrmRefundMapper;
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 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.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;

public class CrmRefundSyncJob extends PointJob {
    private PropertiesUtil propertiesUtil = PropertiesUtil.getInstance("const");
    private OkHttpClient client = OkHttpUtil.getInstance();

    @Override
    public void executeJob(ShardingContext shardingContext, JobPointLog jobPointLog) {
        HashMap<String, String> map = new HashMap<>(4);
        map.put("btime", jobPointLog.getStartTime().format(DateTimeFormatter.ofPattern(CommonConstant.TIME_FORMAT)));
        map.put("etime", jobPointLog.getEndTime().format(DateTimeFormatter.ofPattern(CommonConstant.TIME_FORMAT)));
        map.put("rows", jobPointLog.getPageSize().toString());
        Integer totalPage = 0;
        do {
            map.put("page", jobPointLog.getPageIndex().toString());
            Response response = null;
            String resultStr = null;
            try {
                Request request = new Request.Builder()
                        .url(OkHttpUtil.attachHttpGetParams(propertiesUtil.getPropertyAsString("CRM_REFUND_URL"), map))
                        .get()
                        .addHeader("cache-control", "no-cache")
                        .build();
                response = client.newCall(request).execute();
                resultStr = response.body().string();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("CRM退款接口返回400" + map);
            } finally {
                if (response != null) {
                    response.close();
                }
            }
            if (StringUtils.isNotBlank(resultStr)) {
                JSONObject jsonObject = JSON.parseObject(resultStr);
                if (jsonObject.get("success") != null && jsonObject.getBooleanValue("success")) {
                    RefundDetails refundDetails = jsonObject.getObject("data", RefundDetails.class);
                    totalPage = refundDetails.getTotalPages();
                    if (refundDetails.getItems() != null && refundDetails.getItems().size() > 0) {
                        try {
                            DcBaseCrmRefundMapper mapper = SessionUtil.getSession().getMapper(DcBaseCrmRefundMapper.class);
                            for (RefundItem refundItem : refundDetails.getItems()) {
                                DcBaseCrmRefund dcBaseCrmRefund = new DcBaseCrmRefund();
                                try {
                                    BeanUtils.copyProperties(dcBaseCrmRefund, refundItem);
                                    dcBaseCrmRefund.setRefundTime(LocalDateTime.ofInstant(refundItem.getRefundedTime().toInstant(), ZoneId.systemDefault()));
                                    BigDecimal exchangeRate = CallBailunSystem.getExchangeRate(dcBaseCrmRefund.getOrderCurrency(), "CNY", dcBaseCrmRefund.getRefundTime());
                                    dcBaseCrmRefund.setAmountRefundRmb(exchangeRate.multiply(dcBaseCrmRefund.getAmountRefund()));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    throw new RuntimeException("CRM退款BeanUtils.copyProperties失败", e);
                                }
                                mapper.upsertSelective(dcBaseCrmRefund);
                                SessionUtil.getSession().commit();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            throw new RuntimeException("MYBATIS操作DB异常", e);
                        } finally {
                            SessionUtil.closeSession();
                        }
                    }
                } else {
                    throw new RuntimeException("CRM退款接口返回200, 但JSON错误" + map);
                }
                jobPointLog.setPageIndex(jobPointLog.getPageIndex() + 1);
            } else {
                throw new RuntimeException("CRM退款接口返回200, 但JSON错误" + map);
            }
        }
        while (jobPointLog.getPageIndex() <= totalPage);
        if (jobPointLog.getPageIndex() > totalPage) {
            jobPointLog.setPageIndex(1);
            jobPointLog.setStartTime(jobPointLog.getEndTime());
            jobPointLog.setEndTime(jobPointLog.getEndTime().plusDays(jobPointLog.getIntervalTime()).isAfter(LocalDateTime.now()) ? LocalDateTime.now() : jobPointLog.getEndTime().plusDays(jobPointLog.getIntervalTime()));
        }
    }
}
