package com.xxfc.platform.order.rest;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreClientToken;
import com.github.wxiaoqi.security.common.context.BaseContextHandler;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.CommonBaseController;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.xxfc.platform.order.biz.BaseOrderBiz;
import com.xxfc.platform.order.biz.OrderRentVehicleBiz;
import com.xxfc.platform.order.biz.inner.OrderCalculateBiz;
import com.xxfc.platform.order.entity.BaseOrder;
import com.xxfc.platform.order.entity.OrderRentVehicleDetail;
import com.xxfc.platform.order.pojo.order.RentVehicleBO;
import com.xxfc.platform.order.pojo.order.add.AddRentVehicleDTO;
import com.xxfc.platform.order.pojo.order.add.BgAddRentDTO;
import com.xxfc.platform.order.pojo.price.RentVehiclePriceVO;
import com.xxfc.platform.order.service.OrderRentVehicleService;
import com.xxfc.platform.universal.feign.ThirdFeign;
import com.xxfc.platform.vehicle.entity.BranchCompany;
import com.xxfc.platform.vehicle.feign.VehicleFeign;
import com.xxfc.platform.vehicle.pojo.BookVehicleVO;
import com.xxfc.platform.vehicle.pojo.CompanyDetail;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.mockito.internal.util.collections.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("orderRentVehicle")
@Api(value="租车订单",tags={"租车订单"})
@IgnoreClientToken
@Slf4j
public class OrderRentVehicleController extends CommonBaseController {

        @Autowired
        OrderRentVehicleService orderRentVehicleService;

        @Autowired
        OrderRentVehicleBiz orderRentVehicleBiz;

        @Autowired
        BaseOrderBiz baseOrderBiz;

        @Autowired
        UserFeign userFeign;

        @Autowired
        VehicleFeign vehicleFeign;

        @Autowired
        ThirdFeign thirdFeign;

        @Autowired
        OrderCalculateBiz orderCalculateBiz;

        @RequestMapping(value = "add",method = RequestMethod.POST)
        @ResponseBody
        @ApiOperation(value = "确认租车订单")
        public ObjectRestResponse<BaseOrder> add(@RequestBody AddRentVehicleDTO vo){
            RentVehicleBO bo = initRentVehicleBO(vo);
            bo.setAppUserDTO(userFeign.userDetailByToken(BaseContextHandler.getToken()).getData());
            orderRentVehicleService.createOrder(bo);
            return ObjectRestResponse.succ(bo.getOrder());
//                return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE, "系统维护，请联系客服线下租车: 4000-369-369！");
        }

        @RequestMapping(value = "back-stage/add",method = RequestMethod.POST)
        @ResponseBody
        @ApiOperation(value = "后台人员为客户下租车订单")
        public ObjectRestResponse<BaseOrder> backStagedd(@RequestBody BgAddRentDTO dto){
                RentVehicleBO bo = initRentVehicleBO(dto);

                bo.setAppUserDTO(userFeign.userDetailById(dto.getAppUserId()).getData());
                bo.setCrtUser("-1"+ BaseContextHandler.getUserID());
                //设置-1表示查询所有的车
                //bo.setUseType(-1);
                orderRentVehicleService.createOrder(bo);
                return ObjectRestResponse.succ(bo.getOrder());
        }

