package com.bailuntec.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.bailuntec.domain.constant.CommonConstant;
import com.bailuntec.domain.dto.PurchaseDetailAimsDTO;
import com.bailuntec.domain.dto.PurchaseDetailDTO;
import com.bailuntec.domain.entity.DcBasePurchaseDetails;
import com.bailuntec.domain.entity.JobPointLog;
import com.bailuntec.domain.example.DcBasePurchaseDetailsExample;
import com.bailuntec.mapper.DcBasePurchaseDetailsMapper;
import com.bailuntec.mapper.JobPointLogMapper;
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.*;
import org.apache.commons.beanutils.BeanUtils;
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 SyncPurchaseAimsJob extends PointJob {
    private static PropertiesUtil propertiesUtil = PropertiesUtil.getInstance("const");
    private static OkHttpClient client = OkHttpUtil.getInstance();

    @Override
    public void executeJob(ShardingContext shardingContext, JobPointLog jobPointLog) {
        Integer pageSize = jobPointLog.getPageSize();
        jobPointLog.setPageIndex(jobPointLog.getPageIndex() != 1 ? 1 : jobPointLog.getPageIndex());
        DcBasePurchaseDetailsMapper dcBasePurchaseDetailsMapper = SessionUtil.getSession().getMapper(DcBasePurchaseDetailsMapper.class);
        long count = 0L;
        try{
            count = dcBasePurchaseDetailsMapper.getCount();
        }catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("MYBATIS操作DB失败");
        } finally {
            SessionUtil.closeSession();
        }
        int totalPage = (int)(count % pageSize.longValue() == 0 ? count/pageSize.longValue() : count/pageSize.longValue() + 1);
        do{
            dcBasePurchaseDetailsMapper = SessionUtil.getSession().getMapper(DcBasePurchaseDetailsMapper.class);
            List<String> dcBasePurchaseDetailsList = dcBasePurchaseDetailsMapper.selectPageByGroup((jobPointLog.getPageIndex() - 1) * jobPointLog.getPageSize(), jobPointLog.getPageSize());


            MediaType mediaType = MediaType.parse("application/json");
            LinkedHashMap<String, Object> map = new LinkedHashMap<>(1);
            map.put("purchasenos", String.join(",", dcBasePurchaseDetailsList));
            List<PurchaseDetailAimsDTO> purchaseDetailAimsDTOS = null;


            RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(map));
            String purchaseStr = null;
            Response response = null;
            if (purchaseDetailAimsDTOS != null) purchaseDetailAimsDTOS = null;
            try {
                Request request = new Request.Builder()
                        .url(propertiesUtil.getPropertyAsString("PURCHASE_AIMS_URL"))
                        .post(body)
                        .addHeader("Content-Type", "application/json")
                        .build();
                response = client.newCall(request).execute();
                purchaseStr = response.body().string();
                System.out.println(purchaseStr);
            } catch (IOException e) {
                log.error("调用采购单sku详细信息接口失败", e);
                throw new RuntimeException("调用采购单sku详细信息接口失败", e);
            } finally {
                if (response != null) {
                    response.close();
                }
            }

            if (StringUtils.isNotBlank(purchaseStr)) {
                JSONObject jsonObject = JSON.parseObject(purchaseStr);
                if (jsonObject != null) {
                    purchaseDetailAimsDTOS = jsonObject.getObject("list", new TypeReference<List<PurchaseDetailAimsDTO>>() {
                    });
                    if (purchaseDetailAimsDTOS != null && purchaseDetailAimsDTOS.size() > 0) {
                        dcBasePurchaseDetailsMapper = SessionUtil.getSession().getMapper(DcBasePurchaseDetailsMapper.class);
                        try {
                            for(PurchaseDetailAimsDTO purchaseDetailAimsDTO : purchaseDetailAimsDTOS) {
                                dcBasePurchaseDetailsMapper.updateByBuyNo(purchaseDetailAimsDTO.getIsaims(), purchaseDetailAimsDTO.getPurchaseId());
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                            throw new RuntimeException("MYBATIS操作DB失败");
                        }finally {
                            SessionUtil.closeSession();
                        }
                    }
                }else {
                    throw new RuntimeException("调用采购单sku详细信息接口失败");
                }
            } else {
                throw new RuntimeException("调用采购单sku详细信息接口失败");
            }
            jobPointLog.setPageIndex(jobPointLog.getPageIndex() + 1);
        }while (jobPointLog.getPageIndex() <= totalPage);
        jobPointLog.setPageIndex(1);
        jobPointLog.setGmtModified(LocalDateTime.now());
        jobPointLog.setStartTime(jobPointLog.getEndTime());
        jobPointLog.setEndTime(jobPointLog.getStartTime().plusDays(jobPointLog.getIntervalTime().longValue()).isAfter(LocalDateTime.now()) ? LocalDateTime.now() : jobPointLog.getStartTime().plusDays(jobPointLog.getIntervalTime().longValue()));
    }
}
