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

import ch.qos.logback.core.util.StringCollectionUtil;
import cn.dev33.satoken.annotation.SaIgnore;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.page.PageMethod;
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.MyModelUtil;
import com.tourism.common.core.util.MyPageUtil;
import com.tourism.webadmin.app.website.dto.PageDto;
import com.tourism.webadmin.app.website.dto.TourVisaSearchDto;
import com.tourism.webadmin.back.model.*;
import com.tourism.webadmin.back.model.constant.InterviewFlag;
import com.tourism.webadmin.back.service.*;
import com.tourism.webadmin.back.vo.*;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 畅
 * @date 2024年12月5日 周四 14:00:00
 */
@Tag(name = "签证接口")
@Slf4j
@RestController
@RequestMapping("/website/tourism/visa")
@DisableDataFilter
public class TourWebVisaController {
    @Autowired
    private TourVisaService tourVisaService;
    @Autowired
    private TourVisaTypeService tourVisaTypeService;
    @Autowired
    private TourVisaOrderService tourVisaOrderService;
    @Autowired
    private ITourIntercontinentalService tourIntercontinentalService;
    @Autowired
    private ITourInterlinkcountryService tourInterlinkcountryService;
    @Autowired
    private TourCountryCodeService tourCountryCodeService;
    @Autowired
    private TourVisaCounselorService tourVisaCounselorService;
    @Autowired
    private ChinaAreaService chinaAreaService;
    @Autowired
    private TourVisaOrderService orderService;
    @Autowired
    private ApplicationConfig applicationConfig;
    @Autowired
    private VisaMetarialsListService visaMetarialsListService;
    /**
     * 分页条件查询签证商品，根据价格从高到低排序
     * @param tourVisaSearchDto
     * @return
     */
    @GetMapping("/list/page")
    @SaIgnore
    public ResponseResult listPage(TourVisaSearchDto tourVisaSearchDto) {
        Integer pageNum = tourVisaSearchDto.getPageNum();
        Integer pageSize = tourVisaSearchDto.getPageSize();
        // 判断如果分页参数是null 则赋予默认值
         if (pageNum == null) {
             pageNum = 1;
         }
         if (pageSize == null) {
             pageSize = 10;
         }
         //分页查询
         PageMethod.startPage(pageNum, pageSize);
         //转换成visa查询对象
        TourVisa tourVisaFilter = MyModelUtil.copyTo(tourVisaSearchDto, TourVisa.class);
        //构建查询排序条件
        MyOrderParam myOrderParam = new MyOrderParam();
        //如果是为null 则默认降序
        if (tourVisaSearchDto.getPriceSortFlag() == null) {
            MyOrderParam.OrderInfo orderInfo = new MyOrderParam.OrderInfo("floorPrice",false,null);
            myOrderParam.add(orderInfo);
        }else {
            //为1 则降序
            if (tourVisaSearchDto.getPriceSortFlag() == 1){
                MyOrderParam.OrderInfo orderInfo = new MyOrderParam.OrderInfo("floorPrice",false,null);
                myOrderParam.add(orderInfo);
            }else if (tourVisaSearchDto.getPriceSortFlag() == 0){
                //为0升序排序
                MyOrderParam.OrderInfo orderInfo = new MyOrderParam.OrderInfo("floorPrice",true,null);
                myOrderParam.add(orderInfo);
            }
        }
        //排序参数
        String orderBy = MyOrderParam.buildOrderBy(myOrderParam, TourVisa.class);
        //查询结果集
        List<TourVisa> tourVisaList = tourVisaService.getTourVisaListWithRelation(tourVisaFilter, null,orderBy);
        int batchSize = tourVisaList instanceof Page ? 0 : 1000;
        //替换字典
        tourVisaService.buildRelationForDataList(tourVisaList, MyRelationParam.normal(), batchSize);
        //转换图片
        MyPageData<TourVisaVo> tourVisaVoMyPageData = MyPageUtil.makeResponseData(tourVisaList, TourVisaVo.class);
        List<TourVisaVo> dataList = tourVisaVoMyPageData.getDataList();
        for(TourVisaVo item:dataList){
            if(StringUtils.isNotBlank(item.getImg())){
                item.setImg(UrlConvertUtils.urlConvertSingle(applicationConfig.getHostIpPort(), item.getImg()));
            }
        }
        tourVisaVoMyPageData.setDataList(dataList);
        //返回结果集
        return ResponseResult.success(tourVisaVoMyPageData);
    }