        private RentVehicleBO initRentVehicleBO(@RequestBody AddRentVehicleDTO vo) {
                //计算天数
                vo.setDayNum(orderCalculateBiz.getIncludeDays(vo.getStartTime(), vo.getEndTime()));

                if(null == vo.getEndCompanyId() || vo.getEndCompanyId().equals(0)) {
                    if(StrUtil.isBlank(vo.getEndAddr())) {
                            throw new BaseException(ResultCode.PARAM_ILLEGAL_CODE, Sets.newSet("公司参数不正确"));
                    }else {
                            Map<String, Object> map = BeanUtil.beanToMap(new BranchCompany(){{
                                    setName(vo.getEndAddr());
                            }}, false, true);
                            List<BranchCompany> data = vehicleFeign.branchCompanyEntityList(map).getData();
                            if(null == data) {
                                    throw new BaseException(ResultCode.PARAM_ILLEGAL_CODE, Sets.newSet("公司参数不正确"));
                            }else {
                                    BranchCompany endCompany = vehicleFeign.branchCompanyEntityList(map).getData().get(0);
                                    vo.setEndCompanyId(endCompany.getId());
                            }
                    }
                }
                if(vo.getStartCompanyId() != null) {
                        CompanyDetail companyDetail = vehicleFeign.getCompanyDetail(vo.getStartCompanyId()).getData();
                        if(companyDetail != null) {
                                vo.setStartAddr(companyDetail.detailAddr());
                        }
                }
                if(vo.getEndCompanyId() != null) {
                        CompanyDetail companyDetail = vehicleFeign.getCompanyDetail(vo.getEndCompanyId()).getData();
                        if(companyDetail != null) {
                                vo.setEndAddr(companyDetail.detailAddr());
                        }
                }
                RentVehicleBO bo = BeanUtil.toBean(vo, RentVehicleBO.class);
                bo.setBookVehicleVO(new BookVehicleVO(){{
                        setBookStartDate(vo.getBookStartDate());
                        setBookEndDate(vo.getBookEndDate());
                        setBookStartDateTime(vo.getBookStartDateTime());
                        setBookEndDateTime(vo.getBookEndDateTime());
                }});
                bo.setTickerNo(StrUtil.isNotBlank(vo.getTickerNos())?
                        StrUtil.splitTrim(vo.getTickerNos(), ","):null);
                bo.setAccompanyItems(vo.getAccompanyItems());
                return bo;
        }

        @RequestMapping(value = "list-by-order/{orderId}",method = RequestMethod.GET)
        @ResponseBody
        @ApiOperation(value = "租车列表by订单Id")
        public ObjectRestResponse<OrderRentVehicleDetail> listByOrder(@PathVariable("orderId") Integer orderId){
                return ObjectRestResponse.succ(orderRentVehicleBiz.listByOrderId(orderId));
        }

        @RequestMapping(value = "/calculate-price",method = RequestMethod.GET)
        @ResponseBody
        @ApiOperation(value = "价格计算")
        public ObjectRestResponse<RentVehiclePriceVO> calculatePrice(CalculatePriceVO vo){
                RentVehicleBO bo = BeanUtil.toBean(vo, RentVehicleBO.class);
                if(StrUtil.isNotBlank(BaseContextHandler.getToken())) {
                        bo.setAppUserDTO(userFeign.userDetailByToken(BaseContextHandler.getToken()).getData());
                }
                bo.setOrder(new BaseOrder(){{
                        setHasMemberRight(vo.getHasMemberRight());
                }});
                bo.setAppUserDTO(userFeign.userDetailByToken(BaseContextHandler.getToken()).getData());
                bo.setTickerNo(StrUtil.isNotBlank(vo.getTickerNos())? Arrays.asList(vo.getTickerNos().split(",")):null);
                bo.setDayNum(orderCalculateBiz.getIncludeDays(vo.getStartTime(), vo.getEndTime()));
                orderRentVehicleService.initDetailSecond(bo);
                return ObjectRestResponse.succ(orderRentVehicleService.calculatePrice(bo));
        }

        @Data
        public class CalculatePriceVO {
                @ApiModelProperty(value = "司机类型 1--公司司机；2--自己司机")
                private Integer driverType;

                @ApiModelProperty(value = "车型id")
                private Integer modelId;

                //开始时间
                @ApiModelProperty(value = "开始时间")
                private Long startTime;

                //结束时间
                @ApiModelProperty(value = "结束时间")
                private Long endTime;

                @ApiModelProperty(value = "天数")
                private Integer dayNum;

                //是否购买免赔
                @ApiModelProperty(value = "是否购买免赔 1--是")
                private Integer damageSafe;

                /**
                 *  是否有使用会员权益
                 */
                @ApiModelProperty(value = "是否有使用会员权益")
                private Integer hasMemberRight;

                /**
                 * 是否使用出租免费天数
                 */
                @ApiModelProperty(value = "是否使用出租免费天数")
                private Integer rentFreeDay;

                /**
                 * 优惠券*
                 */
                @ApiModelProperty(value = "优惠卷卷号")
                private String tickerNos;
        }
}