package com.mcwl.resource.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mcwl.common.constant.HttpStatus;
import com.mcwl.common.core.domain.R;
import com.mcwl.common.utils.SecurityUtils;
import com.mcwl.resource.domain.Collect;
import com.mcwl.resource.domain.WorkFlow;
import com.mcwl.resource.domain.WorkFlowVersion;
import com.mcwl.resource.mapper.WorkFlowMapper;
import com.mcwl.resource.mapper.WorkFlowVersionMapper;
import com.mcwl.resource.service.WorkFlowVersionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 工作流版本 业务实现层
 *
 * @author DaiZibo
 * @date 2025/1/9
 * @apiNote
 */

@Service
public class WorkFlowVersionServiceImpl implements WorkFlowVersionService {

    @Autowired
    private WorkFlowVersionMapper workFlowVersionMapper;

    @Autowired
    private WorkFlowMapper workFlowMapper;

    @Autowired
    private CollectServiceImpl collectService;


    @Override
    public R<List<WorkFlowVersion>> selectVersionByWorkId(Long workId) {

        LambdaQueryWrapper<WorkFlowVersion> workFlowVersionLambdaQueryWrapper = new LambdaQueryWrapper<>();

        workFlowVersionLambdaQueryWrapper.eq(WorkFlowVersion::getDelFlag, 0);
        workFlowVersionLambdaQueryWrapper.eq(WorkFlowVersion::getWorkFlowId, workId);

        List<WorkFlowVersion> workFlowVersions = workFlowVersionMapper.selectList(workFlowVersionLambdaQueryWrapper);
        Long userIdMax = SecurityUtils.getUserIdMax();
        if (userIdMax != 0) {
            for (WorkFlowVersion workFlowVersion : workFlowVersions) {
                workFlowVersion.setFilePath("");
                //模型字典 0 工作流字典 1
                Integer type = 1;
                //校验是否收藏
                Collect collect = collectService.selectCollectById(workFlowVersion.getId(), userIdMax, type);
                if (collect != null) {
                    workFlowVersion.setIsCollect(1);
                }
            }
        }

        return R.ok(workFlowVersions);
}

    @Override
    public R workFlowFileDownload(Long id) {

        //查找数据
        WorkFlowVersion workFlowVersion = workFlowVersionMapper.selectById(id);
        if (workFlowVersion == null) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG,"文件不存在");
        }

        WorkFlow workFlow = workFlowMapper.selectById(workFlowVersion.getWorkFlowId());
        if (workFlow.getDownload().equals(1)) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG,"该文件不允许下载");
        }

        //更新下载次数
        workFlow.setDownloadNumber(workFlow.getDownloadNumber()+1);
        workFlowMapper.updateById(workFlow);

        return R.ok(workFlowVersion.getFilePath(), workFlowVersion.getFileName());
    }
}
