package com.xxfc.platform.order.jobhandler;

import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.xxfc.platform.order.biz.*;
import com.xxfc.platform.order.biz.inner.OrderMsgBiz;
import com.xxfc.platform.order.contant.enumerate.OrderStatusEnum;
import com.xxfc.platform.order.contant.enumerate.OrderTypeEnum;
import com.xxfc.platform.order.contant.enumerate.RefundStatusEnum;
import com.xxfc.platform.order.contant.enumerate.RefundTypeEnum;
import com.xxfc.platform.order.entity.BaseOrder;
import com.xxfc.platform.order.entity.OrderRentVehicleDetail;
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 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.List;
import java.util.Map;

import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_FALSE;
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::getRefundTime, System.currentTimeMillis() - (rentDepositAutoRefundTime * 60 * 1000))
//                                    .andLike(BaseOrder::getId, "%"+ i)
                            ).build());

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

                        OrderViolation orderViolation = orderViolationBiz.selectOne(new OrderViolation(){{
                            setDetailId(orvd.getId());
                            setIsDel(SYS_FALSE);
                        }});

                        //还车扣除款 剩余的 钱，再减去违章预备金
                        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());
                    }

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

}