package com.xxfc.platform.order.rest;

import com.github.wxiaoqi.security.admin.entity.AppUserLogin;
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.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.Query;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.xxfc.platform.order.biz.BaseOrderBiz;
import com.xxfc.platform.order.biz.OrderUserLicenseBiz;
import com.xxfc.platform.order.pojo.order.OrderListVo;
import com.xxfc.platform.order.pojo.order.OrderPageVO;
import com.xxfc.platform.order.pojo.order.OrderVehicleCrosstownDto;
import com.xxfc.platform.order.pojo.order.QueryOrderDTO;
import com.xxfc.platform.vehicle.common.RestResponse;
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.CompanyDetail;
import com.xxfc.platform.vehicle.pojo.QueryMultiDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

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

    public static final Integer STATUS_SUCCESS = 1;
    @Autowired
    BaseOrderBiz baseOrderBiz;

    @Autowired
    OrderUserLicenseBiz orderUserLicenseBiz;

    @Autowired
    UserFeign userFeign;

    @Resource
    VehicleFeign vehicleFeign;

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

    @RequestMapping(value = "/getOrderList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取后台订单列表")
    @IgnoreClientToken
    @CrossOrigin
    public ObjectRestResponse<PageDataVO<OrderListVo>> selectByUser(BaseOrderController.QueryOrderList dto) {
        if (dto.getStartTime() != null) {
            if (dto.getEndTime() == null) {
                dto.setEndTime(new Date().getTime());
            }
        }
        if (StringUtils.isNotBlank(dto.getPhone())) {
            AppUserLogin appUserLogin = userFeign.one(dto.getPhone());
            if (appUserLogin != null) {
                dto.setUserId(appUserLogin.getId());
            }
        }
        UserDTO userDTO = getAdminUserInfo();
        if (userDTO == null) {
            return ObjectRestResponse.succ(new PageDataVO<>());
        }
        if(dto.getType() != 3) {
            List<BranchCompany> branchCompanies = vehicleFeign.companyAll(userDTO.getDataAll(), userDTO.getDataCompany(), userDTO.getDataZone());
            List<Integer> companyIds = branchCompanies.stream().map(BranchCompany::getId).collect(Collectors.toList());
            dto.setCompanyIds(companyIds);
        }

        Query query = new Query(dto);
        PageDataVO pageDataVO = PageDataVO.pageInfo(query, () -> baseOrderBiz.listOrder(query.getSuper()));
        List<OrderListVo> list = pageDataVO.getData();
        List<Integer> userIds = list.stream().map(OrderListVo::getUserId).distinct().collect(Collectors.toList());
        if (userIds != null && userIds.size() > 0) {
            ObjectRestResponse<List<AppUserVo>> objectRestResponse = userFeign.getByUserIds(userIds);
            log.info("获取用户信息：objectRestResponse = {}", objectRestResponse.getData());
            Map<String, AppUserVo> appUserVoMap = objectRestResponse.getData() == null ? new HashMap<String, AppUserVo>()
                    : objectRestResponse.getData().parallelStream().collect(Collectors.toMap(v -> v.getUserid().toString().trim(), v -> v));

            for (OrderListVo orderPageVO : list) {
                AppUserVo appUserVo = appUserVoMap.get(orderPageVO.getUserId().toString());
                if (null != appUserVo) {
                    orderPageVO.setTelephone(appUserVo.getUsername());
                    orderPageVO.setUsername(appUserVo.getNickname());
                }
                if (orderPageVO.getOrderRentVehicleDetail() != null && orderPageVO.getOrderRentVehicleDetail().getVehicleId() != null) {
                    RestResponse<Vehicle> restResponse = vehicleFeign.findById(orderPageVO.getOrderRentVehicleDetail().getVehicleId());
                    log.info("获取车辆信息返回消息：{}", restResponse.getMessage());
                    if (restResponse.getData() != null) {
                        orderPageVO.setVehicleNumberPlat(restResponse.getData().getNumberPlate());
                    }
                    if (StringUtils.isNotBlank(orderPageVO.getOrderRentVehicleDetail().getMyDriverIds())) {
                       try {
                           QueryMultiDTO queryMultiDTO = new QueryMultiDTO();
                           queryMultiDTO.setIds(orderPageVO.getOrderRentVehicleDetail().getMyDriverIds());
                           List<VehicleUserLicense> orderUserLicenses = vehicleFeign.multi(queryMultiDTO).getData();

                           if (orderUserLicenses != null && orderUserLicenses.size() > 0) {
                               OrderVehicleCrosstownDto orderVehicleCrosstownDto = new OrderVehicleCrosstownDto();
                               orderVehicleCrosstownDto.setLicenseIdCard(orderUserLicenses.get(0).getIdCard());
                               orderVehicleCrosstownDto.setLicenseImg(orderUserLicenses.get(0).getImg());
                               orderVehicleCrosstownDto.setLicenseName(orderUserLicenses.get(0).getName());
                               orderVehicleCrosstownDto.setLicensePhone(orderUserLicenses.get(0).getPhone());
                               orderPageVO.setOrderVehicleCrosstownDto(orderVehicleCrosstownDto);
                           }
                       } catch (Exception e) {
                           log.info("获取驾驶人信息失败！");
                       }

                    }

                }
                if (orderPageVO.getOrderRentVehicleDetail() != null && orderPageVO.getOrderRentVehicleDetail().getStartCompanyId() != null && orderPageVO.getOrderRentVehicleDetail().getEndCompanyId() != null) {
                    ObjectRestResponse<CompanyDetail> startResponse = vehicleFeign.getCompanyDetail(orderPageVO.getOrderRentVehicleDetail().getStartCompanyId());
                    if (startResponse.getData() != null) {
                        orderPageVO.setStartCompanyName(startResponse.getData().getName());
                    }

                    ObjectRestResponse<CompanyDetail> restResponse = vehicleFeign.getCompanyDetail(orderPageVO.getOrderRentVehicleDetail().getEndCompanyId());
                    if (restResponse.getData() != null) {
                        orderPageVO.setEndCompanyName(restResponse.getData().getName());
                    }
                }
                //旅游
                if (orderPageVO.getOrderTourDetail() != null && orderPageVO.getOrderTourDetail().getStartCompanyId() != null) {
                    ObjectRestResponse<CompanyDetail> startResponse = vehicleFeign.getCompanyDetail(orderPageVO.getOrderTourDetail().getStartCompanyId());
                    if (startResponse.getData() != null) {
                        orderPageVO.setStartCompanyName(startResponse.getData().getName());
                    }
                    List<Integer> tourUserIds = Arrays.asList(orderPageVO.getOrderTourDetail().getTourUserIds().split(",")).parallelStream().map(s -> Integer.valueOf(s.trim())).collect(Collectors.toList());
                    ObjectRestResponse<List<AppUserVo>> users = userFeign.getByUserIds(tourUserIds);
                    if (users.getData() != null) {
                        orderPageVO.getOrderTourDetail().setUserVoList(users.getData() == null? users.getData() : new ArrayList<>());
                    }
                }


            }
        }
        return new ObjectRestResponse<>().data(pageDataVO);
    }

    @RequestMapping(value = "/getVehicleList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "交还车租车订单列表")
    @IgnoreClientToken
    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());
            }
        }
        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());
                }
            }

        }
        return new ObjectRestResponse<>().data(pageDataVO);
    }

    @RequestMapping(value = "/getTourList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "交还车旅游订单列表")
    @IgnoreClientToken
    public ObjectRestResponse<List<OrderPageVO>> getTourList(BaseOrderController.QueryOrderList dto) {
        if (dto.getStartTime() != null) {
            if (dto.getEndTime() == null) {
                dto.setEndTime(dto.getStartTime());
            }

        }
        Query query = new Query(dto);
        PageDataVO pageDataVO = PageDataVO.pageInfo(query, () -> baseOrderBiz.getTourList(query.getSuper()));
        return new ObjectRestResponse<>().data(pageDataVO);
    }

    @GetMapping(value = "/orderDetail")
    @ApiOperation(value = "交还车获取订单详情，带驾驶人信息")
    @IgnoreClientToken
    @ResponseBody
    public ObjectRestResponse<OrderPageVO> getOrderDetail(String orderNo) {
        UserDTO userDTO = getAdminUserInfo();
        if (userDTO == null) {
            return ObjectRestResponse.succ(new PageDataVO<>());
        }
        if (StringUtils.isBlank(orderNo)) {
            return ObjectRestResponse.paramIsEmpty();
        }
        return baseOrderBiz.getOrderDetail(orderNo, userDTO);
    }


    @ApiOperation("结合后台人员所属公司查询订单详情")
    @RequestMapping(value = "/company/{no}", method = RequestMethod.GET)
    @IgnoreClientToken
    @ResponseBody
    public ObjectRestResponse<OrderPageVO> companyGet(@PathVariable String no) {
        //查询列表数据
        if (StringUtils.isBlank(BaseContextHandler.getUserID())) {
            throw new BaseException(ResultCode.AJAX_WECHAT_NOTEXIST_CODE);
        }

        Query query = initCompanyQuery(no);
        PageDataVO<OrderPageVO> page = PageDataVO.pageInfo(query, () -> baseOrderBiz.pageByParm(query.getSuper()));
        if (page.getData().isEmpty()) {
            throw new BaseException(ResultCode.NOTEXIST_CODE);
        }
        return new ObjectRestResponse<>().data(page.getData().get(0));
    }

    private Query initCompanyQuery(String no) {
        BackStageOrderController.QueryOrderDetailDTO qodd = new BackStageOrderController.QueryOrderDetailDTO();
        //查询公司id
        UserDTO userDto = userFeign.userinfoByToken(BaseContextHandler.getToken()).getData();
        qodd.setCrtCompanyId(userDto.getCompanyId());
        qodd.setNo(no);
        qodd.setLimit(1);
        qodd.setPage(1);
        Query query = new Query(qodd);
        return query;
    }

    /**
     * 订单查询类
     */
    @Data
    public class QueryOrderDetailDTO extends QueryOrderDTO {
        private String no;
    }
}