    /**
     * 获取类型list
     * @return
     */
    @GetMapping("/getTypeList")
    @SaIgnore
    public ResponseResult getTypeList() {
        //分组去重获取签证类型
        List<TourVisaType> list = tourVisaTypeService.list(
                new LambdaQueryWrapper<TourVisaType>()
                        .last("limit 4")
        );
        //转换vo
        List<TourVisaTypeVo> tourVisaTypeVos = MyModelUtil.copyCollectionTo(list, TourVisaTypeVo.class);
        return ResponseResult.success(tourVisaTypeVos);
    }

    /**
     * 查询热门目的地
     * @return
     */
    @GetMapping("/hotAddress")
    @SaIgnore
    public ResponseResult hotAddress() {
        //分组查询取最高
        List<Map<String, Object>> maps = tourVisaOrderService.listMaps(
                new QueryWrapper<TourVisaOrder>()
                        .select("count(*) as count,visa_id as id")
                        .lambda()
                        .groupBy(TourVisaOrder::getVisaId)
                        .last("limit 8")
        );
        //排降序
        if (!maps.isEmpty() && maps.size() > 1) {
            maps.sort(new Comparator<Map<String, Object>>() {
                @Override
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    Integer count1 = Integer.valueOf(o1.get("count").toString());
                    Integer count2 = Integer.valueOf(o2.get("count").toString());
                    return count2.compareTo(count1);
                }
            });
        }
        //重新循环截取前端所需的8个
        if (maps.size() > 8) {
            maps = maps.subList(0, 8);
        }
        List<String> ids = new ArrayList<>();
        maps.forEach(map -> {
            ids.add(map.get("id").toString());
        });
        //查询最高的8个热门目的地

