package com.tourism.webadmin.app.website.controller;

import com.github.pagehelper.page.PageMethod;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.tourism.common.additional.config.ApplicationConfig;
import com.tourism.common.additional.utils.UrlConvertUtils;
import com.tourism.common.core.annotation.DisableDataFilter;
import com.tourism.common.core.constant.ErrorCodeEnum;
import com.tourism.common.core.object.*;
import com.tourism.common.core.util.MyCommonUtil;
import com.tourism.common.core.util.MyModelUtil;
import com.tourism.common.core.util.MyPageUtil;
import com.tourism.common.log.annotation.OperationLog;
import com.tourism.common.log.model.constant.SysOperationLogType;
import com.tourism.webadmin.app.website.dto.TourCarOrderToWebDto;
import com.tourism.webadmin.back.dto.TourCarOrderDto;
import com.tourism.webadmin.back.model.TourCarCategory;
import com.tourism.webadmin.back.model.TourCarDriver;
import com.tourism.webadmin.back.model.TourCarOrder;
import com.tourism.webadmin.back.model.constant.TourCarOrderState;
import com.tourism.webadmin.back.model.constant.TourCarType;
import com.tourism.webadmin.back.service.TourCarCategoryService;
import com.tourism.webadmin.back.service.TourCarDriverService;
import com.tourism.webadmin.back.service.TourCarOrderService;
import com.tourism.webadmin.back.util.QueryConditionProccessUtils;
import com.tourism.webadmin.back.util.TourBillNoUtils;
import com.tourism.webadmin.back.vo.TourCarOrderVo;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * 包车订单操作控制器类。
 *
 * @author 吃饭睡觉
 * @date 2024-09-06
 */
@Tag(name = "门户包车订单相关接口")
@Slf4j
@RestController
@DisableDataFilter
@RequestMapping("/website/app/tourCarOrder")
public class WebsiteCarOrderController {

    @Autowired
    private TourCarOrderService tourCarOrderService;
    @Autowired
    private TourCarCategoryService tourCarCategoryService;
    @Autowired
    private TourCarDriverService tourCarDriverService;
    @Autowired
    private ApplicationConfig config;

    /**
     * 新增包车订单数据。
     *
     * @param tourCarOrderDto 新增对象。
     * @return 应答结果对象，包含新增对象主键Id。
     */
    @ApiOperationSupport(ignoreParameters = {
            "tourCarOrderDto.id",
            "tourCarOrderDto.searchString",
            "tourCarOrderDto.startTimeStart",
            "tourCarOrderDto.startTimeEnd",
            "tourCarOrderDto.endTimeStart",
            "tourCarOrderDto.endTimeEnd"})
    @OperationLog(type = SysOperationLogType.ADD)
    @PostMapping("/add")
    public ResponseResult<Long> add(@RequestBody TourCarOrderDto tourCarOrderDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(tourCarOrderDto, false);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }

        TourCarOrder tourCarOrder = MyModelUtil.copyTo(tourCarOrderDto, TourCarOrder.class);
        // 处理订单结束时间
        tourCarOrder.setEndTime(QueryConditionProccessUtils.getEndDate(tourCarOrderDto.getStartTime(), tourCarOrderDto.getDays()));
        // 判断司机是否被其他订单占用
        boolean b = tourCarOrderService.verifyDriverOrder(tourCarOrder);
        if (b){
            return ResponseResult.error(ErrorCodeEnum.TOUR_ORDER_DRIVER_ALREADY_INORDER);
        }
        // 生成订单号
        tourCarOrder.setOrderNo(TourBillNoUtils.generateBillNo());
        // 下单状态
        tourCarOrder.setState(TourCarOrderState.PLACED_ORDER);
        // 查询车辆信息，冗余到订单内
        TourCarCategory carCategory = tourCarCategoryService.getById(tourCarOrder.getCategoryId());
        tourCarOrder.setCarModel(carCategory.getModel());
        tourCarOrder.setCarImage(UrlConvertUtils.urlConvertSingle(config.getHostIpPort(), carCategory.getImage()));
        tourCarOrder.setCarName(carCategory.getName());
        tourCarOrder.setCarSeatNumber(carCategory.getSeatNumber());
        tourCarOrder.setCarLuggageNumber(carCategory.getLuggageNumber());
        // 设置订单归属（自营OR三方个人） 计算订单价格
        tourCarOrder.setDayPrice(carCategory.getPrice());
        tourCarOrder.setTotalPrice(carCategory.getPrice().multiply(BigDecimal.valueOf(tourCarOrder.getDays())));
        tourCarOrder.setCategoryType(carCategory.getType());
        tourCarOrder.setDayPriceUnit(carCategory.getUnit());
        tourCarOrder.setTotalPriceUnit(carCategory.getUnit());

