package com.xxfc.platform.tour.biz;

import cn.hutool.db.handler.HandleHelper;
import com.ace.cache.annotation.CacheClear;
import com.github.wxiaoqi.security.admin.feign.dto.UserDTO;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.xxfc.platform.tour.comstnt.RedisKey;
import com.xxfc.platform.tour.dto.TourTagAndBannerDTO;
import com.xxfc.platform.tour.dto.TourTagBannerDTO;
import com.xxfc.platform.tour.dto.TourTagDTO;
import com.xxfc.platform.tour.entity.TourGood;
import com.xxfc.platform.tour.mapper.TourGoodMapper;
import com.xxfc.platform.tour.mapper.TourTagMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xxfc.platform.tour.entity.TourTag;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 旅游路线标签
 *
 * @author zjw
 * @email nishijjo@qq.com
 * @date 2019-06-06 11:41:51
 */
@Service
@Slf4j
public class TourTagBiz extends BaseBiz<TourTagMapper,TourTag> {


     @Autowired
     private TourTagBannerBiz tourTagBannerBiz;

    @Autowired
    private TourGoodMapper tourGoodMapper;

//    @Cache(key = RedisKey.CONSTANT_CODE_PREFIX_HOTTAG)
    public List<TourTag> getHotTag() {

        TourTag tag = new TourTag();
        tag.setIsDel(0);
        tag.setIsHot(1);
        return mapper.findHotListTag(tag);
    }

    public List<TourTag> getHotTagAndGoods() {
        TourTag tag = new TourTag();
        tag.setIsDel(0);
        tag.setIsHot(1);
        List<TourTag>list = mapper.findHotListTag(tag);
        Map<String,Object>map = new HashMap<String,Object>();
        //增加两条线路例子
        for(TourTag tourTag :list){
            map.put("tagId",tourTag.getId());
            PageDataVO<TourGood> dataVO = PageDataVO.pageInfo(1, 2, () -> tourGoodMapper.getGoodList(map));
            List<TourGood> pageDataVO = dataVO.getData();
            tourTag.setList(pageDataVO);
        }
        return list;
    }

    public List<TourTag> getTagList(Integer isHot) {
        TourTag tag = new TourTag();
        tag.setIsDel(0);
        if (isHot!=null&&isHot==1){
            tag.setIsHot(1);
            return mapper.findHotListTag(tag);
        }
        return mapper.findAllByIsDel(tag);
    }



    public PageDataVO<TourTag> findPage(Map map) {
        TourTag tag = new TourTag();
        tag.setIsDel(0);
        return PageDataVO.pageInfo((Integer)map.get("page"),(Integer)map.get("limit"),() -> mapper.findAllByIsDel(tag));
    }

    @CacheClear(key = RedisKey.CONSTANT_CODE_PREFIX_HOTTAG)
    public void update(TourTag banner) {
        this.updateSelectiveById(banner);
    }


    @CacheClear(key = RedisKey.CONSTANT_CODE_PREFIX_HOTTAG)
    public void remove(int id) {
        this.deleteById(id);
    }


    /**
     * 分页查询旅游标签
     * @param pageNo 查询的当前
     * @param pageSize 分页大小
     * @return
     */
    public PageDataVO<TourTagAndBannerDTO> findTourTagWithPage(Integer pageNo, Integer pageSize) {
        PageDataVO<TourTagAndBannerDTO> tourTagAndBannerDTOPageDataVO = new PageDataVO<>();
        //根据分页条件查询出旅游标签的信息
        PageDataVO<TourTag> pageDataVO = PageDataVO.pageInfo(pageNo, pageSize, () -> mapper.findAllByIsDel(TourTag.builder().isDel(0).build()));
        List<TourTag> tourTags = pageDataVO.getData();
        if (log.isDebugEnabled()){
            log.debug("旅游分页查询标签：[{}]",tourTags);
        }
        if (CollectionUtils.isEmpty(tourTags)){
            return tourTagAndBannerDTOPageDataVO;
        }
          List<TourTagAndBannerDTO> tourTagAndBannerDTOS = new ArrayList<>();
        //根据标签ids查询banner
        List<Integer> tagIds = tourTags.stream().map(TourTag::getId).collect(Collectors.toList());
        Map<Integer, List<TourTagBannerDTO>> tourTagBannerMap = tourTagBannerBiz.findTourTagBannersByTagIds(tagIds);
        tourTags.forEach(tourTag -> {

         });
        for (TourTag tourTag:tourTags){
            //vo转换
            TourTagDTO tourTagDTO = new TourTagDTO();
            BeanUtils.copyProperties(tourTag,tourTagDTO);
            //根据旅游标签id查询出标签banner相关信息
            List<TourTagBannerDTO> tagBannerDTOS = tourTagBannerMap.get(tourTag.getId());
            //banner 数量
            tourTagDTO.setBannerNums(tagBannerDTOS==null?0:tagBannerDTOS.size());
            tourTagAndBannerDTOS.add(TourTagAndBannerDTO.builder().tourTagDTO(tourTagDTO).tourTagBannerDTOS(tagBannerDTOS).build());
        }
          //组装数据
        tourTagAndBannerDTOPageDataVO.setData(tourTagAndBannerDTOS);
        tourTagAndBannerDTOPageDataVO.setPageNum(pageDataVO.getPageNum());
        tourTagAndBannerDTOPageDataVO.setPageSize(pageDataVO.getPageSize());
        tourTagAndBannerDTOPageDataVO.setTotalCount(pageDataVO.getTotalCount());
        tourTagAndBannerDTOPageDataVO.setTotalPage(pageDataVO.getTotalPage());

        return tourTagAndBannerDTOPageDataVO;
    }

