package com.xxfc.platform.order.biz;

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.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.Query;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.xxfc.platform.order.entity.BaseOrder;
import com.xxfc.platform.order.mapper.BaseOrderMapper;
import com.xxfc.platform.order.rest.BaseOrderController;
import com.xxfc.platform.tour.feign.TourFeign;
import com.xxfc.platform.vehicle.entity.BranchCompany;
import com.xxfc.platform.vehicle.feign.VehicleFeign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class BackgroundBaseOrderBiz extends BaseBiz<BaseOrderMapper, BaseOrder> implements UserRestInterface {
	@Autowired
	UserFeign userFeign;
	@Autowired
	VehicleFeign vehicleFeign;
	@Autowired
	TourFeign tourFeign;
	@Override
	public UserFeign getUserFeign() {
		return userFeign;
	}

	public ObjectRestResponse getAllOrderList(BaseOrderController.QueryOrderList dto) {
		//判断token是否存在
		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());
		//大区搜索
		//有当前大区权限才能搜索到数据
		if (dto.getZoneId() != null && (userDTO.getDataAll() == 1 || userDTO.getZoneId().equals(dto.getZoneId()) || userDTO.getDataZone().contains(dto.getZoneId()+""))) {
			companyIds.clear();
		}
		//所属公司筛选
		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);
		if (dto.getStartTime() != null) {
			if (dto.getEndTime() == null) {
				dto.setEndTime(new Date().getTime());
			}
		}
		Query query = new Query(dto);
		PageDataVO pageDataVO = PageDataVO.pageInfo(query, () -> mapper.getAllOrderList(query.getSuper()));
		return ObjectRestResponse.succ(pageDataVO);
	}
}