        List<TourVisa> tourVisas = null;
        if (ids.isEmpty() || ids.size()<8) {
            tourVisas = tourVisaService.list(new LambdaQueryWrapper<TourVisa>().orderByDesc(TourVisa::getHotValue));
        }else {
           tourVisas=  tourVisaService.list(new LambdaQueryWrapper<TourVisa>().in(TourVisa::getId,ids).orderByDesc(TourVisa::getHotValue));
        }
        tourVisaService.buildRelationForDataList(tourVisas,MyRelationParam.normal(), null);
        //转换vo
        List<TourVisaVo> tourVisaVos = MyModelUtil.copyCollectionTo(tourVisas, TourVisaVo.class);
        //转换图片
        for (TourVisaVo tourVisaVo : tourVisaVos) {
            if (StringUtils.isNotBlank(tourVisaVo.getImg())) {
                tourVisaVo.setImg(UrlConvertUtils.urlConvertSingle(applicationConfig.getHostIpPort(), tourVisaVo.getImg()));

            }
        }
        return ResponseResult.success(tourVisaVos);
    }

    /**
     * 根据洲际id查询国家
     * @param id 洲际id
     * @return
     */
    @GetMapping("/findAllCountry")
    @SaIgnore
    public ResponseResult findAllCountry(String id) {
        // 查询洲际id存在才进行下面逻辑不然就返回空
        if (tourIntercontinentalService.getById(id) == null) {
            return ResponseResult.success(new HashMap<>());
        }
        //同理查询关联关系 如果关联关系没有则返回空
        List<TourInterlinkcountry> list = tourInterlinkcountryService.list(new LambdaQueryWrapper<TourInterlinkcountry>().eq(TourInterlinkcountry::getInterId, id));
        if (list == null || list.isEmpty()) {
            return ResponseResult.success(new HashMap<>());
        }
        Set<Long> collect = list.stream().map(TourInterlinkcountry::getCountryId).collect(Collectors.toSet());
        //关联查询国家信息和国家图
        List<Map> maps = tourCountryCodeService.selectByIds(collect);
        return ResponseResult.success(maps);
    }

    /**
     * 获取所有的洲际列表
     * @return
     */
    @GetMapping("/interFind")
    @SaIgnore
    public ResponseResult interFind() {
        //直接查询所有洲际列表
        List<TourIntercontinental> list = tourIntercontinentalService.list();

        return ResponseResult.success(list);
    }

    /**
     *  根据id查询详情
     * @param id 根据id查询具体详情
     * @return
     */
    @GetMapping("/findByById")
    @SaIgnore
    public ResponseResult findById(String id) {
        //如果id为空则说明错误，不应该查询
        if (StringUtils.isBlank(id)) {
            return ResponseResult.success(null);
        }
        //查询详情对象进行返回
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        TourVisa visa = tourVisaService.getById(id);
        //封装进行字典替换
        //替换字典
//        tourVisaService.buildRelationForData(visa, MyRelationParam.normal());
        //设置国家
        List<TourCountryCode> list = tourCountryCodeService.list(new LambdaQueryWrapper<TourCountryCode>().eq(TourCountryCode::getCountryCode, visa.getCountryCodeId()));
        if (!list.isEmpty()) {
            TourCountryCode one = list.get(0);
            if (one != null) {
                HashMap<String, Object> countryCodeDictMap = new HashMap<>();
                countryCodeDictMap.put("id", one.getCountryCode());
                countryCodeDictMap.put("name", one.getCountry());
                visa.setCountryCodeIdDictMap(countryCodeDictMap);
            }
        }

        //设置出签地
        ChinaArea chinaArea = chinaAreaService.getOne(new LambdaQueryWrapper<ChinaArea>().eq(ChinaArea::getCode, visa.getIssueVisaCode()));
      if (chinaArea != null) {


        HashMap<String, Object> chinaAreasmaps = new HashMap<>();
        chinaAreasmaps.put("id",chinaArea.getCode());
        chinaAreasmaps.put("name",chinaArea.getName());
        visa.setIssueVisaCodeDictMap(chinaAreasmaps);
      }
        //面签设置
        HashMap<String, Object> interviewFlagMap = new HashMap<>();
        if (visa.getInterviewFlag() == InterviewFlag.INTERVIEW_NO){
            interviewFlagMap.put("id",InterviewFlag.INTERVIEW_NO);
            interviewFlagMap.put("name","否");
        }else {
            interviewFlagMap.put("id",InterviewFlag.INTERVIEW_YES);
            interviewFlagMap.put("name","是");
        }
        visa.setInterviewFlagDictMap(interviewFlagMap);
        //设置签证类型
        Map<String,Object> visaTypeMap = new HashMap<>();
        TourVisaType visaType = tourVisaTypeService.getById(visa.getVisaTypeId());
        if (visaType != null) {
            visaTypeMap.put("id",visaType.getId());
            visaTypeMap.put("name",visaType.getTitle());
            visa.setVisaTypeIdDictMap(visaTypeMap);
        }
        //设置顾问
        Map<String,Object> counselorIdDictMap = new HashMap<>();
        TourVisaCounselor tourVisaCounselor = tourVisaCounselorService.getById(visa.getCounselorId());
        if (tourVisaCounselor != null) {
            counselorIdDictMap.put("id",tourVisaCounselor.getId());
            counselorIdDictMap.put("name",tourVisaCounselor.getCounselorName());
            visa.setCounselorIdDictMap(counselorIdDictMap);
        }

        //转换商品vo
        TourVisaVo tourVisaVo = MyModelUtil.copyTo(visa, TourVisaVo.class);
        if (StringUtils.isNotBlank(visa.getImg())) {
            tourVisaVo.setImg(UrlConvertUtils.urlConvertSingle(applicationConfig.getHostIpPort(), tourVisaVo.getImg()));
        }
        //封装结果集
        stringObjectHashMap.put("visa",tourVisaVo);
        //查询顾问并封装进结果集
        TourVisaCounselor byId = null;
        if (visa!=null) {
             byId =  tourVisaCounselorService.getById(visa.getCounselorId());
        }else {
            byId =new TourVisaCounselor();
        }
        //翻译字典
        tourVisaCounselorService.buildRelationForData(byId, MyRelationParam.normal());
        //转换顾问vo
        TourVisaCounselorVo tourVisaCounselorVo = MyModelUtil.copyTo(byId, TourVisaCounselorVo.class);
        //转换图片
        if(StringUtils.isNotBlank(tourVisaCounselorVo.getCounselorAvatar())){
            tourVisaCounselorVo.setCounselorAvatar(UrlConvertUtils.urlConvertSingle(applicationConfig.getHostIpPort(), tourVisaCounselorVo.getCounselorAvatar()));
        }
        if(StringUtils.isNotBlank(tourVisaCounselorVo.getCounselorWechat())){
            tourVisaCounselorVo.setCounselorWechat(UrlConvertUtils.urlConvertSingle(applicationConfig.getHostIpPort(), tourVisaCounselorVo.getCounselorWechat()));
        }
        stringObjectHashMap.put("counselor",tourVisaCounselorVo);
        //处理基础材料签证的
        if (visa!=null){
            List<VisaMetarialsList> visaMetarialsLists = visaMetarialsListService.list(new LambdaQueryWrapper<VisaMetarialsList>().eq(VisaMetarialsList::getVisaId, id));
            //转换vo
            List<VisaMetarialsListVo> visaMetarialsListVos = MyModelUtil.copyCollectionTo(visaMetarialsLists, VisaMetarialsListVo.class);
            //不为空返回基础材料list
            if ( visaMetarialsListVos != null&&!visaMetarialsListVos.isEmpty()) {
                stringObjectHashMap.put("metarialsList",visaMetarialsListVos);
            }else {
                stringObjectHashMap.put("metarialsList",new ArrayList<>());
            }
        }else {
            //为空直接返回空list
            stringObjectHashMap.put("metarialsList",new ArrayList<>());
        }
        return ResponseResult.success(stringObjectHashMap);
    }

    /**
     * 分页查询当前登陆人签证订单
     * @param pageDto 分页参数
     * @param phone 电话
     * @return
     */
    @GetMapping("/findOrderPage")
    public ResponseResult findOrderPage(String phone,PageDto pageDto) {
        //获取分页参数
        Integer pageNum = pageDto.getPageNum();
        Integer pageSize = pageDto.getPageSize();
        //如果当前每页为空则设置为默认1
        if (pageNum == null) {
            pageNum = 1;
        }
        //如果每页条数为空则设置为默认为10条
        if (pageSize == null) {
            pageSize = 10;
        }
        //开始分页
        PageMethod.startPage(pageNum, pageSize);
        //根据token里当前登录人的用户id查询订单 并根据订单时间进行排序
        List<TourVisaOrder> list = orderService.list(new LambdaQueryWrapper<TourVisaOrder>()
                .eq(TourVisaOrder::getOrderPhone, phone)
                .orderByDesc(TourVisaOrder::getCreateTime)
        );
        if (list.isEmpty()){
            return ResponseResult.success(new ArrayList<>());
        }
        List<Long> longList = list.stream().map(TourVisaOrder::getVisaId).collect(Collectors.toList());
        List<TourVisa> tourVisas = tourVisaService.listByIds(longList);
        tourVisaService.buildRelationForDataList(tourVisas, MyRelationParam.normal());
        List<TourVisaVo> tourVisaVos = MyModelUtil.copyCollectionTo(tourVisas, TourVisaVo.class);
        int batchSize = list instanceof Page ? 0 : 1000;
        //替换字典
        orderService.buildRelationForDataList(list, MyRelationParam.normal(), batchSize);
        MyPageData<TourVisaOrderVo> tourVisaOrderVoMyPageData = MyPageUtil.makeResponseData(list, TourVisaOrderVo.class);
        //转换文件
        List<TourVisaOrderVo> dataList = tourVisaOrderVoMyPageData.getDataList();
        for (TourVisaOrderVo tourVisaOrderVo : dataList) {
            if (StringUtils.isNotBlank(tourVisaOrderVo.getFile())){
                tourVisaOrderVo.setFile(UrlConvertUtils.urlConvertSingle(applicationConfig.getHostIpPort(), tourVisaOrderVo.getFile()));
            }
            for (TourVisaVo tourVisa : tourVisaVos) {
                if (tourVisaOrderVo.getVisaId().equals(tourVisa.getId().toString())) {
                    if(StringUtils.isNotBlank(tourVisa.getImg())){
                        tourVisa.setImg(UrlConvertUtils.urlConvertSingle(applicationConfig.getHostIpPort(), tourVisa.getImg()));
                    }
                    tourVisaOrderVo.setTourVisaVo(tourVisa);
                }

            }
        }
        tourVisaOrderVoMyPageData.setDataList(dataList);
        //封装返回结果
        return ResponseResult.success(tourVisaOrderVoMyPageData);
    }
    /**
     *     根据订单id查询详情
     * @param id 订单id
     */
    @GetMapping("/findOrderById")
    public ResponseResult findOrderById(String id) {
        //如果id为空直接返回错误
        if (StringUtils.isBlank(id)) {
            return ResponseResult.success(null);
        }
        //查询订单详情
        TourVisaOrder byId = orderService.getById(id);
        TourVisa visa = null;
        if (Objects.nonNull(byId)){
            visa = tourVisaService.getById(byId.getVisaId());
        }
        //替换对象字典
        orderService.buildRelationForData(byId, MyRelationParam.normal());
        //转换订单vo
        TourVisaOrderVo tourVisaOrderVo = MyModelUtil.copyTo(byId, TourVisaOrderVo.class);
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        if (tourVisaOrderVo != null) {
            if (StringUtils.isNotBlank(tourVisaOrderVo.getFile())) {
                tourVisaOrderVo.setFile(UrlConvertUtils.urlConvertSingle(applicationConfig.getHostIpPort(), tourVisaOrderVo.getFile()));
            }
        }
        stringObjectHashMap.put("order",tourVisaOrderVo);
        if (visa!=null) {
            tourVisaService.buildRelationForData(visa, MyRelationParam.normal());
            TourVisaVo tourVisaVo = MyModelUtil.copyTo(visa, TourVisaVo.class);
            //图片转换
            if(StringUtils.isNotBlank(tourVisaVo.getImg())){
                tourVisaVo.setImg(UrlConvertUtils.urlConvertSingle(applicationConfig.getHostIpPort(), tourVisaVo.getImg()));
            }
            stringObjectHashMap.put("visa",tourVisaVo);
        }else {
            stringObjectHashMap.put("visa",null);
        }


        return ResponseResult.success(stringObjectHashMap);
    }

    /**
     * 根据id删除订单
     * @param id 订单id
     * @return
     */
    @GetMapping("/deleteOrderById")
    public ResponseResult deleteOrderById(String id) {
        //如果id为空则是脏数据
        if (StringUtils.isBlank(id)) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        //不为空去删除数据
        boolean removeById = orderService.removeById(id);
        if (removeById) {
            //删除成功返回成功
            return ResponseResult.success(null);
        }
        //否则返回报错删除失败
        return ResponseResult.error(ErrorCodeEnum.SERVER_INTERNAL_ERROR);
    }
    /**
     * 返回中国出签地编码
     * @return
     */
    @GetMapping("/findCountryCodeList")
    @SaIgnore
    public ResponseResult findCountryCodeList() {
        //查询中国所有市级省级标准†
        List<ChinaArea> list = chinaAreaService.list(new LambdaQueryWrapper<ChinaArea>().in(ChinaArea::getLevel,1,2));
        return ResponseResult.success(list);
    }

    /**
     * 查找顾问二维码
     * @return
     */
    @GetMapping("/findWechatList")
    @SaIgnore
    public ResponseResult findWechatList() {
        //查询为1的顾问
        List<TourVisaCounselor> list = tourVisaCounselorService.list(new LambdaQueryWrapper<TourVisaCounselor>().eq(TourVisaCounselor::getIndexFlag, 1).orderByDesc(TourVisaCounselor::getCreateTime));
        for (TourVisaCounselor tourVisaCounselor : list) {
            if (StringUtils.isNotBlank(tourVisaCounselor.getCounselorWechat())) {
                tourVisaCounselor.setCounselorWechat(UrlConvertUtils.urlConvertSingle(applicationConfig.getHostIpPort(), tourVisaCounselor.getCounselorWechat()));

            }
            if (StringUtils.isNotBlank(tourVisaCounselor.getCounselorAvatar())) {
                tourVisaCounselor.setCounselorAvatar(UrlConvertUtils.urlConvertSingle(applicationConfig.getHostIpPort(),tourVisaCounselor.getCounselorAvatar()));
            }
        }
        if (list.isEmpty()){
            return ResponseResult.success(null);
        }
        //获取最近的总顾问
        TourVisaCounselor tourVisaCounselor = list.get(0);
        tourVisaCounselorService.buildRelationForData(tourVisaCounselor, MyRelationParam.normal());
        //转换字典vo
        TourVisaCounselorVo tourVisaCounselorVo = MyModelUtil.copyTo(tourVisaCounselor, TourVisaCounselorVo.class);
        return ResponseResult.success(tourVisaCounselorVo);
    }

    /**
     * 查询国家编码
     * @return
     */
    @GetMapping("/getCountryList")
    public ResponseResult getCountryList() {
        return ResponseResult.success(tourCountryCodeService.list());
    }





}
