package com.xxfc.platform.order.rest;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.admin.feign.dto.UserDTO;
import com.github.wxiaoqi.security.admin.feign.rest.UserRestInterface;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.github.wxiaoqi.security.common.util.AssertUtils;
import com.github.wxiaoqi.security.common.util.OrderUtil;
import com.github.wxiaoqi.security.common.util.Query;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.github.wxiaoqi.security.common.vo.PageParam;
import com.xxfc.platform.order.biz.OrderRentVehicleBiz;
import com.xxfc.platform.order.biz.SpecialRentBiz;
import com.xxfc.platform.order.entity.BaseOrder;
import com.xxfc.platform.order.entity.SpecialRent;
import com.xxfc.platform.order.mqhandler.RabbitProduct;
import com.xxfc.platform.order.pojo.order.RentVehicleBO;
import com.xxfc.platform.order.pojo.order.add.AddRentVehicleDTO;
import com.xxfc.platform.order.service.OrderRentVehicleService;
import com.xxfc.platform.vehicle.entity.Vehicle;
import com.xxfc.platform.vehicle.feign.VehicleFeign;
import com.xxfc.platform.vehicle.pojo.BookVehicleVO;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.mockito.internal.util.collections.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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.order.entity.SpecialRent.STATUS_CRT;
import static com.xxfc.platform.vehicle.entity.Vehicle.STATE_DOWN;

@RestController
@RequestMapping("specialRent")
public class SpecialRentController extends BaseController<SpecialRentBiz, SpecialRent> implements UserRestInterface {

    @Autowired
    RabbitProduct rabbitProduct;

    @Autowired
    OrderRentVehicleBiz orderRentVehicleBiz;

    @Autowired
    OrderRentVehicleService orderRentVehicleService;

    @Autowired
    VehicleFeign vehicleFeign;

    @Autowired
    UserFeign userFeign;

    @Override
    public UserFeign getUserFeign() {
        return userFeign;
    }

    @RequestMapping(value = "/appBusiness/addRent", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "添加特惠租车")
    public ObjectRestResponse appBusinessAddRent(@RequestBody SpecialRent specialRent) {
        UserDTO userDTO = getBusinessUserByAppUser();
        AssertUtils.isBlank(userDTO);

        if(StrUtil.isNotBlank(specialRent.getVehicleId())) {
            throw new BaseException(ResultCode.PARAM_ILLEGAL_CODE);
        }

        Vehicle vehicle = vehicleFeign.get(specialRent.getVehicleId()).getData();

        if(null == vehicle) {
            throw new BaseException(ResultCode.PARAM_ILLEGAL_CODE);
        }

        //判断车辆是否下架、是否已经存在一个特惠租车
        if(STATE_DOWN == vehicle.getStatus() || baseBiz.checkHasSpecialRent(vehicle.getId())) {
            throw new BaseException(ResultCode.PARAM_ILLEGAL_CODE);
        }

        specialRent.setGoodsJson(JSONUtil.parse(vehicle).toString());

        DateTime startDateTime = DateUtil.date(specialRent.getStartTime());
//        DateTime endDateTime = DateUtil.date(specialRent.getEndTime());
//        DateTime tomorrowBegin = DateUtil.beginOfDay(DateUtil.tomorrow());
        DateTime afterDateTime = DateUtil.offsetHour(DateUtil.date(), 1);

        if(!startDateTime.isAfterOrEquals(afterDateTime)) {
            throw new BaseException(ResultCode.FAILED_CODE, Sets.newSet("请提前一小时特惠租车发布"));
        }

        if(null != specialRent.getStartCompanyId()) {
            specialRent.setStartCityCode(vehicleFeign.getCompanyDetail(specialRent.getStartCompanyId()).getData().getAddrCity());
        }
        if(null != specialRent.getEndCompanyId()) {
            specialRent.setEndCityCode(vehicleFeign.getCompanyDetail(specialRent.getEndCompanyId()).getData().getAddrCity());
        }

        specialRent.setPublishUserId(userDTO.getId());
        specialRent.setStatus(STATUS_CRT);

        RentVehicleBO detail = new RentVehicleBO();
        detail.setStartTime(specialRent.getStartTime());
        detail.setEndTime(specialRent.getEndTime());
        detail.setVehicleId(specialRent.getVehicleId());
        detail.setStartAddr(specialRent.getStartCompanyName());
        detail.setStartCompanyId(specialRent.getStartCompanyId());
        detail.setEndCompanyId(specialRent.getEndCompanyId());
        detail.setOrder(new BaseOrder(){{setNo(OrderUtil.GetOrderNumber("", OrderUtil.APP_MID));}});
        detail.setRentFreeDay(SYS_FALSE);
        detail.setBookVehicleVO(new BookVehicleVO(){{
            setBookStartDate(DateUtil.date(specialRent.getStartTime()).toDateStr());
            setBookEndDate(DateUtil.date(specialRent.getEndTime()).toDateStr());
            setBookStartDateTime(DateUtil.date(specialRent.getStartTime()).toString());
            setBookEndDateTime(DateUtil.date(specialRent.getEndTime()).toString());
        }});

        //预约车辆
        orderRentVehicleService.acquireVehicle(detail, null , null);

        specialRent.setOrderNo(detail.getOrder().getNo());
//        specialRent.setOverTime(DateUtil.offsetHour(DateUtil.date(), 1).getTime());
        specialRent.setBookRecordId(detail.getBookRecordId());
        //设置车辆下架
        ObjectRestResponse restResponse = vehicleFeign.updVehicleFeign(new Vehicle(){{
            setId(vehicle.getId());
            setStatus(STATE_DOWN);
        }});
//        rabbitProduct.sendApplyDelayMessage(baseBiz.selectById(specialRent.getId()), 1000L * 3601L);

//        Long delayTime = DateUtil.date().getTime() - DateUtil.offsetDay(endDateTime, -1).getTime();
//        specialRent.setOverTime(delayTime);
        baseBiz.insertSelective(specialRent);
//        rabbitProduct.sendApplyRequireDelayMessage(baseBiz.selectById(shuntApply.getId()), delayTime);

        return ObjectRestResponse.succ();
    }

