package com.sckw.operation.service;

import java.util.*;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sckw.core.exception.SystemException;
import com.sckw.core.model.constant.Global;
import com.sckw.core.model.page.PageHelperUtil;
import com.sckw.core.model.page.PageResult;
import com.sckw.core.utils.BeanUtils;
import com.sckw.core.utils.CollectionUtils;
import com.sckw.core.utils.IdWorker;
import com.sckw.core.utils.StringUtils;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.operation.model.vo.req.BannerAddReqVo;
import com.sckw.operation.model.vo.req.BannerUpdateStatusReqVo;
import com.sckw.operation.model.vo.res.*;
import com.sckw.system.api.model.dto.res.UserCacheResDto;
import com.sckw.operation.dao.KwoBannerMapper;
import com.sckw.operation.model.vo.req.BannerQueryReqVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.sckw.operation.model.entity.KwoBanner;
import com.sckw.core.model.enums.BannerDistrictEnum;

/**
 * @author sky
 * @desc banner service
 * @date 2023/8/28
 */
@Slf4j
@Service
public class BannerService {

    @Autowired
    private KwoBannerMapper kwoBannerMapper;

    @Autowired
    private CommonBusinessService commonBusinessService;




    /**
     * @param reqVo 分页入参
     * @return HttpResult
     * @desc: 分页查询
     * @author: sky
     * @date: 2023/7/12
     */
    public PageResult queryByPage(BannerQueryReqVo reqVo) {
        PageHelper.startPage(reqVo.getPage(), reqVo.getPageSize());
        List<KwoBanner> kwoBannerList = findList(reqVo);
        if (CollectionUtils.isEmpty(kwoBannerList)) {
            return PageHelperUtil.getPageResult(new PageInfo<>());
        }
        List<BannerQueryResVo> list = getBannerQueryResVo(kwoBannerList);
        return PageHelperUtil.getPageResult(new PageInfo<>(list), kwoBannerList, reqVo.getPageSize());
    }

    /**
     * @param reqVo 分页入参
     * @return KwoBanner
     * @desc: 全量查询
     * @author: sky
     * @date: 2023/7/12
     */
    private List<KwoBanner> findList(BannerQueryReqVo reqVo) {
        LambdaQueryWrapper<KwoBanner> wrapper = new LambdaQueryWrapper<>();
        if(Objects.nonNull(reqVo.getDistrict()))
        {
            reqVo.setStatus(1);
        }
        wrapper.eq(Objects.nonNull(reqVo.getStatus()), KwoBanner::getStatus, reqVo.getStatus()).
                eq(KwoBanner::getDelFlag, Global.NO).
                and(StringUtils.isNotBlank(reqVo.getKeywords()),
                        wq -> wq.like(KwoBanner::getUrl, reqVo.getKeywords())).
                orderByDesc(KwoBanner::getDistrict,KwoBanner::getSort);

        if (Objects.nonNull(reqVo.getStartTime())) {
            wrapper.lt(KwoBanner::getStartTime, reqVo.getStartTime()).or().eq(KwoBanner::getStartTime,null);;
        }
        if(Objects.nonNull(reqVo.getDistrict())) {
            wrapper.eq(KwoBanner::getDistrict, reqVo.getDistrict());
        }

        if (Objects.nonNull(reqVo.getEndTime())) {
            wrapper.gt(KwoBanner::getEntTime, DateUtil.offsetDay(reqVo.getEndTime(), 1)).or().eq(KwoBanner::getEntTime,null);
        }
        if(Objects.nonNull(reqVo.getDistrict()))
        {
            Date date = new Date();
            wrapper.lt(KwoBanner::getStartTime, date).or().eq(KwoBanner::getStartTime,null);
            wrapper.gt(KwoBanner::getEntTime, date).or().eq(KwoBanner::getEntTime,null);
        }

        if (StringUtils.isNotBlank(reqVo.getIds())) {
            wrapper.in(KwoBanner::getId, Arrays.stream(reqVo.getIds().split(Global.COMMA)).map(Long::parseLong).toList());
        }
        return kwoBannerMapper.selectList(wrapper);
    }


    /**
     * @return BannerQueryResVo
     * @desc: 转换成vo
     * @param: KwoBanner 实体
     * @author: sky
     * @date 2023/7/18
     */
    private List<BannerQueryResVo> getBannerQueryResVo(List<KwoBanner> kwoBanner) {
        List<BannerQueryResVo> list = new ArrayList<>();
        List<Long> userIds = kwoBanner.stream().map(KwoBanner::getCreateBy).distinct().toList();

        Map<Long, UserCacheResDto> userCacheResDtoMap = commonBusinessService.queryUserCacheMapByIds(userIds);

        kwoBanner.forEach(item -> {
            BannerQueryResVo bannerQueryResVo = new BannerQueryResVo();
            BeanUtils.copyProperties(item, bannerQueryResVo);
            UserCacheResDto userCacheResDto = userCacheResDtoMap.get(item.getCreateBy());

            if (Objects.nonNull(userCacheResDto)) {
                bannerQueryResVo.setCreateByName(userCacheResDto.getName());
            }

            if (Objects.nonNull(item.getDistrict())) {
                bannerQueryResVo.setDistrictName(BannerDistrictEnum.getName(item.getDistrict()).getName());
            }

            list.add(bannerQueryResVo);
        });
        return list;
    }

