package com.mcwl.resource.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mcwl.common.constant.HttpStatus;
import com.mcwl.common.core.domain.entity.SysUser;
import com.mcwl.common.core.page.PageDomain;
import com.mcwl.common.core.page.TableDataInfo;
import com.mcwl.common.exception.ServiceException;
import com.mcwl.common.utils.SecurityUtils;
import com.mcwl.common.utils.StringUtils;
import com.mcwl.resource.domain.ModelImage;
import com.mcwl.resource.domain.ModelImageLike;
import com.mcwl.resource.domain.SysAdvice;
import com.mcwl.resource.domain.response.ResponseModelImage;
import com.mcwl.resource.domain.vo.ModelImageLikeVo;
import com.mcwl.resource.domain.vo.PageVo;
import com.mcwl.resource.mapper.ModelImageLikeMapper;
import com.mcwl.resource.mapper.ModelImageMapper;
import com.mcwl.resource.service.ModelImageLikeService;
import com.mcwl.system.domain.enums.AdviceEnum;
import com.mcwl.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 图片点赞实现
 */
@Service
@RequiredArgsConstructor
public class ModelImageLikeServiceImpl extends ServiceImpl<ModelImageLikeMapper, ModelImageLike> implements ModelImageLikeService {

    private final ModelImageMapper modelImageMapper;

    private final ISysUserService sysUserService;

    @Override
    @Transactional
    public void like(Long imageId) {
        ModelImage modelImage = modelImageMapper.selectById(imageId);
        if (Objects.isNull(modelImage)) {
            throw new ServiceException("该图片不存在或已下架");
        }
        Long userId = SecurityUtils.getUserId();
        ModelImageLike modelImageLike = baseMapper.getLikeImage(userId, imageId);
        if (Objects.nonNull(modelImageLike)) {
            if (Objects.equals(modelImageLike.getDelFlag(), "0")) {
                modelImageLike.setDelFlag("2");
                int likeNum = modelImage.getLikeNum() - 1;
                likeNum = Math.max(likeNum, 0);
                modelImage.setLikeNum(likeNum);
            } else {
                modelImageLike.setDelFlag("0");
                modelImage.setLikeNum(modelImage.getLikeNum() + 1);
                this.addLikeAdvice(modelImage);
            }
            // 更新点赞记录
            baseMapper.updateDelFlagById(modelImageLike);
            // 更新图片点赞数
            modelImageMapper.updateById(modelImage);
            return;
        }

        // 添加点赞记录
        modelImageLike = new ModelImageLike();
        modelImageLike.setUserId(userId);
        modelImageLike.setModelImageId(imageId);
        baseMapper.insert(modelImageLike);

        // 更新图片点赞数
        modelImage.setLikeNum(modelImage.getLikeNum() + 1);
        modelImageMapper.updateById(modelImage);

        this.addLikeAdvice(modelImage);
    }

    @Override
    public void setModelImageTop(Long id, boolean isTop) {
        modelImageMapper.setModelImageTop(id,isTop?1:0);
    }

    @Override
    public List<ModelImage> fetchModelImageSortedByTopStatus() {
        return modelImageMapper.fetchModelImageSortedByTopStatus();
    }



    /**
     * 分页查询
     *
     * @param pageDomain 分页参数
     * @return 分页数据
     */
    @Override
    public TableDataInfo listByPage(PageDomain pageDomain) {

        Page<ModelImageLike> page = new Page<>(pageDomain.getPageNum(), pageDomain.getPageSize());
        if (StringUtils.isEmpty(pageDomain.getOrderByColumn())) {
            pageDomain.setOrderByColumn("create_time");
        }
        // 设置排序
        boolean isAsc = Objects.equals(pageDomain.getIsAsc(), "desc");
        OrderItem orderItem = new OrderItem(pageDomain.getOrderByColumn(), isAsc);
        page.addOrder(orderItem);

        baseMapper.selectPage(page, null);
        // 获取分页数据
        List<ModelImageLike> modelImageList = page.getRecords();

        // ModelImage数据转为ModelImagePageVo
        List<ModelImageLikeVo> modelImageLikeVoList = new ArrayList<>();
        for (ModelImageLike modelImageLike : modelImageList) {
            ModelImageLikeVo modelImageLikeVo = new ModelImageLikeVo();
            BeanUtil.copyProperties(modelImageLike, modelImageLikeVo);

            // 获取用户信息
            SysUser sysUser = sysUserService.selectUserById(modelImageLike.getUserId());
            if (Objects.isNull(sysUser)) {
                page.setTotal(page.getTotal() - 1);
                continue;
            }
            modelImageLikeVo.setUserName(sysUser.getNickName());
            modelImageLikeVo.setUserAvatar(sysUser.getAvatar());

            // 获取图片信息
            ModelImage modelImage = modelImageMapper.selectById(modelImageLike.getModelImageId());
            if (Objects.isNull(modelImage)) {
                page.setTotal(page.getTotal() - 1);
                continue;
            }
            modelImageLikeVo.setImagePaths(modelImage.getImagePaths());
            modelImageLikeVo.setLikeNum(modelImage.getLikeNum());


            modelImageLikeVoList.add(modelImageLikeVo);

        }

        // 封装分页数据
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(modelImageLikeVoList);
        rspData.setTotal(page.getTotal());

        return rspData;
    }

    @Override
    public PageInfo<ResponseModelImage> imageList(PageVo pageVo) {

        PageHelper pageHelper = new PageHelper();
        pageHelper.startPage(pageVo.getPageNumber(),pageVo.getPageSize());

        List<ResponseModelImage> responseModelImageList = modelImageMapper.imageList(pageVo);

        List<Long> modelImageLikeIds = new ArrayList<>();

        List<ModelImageLike> modelImageLikes = baseMapper.selectList(new LambdaQueryWrapper<ModelImageLike>()
                .eq(ModelImageLike::getUserId, SecurityUtils.getUserIdMax()));
        for (ModelImageLike modelImageLike : modelImageLikes) {
            modelImageLikeIds.add(modelImageLike.getModelImageId());
        }


        for (ResponseModelImage responseModelImage : responseModelImageList) {

            String[] split = responseModelImage.getImagePaths().split(",");
            responseModelImage.setPath(split[0]);

            //查询是否点赞
            if (!modelImageLikeIds.contains(responseModelImage.getId())){
                responseModelImage.setIsLike(0);
            }else {
                responseModelImage.setIsLike(1);
            }
        }

        return new PageInfo<>(responseModelImageList);

    }



    private void addLikeAdvice(ModelImage modelImage) {

        Long userId = SecurityUtils.getUserId();
        Long receiverUserId = modelImage.getUserId();

        if (Objects.equals(userId, receiverUserId)) {
            return;
        }

        String content = StringUtils.format("恭喜！{}点赞了您的图片：{}",
                SecurityUtils.getLoginUser().getUser().getNickName(), modelImage.getTitle());

        SysAdvice sysAdvice = new SysAdvice();
        sysAdvice.setSenderId(userId);
        sysAdvice.setReceiverId(receiverUserId);
        sysAdvice.setContent(content);
        sysAdvice.setProductId(modelImage.getId());
        sysAdvice.setProductType(2);
        sysAdvice.setIsRead(0);
        sysAdvice.setType(AdviceEnum.LIKE_REMIND);


    }


}
