package com.xxfc.platform.order.rest;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.wxiaoqi.security.admin.entity.AppUserLogin;
import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.admin.feign.dto.UserDTO;
import com.github.wxiaoqi.security.admin.feign.rest.UserRestInterface;
import com.github.wxiaoqi.security.admin.vo.AppUserVo;
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.AssertUtils;
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.google.common.collect.Lists;
import com.xxfc.platform.activity.entity.Coupon;
import com.xxfc.platform.activity.feign.ActivityFeign;
import com.xxfc.platform.order.biz.*;
import com.xxfc.platform.order.biz.inner.OrderCalculateBiz;
import com.xxfc.platform.order.biz.inner.OrderDelayBiz;
import com.xxfc.platform.order.contant.enumerate.ItemTypeEnum;
import com.xxfc.platform.order.contant.enumerate.OrderTypeEnum;
import com.xxfc.platform.order.entity.OrderItem;
import com.xxfc.platform.order.entity.OrderRentVehicleDetail;
import com.xxfc.platform.order.pojo.OrderAccompanyDTO;
import com.xxfc.platform.order.pojo.order.*;
import com.xxfc.platform.order.pojo.price.RentVehiclePriceVO;
import com.xxfc.platform.order.service.OrderRentVehicleService;
import com.xxfc.platform.tour.entity.TourUser;
import com.xxfc.platform.tour.feign.TourFeign;
import com.xxfc.platform.universal.feign.ThirdFeign;
import com.xxfc.platform.vehicle.common.RestResponse;
import com.xxfc.platform.vehicle.constant.VehicleBookRecordStatus;
import com.xxfc.platform.vehicle.entity.BranchCompany;
import com.xxfc.platform.vehicle.entity.Vehicle;
import com.xxfc.platform.vehicle.entity.VehicleUserLicense;
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.ApiOperation;
import jodd.util.StringUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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 javax.annotation.Resource;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

import static com.github.wxiaoqi.security.common.constant.CommonConstants.DATE_TIME_LINE_FORMATTER;
import static com.github.wxiaoqi.security.common.constant.CommonConstants.YMR_SLASH_FORMATTER;

@Controller
@RequestMapping("/chw/appOrder")
@Api(value = "订单后台相关", tags = {"订单后台相关"})
@Slf4j
public class AppOrderController extends CommonBaseController implements UserRestInterface {

    @Autowired
    UserFeign userFeign;

    @Autowired
    VehicleFeign vehicleFeign;

    @Autowired
    BaseOrderBiz baseOrderBiz;

    @Autowired
    OrderVehicleCrosstownBiz orderVehicleCrosstownBiz;

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

    @RequestMapping(value = "/getVehicleList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "交还车租车订单列表")
    public ObjectRestResponse<List<OrderPageVO>> getVehicleList(BaseOrderController.QueryOrderList dto) {
        log.info("交还车租车订单列表请求参数：dto = {}", dto);
        if (dto.getStartTime() != null) {
            if (dto.getEndTime() == null) {
                dto.setEndTime(new Date().getTime());
            }
        }
        List<Integer> userIds = new ArrayList<>();
        if (StringUtils.isNotBlank(dto.getKeywords())) {
            List<Integer> list = userFeign.getUserIdByUsername(dto.getKeywords());
            if (list != null) {
                userIds.addAll(list);
            }
            if (userIds.size() <= 0) {
                return ObjectRestResponse.succ(new PageDataVO<>());
            }
        }

        //获取app用户信息 根据用户名（手机号）定位后台商家用户
//        UserDTO userDTO = userFeign.businessUserinfoByMobilePhone(currentAppUser.getUsername()).getData();
//        getBusinessUserCompanyIds();
//
////        UserDTO userDTO = getAdminUserInfo();
//        if (userDTO == null) {
//            return ObjectRestResponse.succ(new PageDataVO<>());
//        }

        //List<BranchCompany> branchCompanies = vehicleFeign.companyAll(userDTO.getDataAll(), userDTO.getDataCompany(), userDTO.getDataZone());
        //List<Integer> companyIds = branchCompanies.stream().map(BranchCompany::getId).collect(Collectors.toList());
        List<Integer> companyIds = getBusinessUserCompanyIds();
        if(null == companyIds) {
            return ObjectRestResponse.succ(new PageDataVO<>());
        }
        if (dto.getStartCompanyId() != null) {
            if (companyIds.size() > 0) {
                if (companyIds.contains(dto.getStartCompanyId())) {
                    companyIds.clear();
                    companyIds.add(dto.getStartCompanyId());
                } else {
                    return ObjectRestResponse.succ(new PageDataVO<>());
                }
            } else {
                companyIds.add(dto.getStartCompanyId());
            }
        }
        dto.setCompanyIds(companyIds);
        Query query = new Query(dto);
        PageDataVO<OrderPageVO> pageDataVO = PageDataVO.pageInfo(query, () -> baseOrderBiz.getRentVehicle(query.getSuper()));
        for (OrderPageVO orderPageVO : pageDataVO.getData()) {
            if (orderPageVO.getOrderRentVehicleDetail() != null && orderPageVO.getOrderRentVehicleDetail().getVehicleId() != null) {
                ObjectRestResponse<Vehicle> restResponse = vehicleFeign.get(orderPageVO.getOrderRentVehicleDetail().getVehicleId());
                log.info("获取车辆信息返回消息：{}", restResponse.getMessage());
                if (restResponse.getData() != null) {
                    orderPageVO.setVehicalNumberPlat(restResponse.getData().getNumberPlate());
                    orderPageVO.setCode(restResponse.getData().getCode());
                }
            }
            if (orderPageVO.getUserId() != null) {
                AppUserDTO appUserDTO = userFeign.userDetailById(orderPageVO.getUserId()).getData();
                if (appUserDTO != null) {
                    orderPageVO.setUsername(appUserDTO.getUsername());
                    orderPageVO.setRealName(appUserDTO.getRealname());
                }
            }
        }
        return new ObjectRestResponse<>().data(pageDataVO);
    }

    @GetMapping(value = "/vehicleCrosstown/getByOrderId")
    @ApiOperation(value = "根据订单Id获取所有记录信息")
    public ObjectRestResponse<List<OrderVehicleCrosstownDto>> getByOrderId(OrderVehicleCrosstownDto orderVehicleCrosstownDto) {
        UserDTO userDTO = getAdminUserInfo();
        AppUserDTO appUserDTO = getAppUser();
        if (userDTO == null && appUserDTO == null) {
            return ObjectRestResponse.createFailedResult(508, "token is null or invalid");
        }
        if (orderVehicleCrosstownDto == null) {
            return ObjectRestResponse.createFailedResult(500, "参数orderId为空");
        }
        return ObjectRestResponse.succ(orderVehicleCrosstownBiz.selectByOrderId(orderVehicleCrosstownDto));
    }
}
