package com.mcwl.resource.service.impl;

import cn.hutool.core.bean.BeanUtil;
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.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.ModelLike;
import com.mcwl.resource.domain.ModelProduct;
import com.mcwl.resource.domain.SysAdvice;
import com.mcwl.resource.domain.vo.ModelLikeVo;
import com.mcwl.resource.mapper.ModelLikeMapper;
import com.mcwl.resource.mapper.ModelMapper;
import com.mcwl.resource.service.ModelLikeService;
import com.mcwl.system.domain.enums.AdviceEnum;
import com.mcwl.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
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
public class ModelLikeServiceImpl extends ServiceImpl<ModelLikeMapper, ModelLike> implements ModelLikeService {


    @Autowired
    private ModelMapper modelMapper;

    @Autowired
    private ISysUserService sysUserService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void like(Long modelId) {
        ModelProduct model = modelMapper.selectById(modelId);
        if (Objects.isNull(model)) {
            throw new ServiceException("该模型不存在或已下架");
        }
        Long userId = SecurityUtils.getUserId();
        ModelLike modelLike = baseMapper.getLike(userId, modelId);
        if (Objects.nonNull(modelLike)) {
            if (Objects.equals(modelLike.getDelFlag(), "0")) {
                modelLike.setDelFlag("2");
                int likeNum = model.getLikeNum() - 1;
                likeNum = Math.max(likeNum, 0);
                model.setLikeNum(likeNum);
            } else {
                modelLike.setDelFlag("0");
                model.setLikeNum(model.getLikeNum() + 1);
                this.addLikeAdvice(model);
            }
            // 更新点赞记录
            baseMapper.updateDelFlagById(modelLike);
            // 更新图片点赞数
            modelMapper.updateById(model);
            return;
        }

        // 添加点赞记录
        modelLike = new ModelLike();
        modelLike.setUserId(userId);
        modelLike.setModelId(modelId);
        baseMapper.insert(modelLike);

        // 更新图片点赞数
        model.setNumbers(model.getLikeNum() + 1);
        modelMapper.updateById(model);

        this.addLikeAdvice(model);
    }

    @Override
    public TableDataInfo listByPage(PageDomain pageDomain) {
        Page<ModelLike> page = initPage(pageDomain);


        baseMapper.selectPage(page, null);

        List<ModelLike> modelLikeList = page.getRecords();
        List<ModelLikeVo> modelLikeVoList = new ArrayList<>();
        for (ModelLike modelLike : modelLikeList) {
            ModelLikeVo modelLikeVo = new ModelLikeVo();
            BeanUtil.copyProperties(modelLike, modelLikeVo);

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

            // 获取模型信息
            ModelProduct modelProduct = modelMapper.selectById(modelLike.getModelId());
            if (Objects.isNull(modelProduct)) {
                page.setTotal(page.getTotal() - 1);
                continue;
            }
            modelLikeVo.setSurfaceUrl(modelProduct.getSurfaceUrl());
            modelLikeVo.setModelName(modelProduct.getModelName());

            modelLikeVoList.add(modelLikeVo);
        }


        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setRows(modelLikeVoList);
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        tableDataInfo.setMsg("查询成功");

        return tableDataInfo;


    }



    private void addLikeAdvice(ModelProduct model) {

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

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

        String content = StringUtils.format("恭喜！{}点赞了您的模型：{}",
                SecurityUtils.getLoginUser().getUser().getNickName(), model.getModelName());

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


    }

    private Page<ModelLike> initPage(PageDomain pageDomain) {
        Page<ModelLike> page = new Page<>(pageDomain.getPageNum(), pageDomain.getPageSize());
        if (StringUtils.isBlank(pageDomain.getOrderByColumn())) {
            pageDomain.setOrderByColumn("create_time");
        }
        OrderItem orderItem = OrderItem.desc(pageDomain.getOrderByColumn());
        page.addOrder(orderItem);

        return page;
    }


}