    /**
     * 根据主键id查询 旅游标签
     * @param tagId
     * @return
     */
    public TourTagAndBannerDTO findTourTagById(Integer tagId){
        TourTagAndBannerDTO tourTagAndBannerDTO = new TourTagAndBannerDTO();
         //根据旅游标签id查询出标签信息
        TourTag tourTag = mapper.findById(tagId);
        if (log.isDebugEnabled()){
            log.debug("根据标签id=[{}]查询出标签信息:[{}]",tagId,tourTag);
        }
        if (tourTag==null){
            return tourTagAndBannerDTO;
        }
        TourTagDTO tourTagDTO = new TourTagDTO();
        BeanUtils.copyProperties(tourTag,tourTagDTO);
        //根据旅游标签id查询出标签对应的轮播图信息
        List<TourTagBannerDTO> tourTagBannerDTOS = tourTagBannerBiz.findTourTagBannersByTagId(tagId);
        if (log.isDebugEnabled()){
            log.debug("根据标签id=[{}],查询出轮播图信息：[{}]",tagId,tourTagBannerDTOS);
        }

        //组装数据
        tourTagAndBannerDTO.setTourTagDTO(tourTagDTO);
        tourTagAndBannerDTO.setTourTagBannerDTOS(tourTagBannerDTOS);
        return tourTagAndBannerDTO;
    }

    /**
     * 保存旅游标签
     * @param tourTagAndBannerDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int saveTourTag(TourTagAndBannerDTO tourTagAndBannerDTO, UserDTO userDTO) {
        if (log.isDebugEnabled()){
            log.debug("传入保存的标签信息:[{}]",tourTagAndBannerDTO);
        }
        TourTagDTO tourTagDTO = tourTagAndBannerDTO.getTourTagDTO();
        List<TourTagBannerDTO> tourTagBannerDTOS = tourTagAndBannerDTO.getTourTagBannerDTOS();
        //设置标签创建的相关信息
        tourTagDTO.setCtrTime(Instant.now().toEpochMilli());
        tourTagDTO.setRank(tourTagDTO.getRank()==null?0:tourTagDTO.getRank());
        tourTagDTO.setIsHot(0);
        //保存标签
        int effectRows = mapper.save(tourTagDTO);
        if (effectRows==0){
            return effectRows;
        }
        if (CollectionUtils.isNotEmpty(tourTagBannerDTOS)) {
            //保存标签轮播图
            tourTagBannerDTOS.stream().peek(tourTagBannerDTO -> tourTagBannerDTO.setTagId(tourTagDTO.getId())).count();
            tourTagBannerBiz.saveBatch(tourTagBannerDTOS, userDTO);
        }
         return  effectRows;
    }

    /**
     * 根据主键修改标签状态
     * @param id
     * @param status
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateTourTagStateById(Integer id,int status) {
        //更改标签状态
        int effecttagRows = mapper.updateTourTagStatusById(id, status);
        if (effecttagRows ==0){
            return effecttagRows;
        }
        //更改标签对应的轮播图状态
        tourTagBannerBiz.updateTourTagBannerStatusByTagId(id,status);
        return effecttagRows;
    }

    /**
     *更改旅游标签信息
     * @param tourTagAndBannerDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateTourTag(TourTagAndBannerDTO tourTagAndBannerDTO, UserDTO userDTO) {
        if (log.isDebugEnabled()){
            log.debug("更改的旅游标签信息：[{}]",tourTagAndBannerDTO);
        }
        TourTagDTO tourTagDTO = tourTagAndBannerDTO.getTourTagDTO();
        //修改旅游标签信息
        tourTagDTO.setUpdTime(Instant.now().toEpochMilli());
         int effrows =  mapper.updateTourTag(tourTagDTO);
         if (effrows==0){
             return effrows;
         }
        //修改标签的相关轮播图
        List<TourTagBannerDTO> tourTagBannerDTOS = tourTagAndBannerDTO.getTourTagBannerDTOS();
         if (log.isDebugEnabled()){
             log.debug("更改标签对应的轮播图信息：[{}]",tourTagBannerDTOS);
         }
         if (CollectionUtils.isNotEmpty(tourTagBannerDTOS)){
             tourTagBannerDTOS.stream().filter(tourTagBannerDTO -> Objects.isNull(tourTagBannerDTO.getTagId())).peek(tourTagBannerDTO -> tourTagBannerDTO.setTagId(tourTagDTO.getId())).count();
         }
        tourTagBannerBiz.updateTourBannerByBatch(tourTagBannerDTOS,tourTagAndBannerDTO.getTourTagDTO().getId(),userDTO);
        return effrows;
    }

    /**
     * 更改旅游标签热度状态
     * @param id
     * @param state
     * @return
     */
    public int updateTourTagHotSate(Integer id, Integer state) {
         return  mapper.updateTourTagHotSate(id,state);
    }

    /**
     * 根据标签名查询是否存在
     * @param name
     * @return
     */
    public boolean checkTagNameExist(String name,Integer id) {
        List<TourTag> tourTags = mapper.findByTagName(name,id);
        return CollectionUtils.isNotEmpty(tourTags);
    }

    /**
     * 根据旅游标签状态查询
     * @param status
     * @return
     */
    public List<TourTag> findTourTagNameAndIdsByStatus(Integer status){
       return mapper.selectByStuatus(status);
    }
}