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.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.SysAdvice;
import com.mcwl.resource.domain.WorkFlow;
import com.mcwl.resource.domain.WorkFlowLike;
import com.mcwl.resource.domain.vo.WorkFlowLikeVo;
import com.mcwl.resource.mapper.WorkFlowLikeMapper;
import com.mcwl.resource.mapper.WorkFlowMapper;
import com.mcwl.resource.service.WorkFlowLikeService;
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;

/**
 * 工作流点赞
 * @Author：ChenYan
 * @Project：McWl
 * @Package：com.mcwl.resource.service.impl
 * @Filename：ModelLikeServiceImpl
 * @Description TODO
 * @Date：2025/1/12 12:05
 */
@Service
public class WorkFlowLikeServiceImpl extends ServiceImpl<WorkFlowLikeMapper, WorkFlowLike> implements WorkFlowLikeService {


    @Autowired
    private WorkFlowMapper workFlowMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Override
    @Transactional
    public void like(Long modelId) {
        WorkFlow workFlow = workFlowMapper.selectById(modelId);
        if (Objects.isNull(workFlow)) {
            throw new ServiceException("该工作流不存在或已下架");
        }
        Long userId = SecurityUtils.getUserId();
        WorkFlowLike workFlowLike = baseMapper.getLike(userId, modelId);
        if (Objects.nonNull(workFlowLike)) {
            if (Objects.equals(workFlowLike.getDelFlag(), "0")) {
                workFlowLike.setDelFlag("2");
                int likeCount = workFlow.getLikeCount() - 1;
                likeCount = Math.max(likeCount, 0);
                workFlow.setLikeCount(likeCount);
            } else {
                workFlowLike.setDelFlag("0");
                workFlow.setLikeCount(workFlow.getLikeCount() + 1);
                this.addLikeAdvice(workFlow);
            }
            // 更新点赞记录
            baseMapper.updateStatus(workFlowLike);
            // 更新图片点赞数
            workFlowMapper.updateById(workFlow);
            return;
        }

        // 添加点赞记录
        workFlowLike = new WorkFlowLike();
        workFlowLike.setUserId(userId);
        workFlowLike.setWorkFlowId(modelId);
        baseMapper.insert(workFlowLike);

        // 更新图片点赞数
        workFlow.setLikeCount(workFlow.getLikeCount() + 1);
        workFlowMapper.updateById(workFlow);

        this.addLikeAdvice(workFlow);
    }

    @Override
    public TableDataInfo listByPage(PageDomain pageDomain) {

        Page<WorkFlowLike> page = initPage(pageDomain);


        baseMapper.selectPage(page, null);

        List<WorkFlowLike> workFlowLikeList = page.getRecords();
        List<WorkFlowLikeVo> modelLikeVoList = new ArrayList<>();
        for (WorkFlowLike workFlowLike : workFlowLikeList) {
            WorkFlowLikeVo workFlowLikeVo = new WorkFlowLikeVo();
            BeanUtil.copyProperties(workFlowLike, workFlowLikeVo);

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

            // 获取工作流信息
            WorkFlow workFlow = workFlowMapper.selectById(workFlowLike.getWorkFlowId());
            if (Objects.isNull(workFlow)) {
                page.setTotal(page.getTotal() - 1);
                continue;
            }
            workFlowLikeVo.setConverPath(workFlow.getCoverPath());
            workFlowLikeVo.setLikeNum(workFlow.getLikeCount());

            modelLikeVoList.add(workFlowLikeVo);
        }


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

        return tableDataInfo;
    }

    @Override
    public WorkFlowLike selectWorkFlowLikeById(Long userId, Long id) {

        LambdaQueryWrapper<WorkFlowLike> workFlowLikeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        workFlowLikeLambdaQueryWrapper.eq(WorkFlowLike::getWorkFlowId,id);
        workFlowLikeLambdaQueryWrapper.eq(WorkFlowLike::getUserId,userId);

        return baseMapper.selectOne(workFlowLikeLambdaQueryWrapper);
    }


    private void addLikeAdvice(WorkFlow workFlow) {

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

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

        String content = StringUtils.format("恭喜！{}点赞了您的工作流：{}",
                SecurityUtils.getLoginUser().getUser().getNickName(), workFlow.getWorkflowName());

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


    }


    private Page<WorkFlowLike> initPage(PageDomain pageDomain) {
        Page<WorkFlowLike> 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;
    }

}