    /**
     * @param reqVo 新增入参
     * @desc: 新增banner
     * @author: sky
     * @date: 2023/8/29
     */
    @Transactional(rollbackFor = {})
    public void addService(BannerAddReqVo reqVo) {
        KwoBanner kwoBanner = new KwoBanner();
        BeanUtils.copyProperties(reqVo, kwoBanner);
        Long userId = LoginUserHolder.getUserId();
        Date date = new Date();
        kwoBanner.setDelFlag(Global.NO);
        kwoBanner.setStatus(reqVo.getStatus());
        kwoBanner.setCreateBy(userId);
        kwoBanner.setUpdateBy(userId);
        kwoBanner.setCreateTime(date);
        kwoBanner.setUpdateTime(date);
        kwoBanner.setId(new IdWorker(1L).nextId());
        if (kwoBannerMapper.insert(kwoBanner) <= 0) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.INSERT_FAIL);
        }
    }

    /**
     * @param reqVo 更新入参
     * @desc: 更新banner
     * @author: sky
     * @date: 2023/8/29
     */
    @Transactional(rollbackFor = {})
    public void udpateService(BannerAddReqVo reqVo) {
        KwoBanner kwobanner = kwoBannerMapper.selectById(reqVo.getId());
        if (Objects.isNull(kwobanner)) {
            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.BANNER_NOT_EXISTS);
        }
        BeanUtils.copyProperties(reqVo, kwobanner);
        Date date = new Date();
        Long userId = LoginUserHolder.getUserId();
        kwobanner.setUpdateTime(date);
        kwobanner.setUpdateBy(userId);
        if (kwoBannerMapper.updateById(kwobanner) <= 0) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.UPDATE_FAIL);
        }
    }

    /**
     * @param ids 主键
     * @desc: 删除
     * @author: sky
     * @date: 2023/8/29
     */
    @Transactional(rollbackFor = {})
    public void deleteServer(String ids) {
        List<Long> idList = Arrays.stream(ids.split(Global.COMMA)).map(Long::parseLong).toList();
        List<KwoBanner> kwoBanner = kwoBannerMapper.selectBatchIds(idList);
        if (CollectionUtils.isEmpty(kwoBanner)) {
            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.ADDRESS_NOT_EXISTS);
        }

        Long userId = LoginUserHolder.getUserId();
        Date date = new Date();
        kwoBanner.forEach(item -> {
            item.setUpdateTime(date);
            item.setUpdateBy(userId);
            item.setDelFlag(Global.YES);

            if (kwoBannerMapper.updateById(item) <= 0) {
                throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.DELETE_FAIL);
            }
        });
    }

    /**
     * @param id 主键
     * @return AddressDetailResVo
     * @desc: 查详情
     * @author: czh
     * @date: 2023/7/25
     */
    public BannerDetailResVo detailServer(Long id) {
        KwoBanner kwoBanner = kwoBannerMapper.selectById(id);
        if (Objects.isNull(kwoBanner) || kwoBanner.getDelFlag().equals(Global.YES)) {
            return null;
        }

        BannerDetailResVo bannerDetailResVo = new BannerDetailResVo();
        BeanUtils.copyProperties(kwoBanner, bannerDetailResVo);
        return bannerDetailResVo;
    }

    /**
     * @return HttpResult
     * @desc: 获取分类
     * @author: sky
     * @date: 2023/7/12
     */
    public List<BannerCategoryResVo> getCategory() {
        BannerDistrictEnum[] values =  BannerDistrictEnum.values();
        List<BannerCategoryResVo> list = new ArrayList<>();
        for (BannerDistrictEnum bannerDistrictEnum : values) {
            BannerCategoryResVo bannerCategoryResVo = new BannerCategoryResVo();
            bannerCategoryResVo.setCode(bannerDistrictEnum.getCode());
            bannerCategoryResVo.setName(bannerDistrictEnum.getName());
            list.add(bannerCategoryResVo);
        }
        return list;
    }

    /**
     * @param reqVo 上架下架入参
     * @desc: 更新banner
     * @author: sky
     * @date: 2023/8/29
     */
    @Transactional(rollbackFor = {})
    public void updateStatusServer(BannerUpdateStatusReqVo reqVo) {
        KwoBanner kwobanner = kwoBannerMapper.selectById(reqVo.getId());
        if (Objects.isNull(kwobanner)) {
            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.BANNER_NOT_EXISTS);
        }
        //BeanUtils.copyProperties(reqVo, kwobanner);
        Date date = new Date();
        Long userId = LoginUserHolder.getUserId();
        kwobanner.setUpdateTime(date);
        kwobanner.setUpdateBy(userId);
        kwobanner.setStatus(reqVo.getStatus());
        if (kwoBannerMapper.updateById(kwobanner) <= 0) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.UPDATE_FAIL);
        }
    }

}
