package com.xxfc.platform.order.jobhandler;

import cn.hutool.core.date.DateUtil;
import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.google.common.collect.Lists;
import com.xxfc.platform.order.biz.*;
import com.xxfc.platform.order.biz.inner.OrderMsgBiz;
import com.xxfc.platform.order.contant.enumerate.*;
import com.xxfc.platform.order.entity.BaseOrder;
import com.xxfc.platform.order.entity.OrderRentVehicleDetail;
import com.xxfc.platform.order.entity.OrderVehicleCrosstown;
import com.xxfc.platform.order.entity.OrderViolation;
import com.xxfc.platform.universal.constant.DictionaryKey;
import com.xxfc.platform.universal.entity.Dictionary;
import com.xxfc.platform.universal.feign.ThirdFeign;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.weekend.WeekendSqls;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_FALSE;
import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_TRUE;
import static com.xxfc.platform.universal.constant.DictionaryKey.APP_ORDER;

/**
 * 跨平台Http任务
 *
 * @author xuxueli 2018-09-16 03:48:34
 */
@JobHandler(value = "rentDepositHandler")
@Component
@Slf4j
public class RentDepositJobHandler extends IJobHandler {

    @Autowired
    BaseOrderBiz baseOrderBiz;

    @Autowired
    OrderRentVehicleBiz orderRentVehicleBiz;

    @Autowired
    OrderVehicleCrosstownBiz crosstownBiz;

    @Autowired
    OrderViolationBiz orderViolationBiz;

    @Autowired
    OrderRefundBiz orderRefundBiz;

    @Autowired
    OrderMsgBiz orderMsgBiz;

    @Autowired
    ThirdFeign thirdFeign;

    @Autowired
    UserFeign userFeign;

    @Override
    public ReturnT<String> execute(String idLastNumInterval) throws Exception {
        Map<String, Dictionary> dictionaryMap = thirdFeign.dictionaryGetAll4Map().getData();
        Integer rentDepositAutoRefundTime = new Integer(dictionaryMap.get(APP_ORDER+ "_"+ DictionaryKey.RENT_DEPOSIT_AUTO_REFUND_TIME).getDetail());

        try {
//            for(int i = 0; i < 10; i++) {
//                if(IntervalUtil.staticIsInTheInterval(String.valueOf(i), idLastNumInterval)) {
                    //三十天
                    List<BaseOrder> lists = baseOrderBiz.selectByExample(new Example.Builder(BaseOrder.class)
                            //订单已完成的租车订单
                            .where(WeekendSqls.<BaseOrder>custom().andEqualTo(BaseOrder::getType, OrderTypeEnum.RENT_VEHICLE)
                                    .andEqualTo(BaseOrder::getStatus, OrderStatusEnum.ORDER_FINISH) //已完成的订单
                                    .andEqualTo(BaseOrder::getRefundStatus, RefundStatusEnum.RESIDUE_ILLEGAL) //已归还了部分押金
                                    .andLessThanOrEqualTo(BaseOrder::getCrtTime, DateUtil.date(System.currentTimeMillis() - (rentDepositAutoRefundTime * 60 * 1000)))
//                                    .andLike(BaseOrder::getId, "%"+ i)
                            ).build());

                    //处理自动退剩余押金
                    for(BaseOrder baseOrder : lists) {
                        OrderRentVehicleDetail orvd = orderRentVehicleBiz.selectOne(new OrderRentVehicleDetail() {{
                            setOrderId(baseOrder.getId());
                        }});

                        Integer crosstownTypeEnum;
                        //判断是否定损过
                        if(SYS_TRUE.equals(orvd.getFixedLossStatus())) {
                            crosstownTypeEnum = CrosstownTypeEnum.FIXED_LOSS.getCode();
                        }else {
                            crosstownTypeEnum = CrosstownTypeEnum.ARRIVE.getCode();
                        }
                        OrderVehicleCrosstown crosstown = crosstownBiz.selectOne(new OrderVehicleCrosstown(){{
                            setOrderId(baseOrder.getId());
                            setType(crosstownTypeEnum);
                        }});

                        if(crosstown.getCrtTime().compareTo(System.currentTimeMillis() - (rentDepositAutoRefundTime * 60 * 1000)) < 0) {
                            OrderViolation orderViolation = orderViolationBiz.selectOne(new OrderViolation(){{
                                setDetailId(orvd.getId());
                                setIsDel(SYS_FALSE);
                            }});

                            if(null != orderViolation) {
                                //还车扣除款 剩余的 钱，再减去违章预备金
                                BigDecimal refundAmont = orvd.getReturnPayResidue().subtract(orderViolation.getPrice());
                                String refundDesc = "退还押金："+ refundAmont.toString()+ "(已扣除 违章扣款："+ refundAmont.toString();
                                refundDesc += ")";
                                orderRefundBiz.refundTrigger(baseOrder, orvd, BigDecimal.ZERO, orvd.getReturnPayResidue(), refundAmont, refundDesc, RefundStatusEnum.REFUND_DEPOSIT.getCode(), RefundTypeEnum.RESIDUE_DEPOSIT);
                                orderMsgBiz.handelMsgDeposit(orvd, baseOrder, userFeign.userDetailById(baseOrder.getUserId()).getData());
                            }
                        }

                        //获取交车时间
//                        List<OrderVehicleCrosstown> crosstowns = crosstownBiz.selectByExample(
//                                new Example.Builder(BaseOrder.class)
//                                        .where(WeekendSqls.<OrderVehicleCrosstown>custom()
//                                                .andIn(OrderVehicleCrosstown::getType, Lists.newArrayList(CrosstownTypeEnum.ARRIVE.getCode(), CrosstownTypeEnum.FIXED_LOSS.getCode()))
//                                                .andEqualTo(OrderVehicleCrosstown::getOrderId, baseOrder.getId())).build());

                    }

//                }
//            }
            ReturnT returnT = new ReturnT();
            returnT.setCode(100);
            returnT.setMsg("成功");
            returnT.setContent(idLastNumInterval);
            return returnT;
        } catch (Exception e) {
            XxlJobLogger.log(e);
            return FAIL;
        } finally {
            ;
        }
    }

}