package com.xxfc.platform.uccn.biz;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.xxfc.platform.campsite.dto.CampsiteShopFindDTO;
import com.xxfc.platform.campsite.feign.CampsiteFeign;
import com.xxfc.platform.campsite.vo.CampsiteShopPageVo;
import com.xxfc.platform.tour.entity.TourGood;
import com.xxfc.platform.tour.feign.TourFeign;
import com.xxfc.platform.uccn.comstnt.ServiceConstant;
import com.xxfc.platform.uccn.vo.SearchResultVo;
import com.xxfc.platform.uccn.vo.ServiceResultVo;
import com.xxfc.platform.uccn.vo.SummitActivityVo;
import com.xxfc.platform.vehicle.entity.VehiclePlatCata;
import com.xxfc.platform.vehicle.feign.VehicleFeign;
import com.xxfc.platform.vehicle.pojo.VehicleModelQueryCondition;
import com.xxfc.platform.vehicle.pojo.VehicleModelVo;
import com.xxfc.platform.vehicle.pojo.dto.BranchCompanyFindDTO;
import com.xxfc.platform.vehicle.pojo.vo.BranchCompanyListVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

/**
 * @author libin
 * @version 1.0
 * @description
 * @data 2019/9/17 10:19
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SearchBiz {
    /**
     * 车型与分公司
     */
    private final VehicleFeign vehicleFeign;
    /**
     * 旅游
     */
    private final TourFeign tourFeign;
    /**
     * 营地
     */
    private final CampsiteFeign campsiteFeign;
    /**
     * 新闻
     */
    private final ArticleBiz articleBiz;
    /**
     * 活动
     */
    private final SummitActivityBiz summitActivityBiz;

    /**
     * 业务个数
     */
    private static final int SERVICE_COUNT = 6;

    private final ThreadPoolTaskExecutor threadPoolTaskExecutor;

    /**
     * 综合搜索
     *
     * @param keyWord 关键字
     * @return
     */
    public SearchResultVo searchWithKeyWords(String keyWord) {
        SearchResultVo searchResultVo = new SearchResultVo();
        CountDownLatch latch = new CountDownLatch(SERVICE_COUNT);
        //车型
        threadPoolTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    ServiceResultVo<VehicleModelVo> vehicleModelVoServiceResultVo = new ServiceResultVo<>();

                    VehicleModelQueryCondition vmqc = new VehicleModelQueryCondition();
                    vmqc.setNotInIds("67");
                    vmqc.setPage(1);
                    vmqc.setLimit(ServiceConstant.VEHICLE_LIMIT);
                    vmqc.setVehicleName(keyWord);
                    ObjectRestResponse<PageDataVO<VehicleModelVo>> objectRestResponse = vehicleFeign.findVehicleModelPageUnauthfind(vmqc);
                    PageDataVO<VehicleModelVo> pageDataVOs = objectRestResponse.getData();
                    pageDataVOs.getData().forEach(v -> {
                        v.setUccnCataList(initUccnCataCollect(v.getConfig()));
                    });

                    long totalCount = pageDataVOs==null?0:pageDataVOs.getTotalCount()==null?0:pageDataVOs.getTotalCount();
                    List<VehicleModelVo> result = pageDataVOs == null ? Collections.EMPTY_LIST : pageDataVOs.getData() == null ? Collections.EMPTY_LIST : pageDataVOs.getData();
                    vehicleModelVoServiceResultVo.setTotalCount(totalCount);
                    vehicleModelVoServiceResultVo.setData(result);
                    searchResultVo.put(ServiceConstant.VEHICLE, vehicleModelVoServiceResultVo);
                } catch (Exception ex) {
                    ex.printStackTrace();
                } finally {
                    latch.countDown();
                }
            }
        });
        //分公司
        threadPoolTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    ServiceResultVo<BranchCompanyListVO> branchCompanyListVOServiceResultVo = new ServiceResultVo<>();
                    BranchCompanyFindDTO branchCompanyFindDTO = new BranchCompanyFindDTO();
                    branchCompanyFindDTO.setPage(1);
                    branchCompanyFindDTO.setLimit(ServiceConstant.BRANCH_COMPANY_LIMIT);
                    branchCompanyFindDTO.setName(keyWord);
                    PageDataVO<BranchCompanyListVO> branchCompanyWithPage = vehicleFeign.findBranchCompanyWithPage(branchCompanyFindDTO);

                    long totalCount = branchCompanyWithPage==null?0:branchCompanyWithPage.getTotalCount()==null?0:branchCompanyWithPage.getTotalCount();
                    List<BranchCompanyListVO> result = branchCompanyWithPage == null ? Collections.EMPTY_LIST : branchCompanyWithPage.getData() == null ? Collections.EMPTY_LIST : branchCompanyWithPage.getData();
                    branchCompanyListVOServiceResultVo.setTotalCount(totalCount);
                    branchCompanyListVOServiceResultVo.setData(result);
                    searchResultVo.put(ServiceConstant.BRANCH_COMPANY, branchCompanyListVOServiceResultVo);
                } catch (Exception ex) {
                    ex.printStackTrace();
                } finally {
                    latch.countDown();
                }
            }
        });
        //旅游
        threadPoolTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    ServiceResultVo<TourGood> tourGoodServiceResultVo = new ServiceResultVo<>();
                    ObjectRestResponse<PageDataVO<TourGood>> goodList = tourFeign.getGoodList(1, ServiceConstant.TOUR_LIMIT, null, keyWord);
                    PageDataVO<TourGood> data = goodList.getData();
                    long totalCount = data==null?0:data.getTotalCount()==null?0:data.getTotalCount();
                    List<TourGood> result = data == null ? Collections.EMPTY_LIST : data.getData() == null ? Collections.EMPTY_LIST : data.getData();
                    tourGoodServiceResultVo.setData(result);
                    tourGoodServiceResultVo.setTotalCount(totalCount);
                    searchResultVo.put(ServiceConstant.TROUR, tourGoodServiceResultVo);
                } catch (Exception ex) {
                    ex.printStackTrace();
                } finally {
                    latch.countDown();
                }

            }
        });
        //营地
        threadPoolTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    ServiceResultVo<CampsiteShopPageVo> campsiteShopPageVoServiceResultVo = new ServiceResultVo<>();

                    CampsiteShopFindDTO campsiteShopFindDTO = new CampsiteShopFindDTO();
                    campsiteShopFindDTO.setPage(1);
                    campsiteShopFindDTO.setLimit(ServiceConstant.CAMPSITE_LIMIT);
                    campsiteShopFindDTO.setName(keyWord);
                    ObjectRestResponse<PageDataVO<CampsiteShopPageVo>> campsiteShopPageForUncc = campsiteFeign.findCampsiteShopPageForUncc(campsiteShopFindDTO);
                    PageDataVO<CampsiteShopPageVo> data = campsiteShopPageForUncc.getData();
                    long totalCount = data==null?0:data.getTotalCount()==null?0:data.getTotalCount();
                    List<CampsiteShopPageVo> result = data == null ? Collections.EMPTY_LIST : data.getData() == null ? Collections.EMPTY_LIST : data.getData();
                    campsiteShopPageVoServiceResultVo.setData(result);
                    campsiteShopPageVoServiceResultVo.setTotalCount(totalCount);
                    searchResultVo.put(ServiceConstant.CAMPSITE, campsiteShopPageVoServiceResultVo);
                } catch (Exception ex) {
                    ex.printStackTrace();
                } finally {
                    latch.countDown();
                }
            }
        });
        //活动
        threadPoolTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    ServiceResultVo<SummitActivityVo> activityVoServiceResultVo = new ServiceResultVo<>();
                    PageDataVO<SummitActivityVo> summitActivityWithPage = summitActivityBiz.findSummitActivityWithPage(1, ServiceConstant.ACTIVITY_LIMIT, null, keyWord);
                    long totalCount = summitActivityWithPage==null?0:summitActivityWithPage.getTotalCount()==null?0:summitActivityWithPage.getTotalCount();
                    List<SummitActivityVo> result = summitActivityWithPage == null ? Collections.EMPTY_LIST : summitActivityWithPage.getData() == null ? Collections.EMPTY_LIST : summitActivityWithPage.getData();
                    activityVoServiceResultVo.setTotalCount(totalCount);
                    activityVoServiceResultVo.setData(result);
                    searchResultVo.put(ServiceConstant.ACTIVITY, activityVoServiceResultVo);
                } catch (Exception ex) {
                    ex.printStackTrace();
                } finally {
                    latch.countDown();
                }
            }
        });

        try {
            latch.await();
        } catch (InterruptedException e) {
            throw new BaseException(e);
        }
        return searchResultVo;
    }

    private List<VehiclePlatCata> initUccnCataCollect(String modelConfig) {
        List<VehiclePlatCata> vehiclePlatCataList = vehicleFeign.getCatasByIds(modelConfig).getData();
        int[] array = StrUtil.splitToInt("14,7,11", ",");
        return vehiclePlatCataList.parallelStream()
                .filter(v1 -> {
                    return ArrayUtil.contains(array, v1.getParentId());
                })
                .sorted(Comparator.comparing(VehiclePlatCata::getParentId, (x, y) -> {
                    int xx = 0, yy = 0;
                    for (int i = 0; i < array.length; i++) {
                        if (x == array[i]) {
                            xx = i;
                        } else if (y == array[i]) {
                            yy = i;
                        }
                    }
                    return (xx - yy);
                })).collect(Collectors.toList());
    }
}
