package com.bohuikeji.delivery.backstage.task;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bohuikeji.delivery.backstage.entity.TCourierSaveDetail;
import com.bohuikeji.delivery.backstage.mapper.TCourierSaveDetailMapper;
import com.bohuikeji.delivery.backstage.service.ITCourierWithdrawService;
import com.bohuikeji.delivery.backstage.service.impl.TCourierSaveDetailServiceImpl;
import com.bohuikeji.frame.module.admin.task.Task;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import com.bohuikeji.frame.module.admin.utils.TaskUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * 骑手保险，保单核查任务类
 * @author MasterBoot
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class CourierSaveTask implements Task {

    /**
     * 支付超时时间（min）
     */
    public static final int PAY_TIME_OUT=10;

    /**
     * 数据库处理MAPPER
     */
    private final TCourierSaveDetailMapper detailMapper;
    /**
     * 提现处理业务类
     */
    private final ITCourierWithdrawService withdrawService;
    /**
     * 保单核查地址
     */
    private static final String URL="http://t.c.tdbxjj.com/api/pip-core-engine/issuing/TB101003";

    /**
     * 订单号参数key
     */
    public static final String KEY_NO="proposalNo";

    @Override
    public long delayTime() {
        return 10000;
    }

    @Override
    public void runTask(HashMap<String,Object> params) {
        String proposalNo=(String) params.get(KEY_NO);
        if (StringUtils.isBlank(proposalNo)){
            log.error("【骑手保单核查任务异常】投保单号参数为空！");
            return;
        }
        //更具投保单号插叙投保详情
        List<TCourierSaveDetail> list=detailMapper.selectList(new QueryWrapper<TCourierSaveDetail>().eq("proposal_no",proposalNo));
        if (list==null||list.size()<1){
            log.error("【骑手保单核查任务异常】无法找到投保单号=[{}]的订单。",proposalNo);
            return;
        }
        TCourierSaveDetail saveDetail=list.get(0);
        if ("投保成功".equals(saveDetail.getStatus())&&(StringUtils.isNotBlank(saveDetail.getInsuredNumber()))){
            log.info("【骑手保单核查任务结束】保单信息=[{}]",saveDetail);
            return;
        }
        JSONObject result= TCourierSaveDetailServiceImpl.checkInsure(proposalNo);
        if (result!=null){
            saveDetail.setPdfUrl(result.getString("epolicy"));
            saveDetail.setInsuredNumber(result.getString("policyNo"));
            saveDetail.setCourierPayChannel("平安保险");
            saveDetail.setStatus("投保成功");
            saveDetail.setInsuredPremium(new BigDecimal("5.00"));
            detailMapper.updateById(saveDetail);
            //直接发放补贴金额
            withdrawService.sendToAliPay("发放保险补贴金",new BigDecimal("3.00"),saveDetail.getCourierId());
            return;
        }
        //其他情况皆视为投保失败
        log.error("【投保等待中】当前时间：{}，投保单号：{}，投保人：{}",
                LocalDateTime.now().format(StringUtils.dataTimeFormat),saveDetail.getProposalNo(),saveDetail.getCourierName());
        //等待10分钟，10分钟之内都放入延时队列继续轮询
        Duration duration=Duration.between(saveDetail.getGmtCreate(),LocalDateTime.now());
        if (duration.toMinutes()<PAY_TIME_OUT) {
            TaskUtils.add(this,duration.toMillis()-delayTime()).addParam(KEY_NO,proposalNo);
            return;
        }
        saveDetail.setStatus("支付超时");
        detailMapper.updateById(saveDetail);
    }
}
