package com.clx.performance.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.clx.performance.component.ThirdComponent;
import com.clx.performance.dao.OrderChildDao;
import com.clx.performance.dao.OrderChildSyncTransportInvoiceRecordDao;
import com.clx.performance.dao.settle.SettlementDriverDetailDao;
import com.clx.performance.dao.settle.SettlementOwnerDetailDao;
import com.clx.performance.dto.OrderChildSyncDTO;
import com.clx.performance.dto.OrderChildSyncResultDTO;
import com.clx.performance.enums.PerformanceResultEnum;
import com.clx.performance.enums.TransportSyncTypeEnum;
import com.clx.performance.enums.settle.SettlementOwnerEnum;
import com.clx.performance.feign.TransportFeignService;
import com.clx.performance.listener.OrderChildSyncTransportListener;
import com.clx.performance.model.OrderChild;
import com.clx.performance.model.OrderChildSyncTransportInvoiceRecord;
import com.clx.performance.model.settle.SettlementDriverDetail;
import com.clx.performance.model.settle.SettlementOwnerDetail;
import com.clx.performance.param.feign.transport.ThirdOrderChildRiskStatusParam;
import com.msl.common.result.Result;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;

@Slf4j
@Component
@AllArgsConstructor
public class OrderChildSyncTransportInvoiceExceptionJob {

    private final OrderChildSyncTransportInvoiceRecordDao orderChildSyncTransportInvoiceRecordDao;

    private final OrderChildSyncTransportListener orderChildPaySync;

    private final OrderChildDao orderChildDao;

    private final TransportFeignService transportFeignService;

    private final SettlementOwnerDetailDao settlementOwnerDetailDao;

    private final SettlementDriverDetailDao settlementDriverDetailDao;
    /**
     * 同步网络货运
     */
    @XxlJob("orderChildSyncTransportInvoiceExceptionJob")
    @Transactional(rollbackFor = Exception.class)
    public void orderChildSyncTransportInvoiceExceptionJob() {
        //只查询同步异常的网络货运任务
        List<OrderChildSyncTransportInvoiceRecord> recordList = orderChildSyncTransportInvoiceRecordDao.selectListForJob();
        if (CollectionUtil.isEmpty(recordList)) {
            return;
        }
        List<Integer> ids = new LinkedList<>();

        for (OrderChildSyncTransportInvoiceRecord record : recordList) {
            log.info("orderChildSyncTransportInvoiceExceptionJob执行：{}", JSONUtil.parse(record));
            if (record.getCreateTime().plusMinutes(10).isBefore(LocalDateTime.now())) {
                log.info("当前记录运单号:{},生成不足10分钟,先不执行", record.getChildNo());
                continue;
            }

            String data = transportFeignService.getRiskStatus(ThirdOrderChildRiskStatusParam.builder().childNo(record.getChildNo()).build()).getData();
            String decrypt = ThirdComponent.decrypt(data);
            Result result = JSONUtil.toBean(decrypt, Result.class);
            if (result.succeed()) {
                SettlementOwnerDetail settlementOwnerDetail = settlementOwnerDetailDao.getByChildNo(record.getChildNo()).orElseThrow(PerformanceResultEnum.DATA_NOT_FIND);
                SettlementDriverDetail settlementDriverDetail = settlementDriverDetailDao.getByChildNo(record.getChildNo()).orElseThrow(PerformanceResultEnum.DATA_NOT_FIND);

                JSON json = JSONUtil.parse(result.getData());
                Object status = json.getByPath("status");
                ids.add(record.getId());
                OrderChildSyncDTO bean = new OrderChildSyncDTO();
                bean.setCode(0);
                OrderChildSyncResultDTO dto = new OrderChildSyncResultDTO();
                OrderChild orderChild = orderChildDao.getByChildNo(record.getChildNo()).get();
                log.info("查询网络货运结果数据：{}", JSONUtil.parse(result));
                if (ObjectUtil.equal(status, 1)) {
                    dto.setStatus(1);
                    bean.setData(dto);
                    orderChildPaySync.extracted(orderChild, bean, "", settlementOwnerDetail,
                            SettlementOwnerEnum.InvoiceType.ONLINE.getCode(), settlementDriverDetail);
                } else if (ObjectUtil.equal(status, 0)){
                    dto.setStatus(2);
                    bean.setData(dto);
                    orderChildPaySync.extracted(orderChild, bean, "", settlementOwnerDetail,
                            SettlementOwnerEnum.InvoiceType.ORDINARY.getCode(), settlementDriverDetail);

                }else if (ObjectUtil.equal(status, 2)){
//                    orderChildPaySync.transportOrderChildProcess(orderChild);
                    dto.setStatus(2);
                    bean.setData(dto);
                    orderChildPaySync.extracted(orderChild, bean, "", settlementOwnerDetail,
                            SettlementOwnerEnum.InvoiceType.ORDINARY.getCode(), settlementDriverDetail);
                } else {
                    Object riskReason = json.getByPath("riskReason");
                    OrderChildSyncTransportInvoiceRecord entity = new OrderChildSyncTransportInvoiceRecord();
                    entity.setChildNo(json.getByPath("childNo").toString());
                    entity.setType(TransportSyncTypeEnum.Type.NO_PASS.getCode());
                    entity.setRemark(riskReason == null ? "" : riskReason.toString());
                    orderChildSyncTransportInvoiceRecordDao.saveEntity(entity);
                }
            }
        }

        orderChildSyncTransportInvoiceRecordDao.deleteByKeys(ids);
    }
}
