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.DcBaseOmsOrder;
import com.bailuntec.domain.entity.JobPointLog;
import com.bailuntec.domain.example.DcBaseCrmRefundExample;
import com.bailuntec.domain.example.DcBaseOmsOrderExample;
import com.bailuntec.domain.pojo.RefundDetails;
import com.bailuntec.domain.pojo.RefundItem;
import com.bailuntec.mapper.DcBaseCrmRefundMapper;
import com.bailuntec.mapper.DcBaseOmsOrderMapper;
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.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;

@Slf4j
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 {
                            for (RefundItem refundItem : refundDetails.getItems()) {
                                DcBaseCrmRefund dcBaseCrmRefund = new DcBaseCrmRefund();
                                try {
                                    BeanUtils.copyProperties(dcBaseCrmRefund, refundItem);
                                    if(refundItem.getRefundedTime() != null) {
                                        dcBaseCrmRefund.setRefundTime(LocalDateTime.ofInstant(refundItem.getRefundedTime().toInstant(), ZoneId.systemDefault()));
                                    }
                                    /*BigDecimal exchangeRate = CallBailunSystem.getExchangeRate((dcBaseCrmRefund.getOrderCurrency() == null ? "CNY" : dcBaseCrmRefund.getOrderCurrency()), "CNY", dcBaseCrmRefund.getRefundTime());
                                    dcBaseCrmRefund.setAmountRefundRmb(exchangeRate.multiply(dcBaseCrmRefund.getAmountRefund()));*/
                                    if(dcBaseCrmRefund.getCompanyId() == null || dcBaseCrmRefund.getCompanyId() == 0) {
                                        dcBaseCrmRefund.setCompanyId(1);
                                    }
                                    log.warn(dcBaseCrmRefund.getOriginOrderId() +"------" + dcBaseCrmRefund.getBailunAccountId() +"------" + dcBaseCrmRefund.getBailunSku());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    throw new RuntimeException("CRM退款BeanUtils.copyProperties失败", e);
                                }
                                DcBaseOmsOrderMapper omsOrderMapper = SessionUtil.getSession().getMapper(DcBaseOmsOrderMapper.class);
                                DcBaseOmsOrder dcBaseOmsOrder = null;

                                if(dcBaseCrmRefund.getPlatformType() != null) {
                                    switch (dcBaseCrmRefund.getPlatformType().toUpperCase()) {
                                        case "EBAY":
                                            dcBaseOmsOrder = omsOrderMapper.selectOneByExample(DcBaseOmsOrderExample.newAndCreateCriteria().andBailunAccountIdEqualTo(dcBaseCrmRefund.getBailunAccountId()).andTransactionIdEqualTo(dcBaseCrmRefund.getOriginOrderId()).example());
                                            break;
                                        default:
                                            dcBaseOmsOrder = omsOrderMapper.selectOneByExample(DcBaseOmsOrderExample.newAndCreateCriteria().andBailunAccountIdEqualTo(dcBaseCrmRefund.getBailunAccountId()).andOriginOrderIdEqualTo(dcBaseCrmRefund.getOriginOrderId()).example());
                                    }

                                    if(dcBaseOmsOrder != null) {
                                        if("MERGED".equals(dcBaseOmsOrder.getBailunMergeStatus().toUpperCase())) {
                                            dcBaseOmsOrder = omsOrderMapper.selectOneByExample(DcBaseOmsOrderExample.newAndCreateCriteria().andBailunAccountIdEqualTo(dcBaseCrmRefund.getBailunAccountId()).andOriginOrderIdEqualTo(dcBaseOmsOrder.getAftermergedBailunOrderNo()).example());
                                        }
                                        if(dcBaseOmsOrder != null) {
                                            dcBaseCrmRefund.setOrderStatus(dcBaseOmsOrder.getBailunOrderStatus());
                                            dcBaseCrmRefund.setShippingStatus(dcBaseOmsOrder.getBailunShippingStatus());
                                            if("FBA".equals(dcBaseCrmRefund.getPlatformType().toUpperCase())) {
                                                dcBaseCrmRefund.setShippingStatus("TotalShipping");
                                            }
                                        }
                                    }
                                }

                                DcBaseCrmRefundMapper mapper = SessionUtil.getSession().getMapper(DcBaseCrmRefundMapper.class);
                                int i = mapper.updateByExampleSelective(dcBaseCrmRefund, DcBaseCrmRefundExample.newAndCreateCriteria().andCrmIdEqualTo(dcBaseCrmRefund.getCrmId()).example());
                                if (i == 0) {
                                    mapper.insertSelective(dcBaseCrmRefund);
                                }
                             //   SessionUtil.getSession().commit();
                            }
                        } catch (Exception e) {
                            throw new RuntimeException("MYBATIS操作DB异常", e);
                        } finally {
                            SessionUtil.closeSession();
                        }
                    }else {
                        break;
                    }
                } else {
                    throw new RuntimeException("CRM退款接口返回200, 但JSON错误" + map);
                }
                jobPointLog.setPageIndex(jobPointLog.getPageIndex() + 1);
            } else {
                throw new RuntimeException("CRM退款接口返回200, 但JSON错误" + map);
            }
        }
        while (true);
            jobPointLog.setPageIndex(1);
            jobPointLog.setStartTime(jobPointLog.getEndTime());
            jobPointLog.setEndTime(jobPointLog.getEndTime().plusDays(jobPointLog.getIntervalTime()).isAfter(LocalDateTime.now()) ? LocalDateTime.now() : jobPointLog.getEndTime().plusDays(jobPointLog.getIntervalTime()));
    }
}