        // 查询司机信息，冗余到订单内
        TourCarDriver carDriver = tourCarDriverService.getById(tourCarOrder.getDriverId());
        tourCarOrder.setDriverAge(carDriver.getAge());
        tourCarOrder.setDriverSex(carDriver.getSex());
        tourCarOrder.setDriverName(carDriver.getName());
        tourCarOrder.setDrivingYears(carDriver.getDrivingYears());
        tourCarOrder.setDriverImage(UrlConvertUtils.urlConvertSingle(config.getHostIpPort(), carDriver.getImage()));
        tourCarOrder.setDriverMobile(carDriver.getMobile());
        tourCarOrder.setDriverDeptId(carDriver.getDeptId());
        tourCarOrder.setDriverSysId(carDriver.getCreateUserId());

        // 判断车型和司机是否是同一个运营商，自营、第三方
        if(carCategory.getType() == carDriver.getType()) {
            // 如果车型和司机都是第三方，判断司机和车是否匹配
            if(carCategory.getType() == TourCarType.THIRD_PARTY_INDIVIDUAL){
                if(carCategory.getRelationDriverId().longValue() == carDriver.getId().longValue()) {
                    // 匹配成功
                } else {
                    // 匹配失败
                    return ResponseResult.error(ErrorCodeEnum.TOUR_ORDER_DRIVER_ERROR);
                }
            }
        }else {
            // 车型和司机不匹配
            return ResponseResult.error(ErrorCodeEnum.TOUR_ORDER_TYPE_ERROR);
        }

        // 验证关联Id的数据合法性
        CallResult callResult = tourCarOrderService.verifyRelatedData(tourCarOrder, null);
        if (!callResult.isSuccess()) {
            return ResponseResult.errorFrom(callResult);
        }
        tourCarOrder = tourCarOrderService.saveNew(tourCarOrder);
        return ResponseResult.success(tourCarOrder.getId());
    }

    /**
     * 包车订单列表接口。
     *
     * @param filter 过滤对象。
     * @return 应答结果对象，包含查询结果集。
     */
    @GetMapping("/list")
    public ResponseResult<MyPageData<TourCarOrderVo>> list(TourCarOrderToWebDto filter) {
        if (filter != null) {
            PageMethod.startPage(filter.getPageNum(), filter.getPageSize(), filter.getCount());
        }
        TourCarOrder tourCarOrderFilter = MyModelUtil.copyTo(filter, TourCarOrder.class);
        // 根据当前登录人查询订单列表
        tourCarOrderFilter.setCreateUserId(TokenData.takeFromRequest().getUserId());

        // 根据创建时间倒序排列
        MyOrderParam myOrderParam = new MyOrderParam();
        myOrderParam.add(new MyOrderParam.OrderInfo("createTime", false, null));
        String orderBy = MyOrderParam.buildOrderBy(myOrderParam, TourCarOrder.class);
        List<TourCarOrder> tourCarOrderList =
                tourCarOrderService.getTourCarOrderListWithRelation(tourCarOrderFilter, null, null, orderBy);
        return ResponseResult.success(MyPageUtil.makeResponseData(tourCarOrderList, TourCarOrderVo.class));
    }

    /**
     * 查看包车订单对象详情。
     *
     * @param id 指定对象主键Id。
     * @return 应答结果对象，包含对象详情。
     */
    @GetMapping("/view")
    public ResponseResult<TourCarOrderVo> view(@RequestParam Long id) {
        // 先判断是不是当前人订单，否则不允许访问订单详情
        TourCarOrder tourCarOrder = tourCarOrderService.getByIdWithRelation(id, MyRelationParam.full());
        if(!tourCarOrder.getCreateUserId().equals(TokenData.takeFromRequest().getUserId())) {
            return ResponseResult.error(ErrorCodeEnum.TOUR_ORDER_NO_PERMISSON);
        }
        if (tourCarOrder == null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        // 图片URL转换
        TourCarOrderVo tourCarOrderVo = MyModelUtil.copyTo(tourCarOrder, TourCarOrderVo.class);
        return ResponseResult.success(tourCarOrderVo);
    }

    /**
     * 打分接口。
     *
     * @param tourCarOrderDto 更新对象。
     * @return 应答结果对象。
     */
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/markOrder")
    public ResponseResult<Void> update(@RequestBody TourCarOrderDto tourCarOrderDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(tourCarOrderDto, true);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        TourCarOrder tourCarOrder = MyModelUtil.copyTo(tourCarOrderDto, TourCarOrder.class);
        TourCarOrder originalTourCarOrder = tourCarOrderService.getById(tourCarOrder.getId());
        if (originalTourCarOrder == null) {
            // NOTE: 修改下面方括号中的话述
            errorMessage = "数据验证失败，当前订单并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        // 验证关联Id的数据合法性
        CallResult callResult = tourCarOrderService.verifyRelatedData(tourCarOrder, originalTourCarOrder);
        if (!callResult.isSuccess()) {
            return ResponseResult.errorFrom(callResult);
        }
        // 状态改为已评分
        tourCarOrder.setMarking(1);
        tourCarOrderService.updateById(tourCarOrder);
        return ResponseResult.success();
    }
}