    @RequestMapping(value = "/pageList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "分页查询可参加特惠租车")
    public ObjectRestResponse<SpecialRentVO> pageList(QueryDTO dto) {
        //查询列表数据
        if (StrUtil.isBlank(getCurrentUserId())) {
            throw new BaseException(ResultCode.AJAX_WECHAT_NOTEXIST_CODE);
        }
        dto.setUserId(getCurrentUserIdInt());
        Query query = new Query(dto);
        PageDataVO<SpecialRentVO> pages = PageDataVO.pageInfo(query, () -> baseBiz.selectByWeekend(w -> {
            w.andEqualTo(SpecialRent::getStatus, STATUS_CRT);
            return w;
        }, " crt_time desc "), SpecialRentVO.class);

        return ObjectRestResponse.succ(pages);
    }

    @RequestMapping(value = "/specialOrder", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "特惠租车下单")
    public ObjectRestResponse specialOrder(@RequestBody SpecialOrderDTO dto) {

        //查询列表数据
        if (StrUtil.isBlank(getCurrentUserId())) {
            throw new BaseException(ResultCode.AJAX_WECHAT_NOTEXIST_CODE);
        }

        if(null == dto.getSpecialId()) {
            throw new BaseException(ResultCode.PARAM_ILLEGAL_CODE);
        }

        SpecialRent specialRent = baseBiz.selectById(dto.getSpecialId());
        if(null == specialRent) {
            throw new BaseException(ResultCode.PARAM_ILLEGAL_CODE);
        }

        if(
                !(DateUtil.date(dto.getStartTime()).isAfterOrEquals(DateUtil.date(specialRent.getStartTime()))
                && DateUtil.date(dto.getEndTime()).isBeforeOrEquals(DateUtil.date(specialRent.getEndTime())))
        ) {
            throw new BaseException(ResultCode.PARAM_ILLEGAL_CODE);
        }
        if(SpecialRent.STATUS_ORDER == specialRent.getStatus()) {
            throw new BaseException("该特惠租车已下单", ResultCode.PARAM_ILLEGAL_CODE);
        }

        //拒绝原来的预约
        orderRentVehicleService.errorRejectVehicle(new RentVehicleBO(){{
            setBookRecordId(specialRent.getBookRecordId());
        }});

        //正式下单
        dto.setVehicleId(specialRent.getVehicleId());
        dto.setStartTime(specialRent.getStartTime());
        dto.setEndTime(specialRent.getEndTime());
        dto.setStartCompanyId(specialRent.getStartCompanyId());
        dto.setEndCompanyId(specialRent.getEndCompanyId());
        RentVehicleBO bo = orderRentVehicleBiz.initRentVehicleBO(dto);
//        bo.setSpecialOrderSign(SYS_TRUE);
        bo.setAppUserDTO(getAppUser());
//        orderRentVehicleService.applyCreateOrder(bo, specialRent.getOrderNo());
        orderRentVehicleService.createOrder(bo);
        baseBiz.updateSelectiveById(new SpecialRent(){{
            setId(specialRent.getId());
            setStatus(SpecialRent.STATUS_ORDER);
            setOrderStatus(SpecialRent.ORDER_STATUS_TOPAY);
        }});
        return ObjectRestResponse.succ(bo.getOrder());
    }


    @RequestMapping(value = "/app/unauth/checkHasSpecialRentFegin", method = RequestMethod.GET)
    @ResponseBody
    @IgnoreUserToken
    @ApiOperation(value = "判断车辆是否有进行中的特惠租车")
    public ObjectRestResponse checkHasSpecialRent(String vehicleId) {
        return ObjectRestResponse.succ(baseBiz.checkHasSpecialRent(vehicleId));
    }

    @Data
    public static class SpecialRentVO extends SpecialRent{
        Vehicle vehicle;

    }

    @Data
    public static class QueryDTO extends PageParam {
        Integer userId;
    }

    @Data
    public static class SpecialOrderDTO extends AddRentVehicleDTO {
        Integer specialId;
    }
}