package com.zxdmy.excite.system.service.impl.cloud.space;

import cn.dev33.satoken.stp.StpUtil;
import com.zxdmy.excite.common.entity.PageList;
import com.zxdmy.excite.common.enums.CloudCode;
import com.zxdmy.excite.common.enums.SystemCode;
import com.zxdmy.excite.common.exception.ServiceException;
import com.zxdmy.excite.system.entity.SysUser;
import com.zxdmy.excite.system.entity.cloud.role.CloudRole;
import com.zxdmy.excite.system.entity.cloud.space.CloudFile;
import com.zxdmy.excite.system.entity.cloud.space.CloudFileRole;
import com.zxdmy.excite.system.entity.req.space.ReqCloudFile;
import com.zxdmy.excite.system.entity.req.trace.ReqCloudFileTrace;
import com.zxdmy.excite.system.entity.vo.space.CloudFileRoleVo;
import com.zxdmy.excite.system.entity.vo.space.CloudFileVo;
import com.zxdmy.excite.system.mapper.SysUserMapper;
import com.zxdmy.excite.system.mapper.cloud.space.CloudFileMapper;
import com.zxdmy.excite.system.mapper.cloud.space.CloudFileRoleMapper;
import com.zxdmy.excite.system.service.cloud.space.ICloudFileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxdmy.excite.system.service.cloud.trace.ICloudFileTraceService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 文件表 服务实现类
 * </p>
 *
 * @author ss
 * @since 2026-01-28
 */
@Service
@AllArgsConstructor
public class CloudFileServiceImpl extends ServiceImpl<CloudFileMapper, CloudFile> implements ICloudFileService {

    private CloudFileMapper cloudFileMapper;
    private SysUserMapper sysUserMapper;
    private CloudFileRoleMapper cloudFileRoleMapper;
    private ICloudFileTraceService iCloudFileTraceService;

    @Override
    public PageList<CloudFileVo> queryByPage(Integer page, Integer limit, ReqCloudFile data) {
        Integer pages = limit * (page - 1);
        ArrayList<CloudFileVo> list = cloudFileMapper.queryByPage(pages, limit,data);
        Integer count = cloudFileMapper.queryByPageCount(data);
        return new PageList<CloudFileVo>(list,page,limit,count);
    }


    @Override
    public PageList<CloudFileVo> queryByRecyclePage(Integer page, Integer limit, ReqCloudFile data) {
        Integer pages = limit * (page - 1);
        ArrayList<CloudFileVo> list = cloudFileMapper.queryByRecyclePage(pages, limit,data);
        Integer count = cloudFileMapper.queryByRecyclePageCount(data);
        return new PageList<CloudFileVo>(list,page,limit,count);
    }
    @Override
    public CloudFileVo getByData(ReqCloudFile data) {
        return cloudFileMapper.getData(data);
    }

    @Override
    public int saveData(ReqCloudFile data) {
        LocalDateTime localDateTime = LocalDateTime.now();
        CloudFile saveData = new CloudFile();
        saveData.setFileName(data.getFileName());
        saveData.setFileFormat(CloudCode.FOLDER_NAME.getCode());
        saveData.setFileFolder(Integer.valueOf(SystemCode.FOLDER_Y.getCode()));
        saveData.setFileImage(CloudCode.FOLDER_IMAGE.getCode());
        saveData.setFileSort(0);

        if(data.getFileParentId().equals("0")){
            saveData.setFileTopId(Long.valueOf("0"));
            saveData.setFileParentId(Long.valueOf("0"));
        }else{
            saveData.setFileTopId(Long.valueOf(data.getFileParentId()));
            saveData.setFileParentId(Long.valueOf(data.getFileParentId()));
        }
        SysUser sysUser = sysUserMapper.selectById(StpUtil.getLoginIdAsInt());
        saveData.setCreatorId(sysUser.getId());
        saveData.setCreatorName(sysUser.getUsername());
        saveData.setCreateTime(localDateTime);
        if(cloudFileMapper.insert(saveData)==1){
            for (Integer userId:data.getIds()) {
                CloudFileRole cloudFileRole = new CloudFileRole();
                cloudFileRole.setFileId(saveData.getId());
                cloudFileRole.setUserId(userId);
                cloudFileRoleMapper.insert(cloudFileRole);
            }
            return 1;
        }
        return 0;
    }


    @Override
    public int saveFileData(ReqCloudFile data) {
        LocalDateTime localDateTime = LocalDateTime.now();
        CloudFile saveData = new CloudFile();
        String[] file = data.getFileName().split("\\.");
        String fileName = null;
        String format = null;
        if(file.length>0) {
            fileName = file[0].toString();
            format = file[1].toString();
            saveData.setFileName(fileName);
            saveData.setFileFormat(format);

        }
        saveData.setFileTop(0);
        saveData.setFileName(fileName);
        saveData.setFileFormat(format);
        saveData.setFileFolder(Integer.valueOf(SystemCode.FOLDER_N.getCode()));
        saveData.setFileImage(CloudCode.PDF_IMAGE.getCode());
        saveData.setFileSort(0);
        saveData.setFileSize(data.getFileSize());
        saveData.setFileOss(data.getFileOss());
        if(data.getFileParentId().equals("0")){
            saveData.setFileTopId(Long.valueOf("0"));
            saveData.setFileParentId(Long.valueOf("0"));
        }else{
            saveData.setFileTopId(Long.valueOf(data.getFileParentId()));
            saveData.setFileParentId(Long.valueOf(data.getFileParentId()));
        }
        SysUser sysUser = sysUserMapper.selectById(StpUtil.getLoginIdAsInt());
        saveData.setCreatorId(sysUser.getId());
        saveData.setCreatorName(sysUser.getUsername());
        saveData.setCreateTime(localDateTime);
        if(cloudFileMapper.insert(saveData)==1){


            ReqCloudFileTrace reqCloudFileTrace = new ReqCloudFileTrace();
            reqCloudFileTrace.setFileId(saveData.getId().toString());
            reqCloudFileTrace.setTraceName("上传了 "+fileName+" 文件");
            iCloudFileTraceService.saveData(reqCloudFileTrace);


            return 1;
        }
        return 0;
    }

    @Override
    public int updateFileData(ReqCloudFile data) {
        LocalDateTime localDateTime = LocalDateTime.now();
        CloudFile saveData = cloudFileMapper.selectById(data.getId());
        saveData.setFileOss(data.getFileOss());
        saveData.setFileSize(data.getFileSize());
        SysUser sysUser = sysUserMapper.selectById(StpUtil.getLoginIdAsInt());
        saveData.setUpdaterId(sysUser.getId());
        saveData.setUpdaterName(sysUser.getUsername());
        saveData.setUpdateTime(localDateTime);
        if(cloudFileMapper.updateById(saveData)==1){

            ReqCloudFileTrace reqCloudFileTrace = new ReqCloudFileTrace();
            reqCloudFileTrace.setFileId(saveData.getId().toString());
            reqCloudFileTrace.setTraceName("替换了 "+saveData.getFileName()+" 文件");
            iCloudFileTraceService.saveData(reqCloudFileTrace);

            return 1;
        }
        return 0;
    }


    @Override
    public int updateData(ReqCloudFile data) {
        LocalDateTime localDateTime = LocalDateTime.now();

        CloudFile updateData = new CloudFile();
        updateData.setId(Long.valueOf(data.getId()));
        updateData.setFileName(data.getFileName());


        SysUser sysUser = sysUserMapper.selectById(StpUtil.getLoginIdAsInt());
        updateData.setUpdateTime(localDateTime);
        updateData.setUpdaterId(sysUser.getId());
        updateData.setUpdaterName(sysUser.getUsername());
        if(cloudFileMapper.updateById(updateData)==1){

            List<CloudFileRoleVo> roleList = cloudFileRoleMapper.getFileRole(data.getId());
            for (CloudFileRoleVo cloudFileRoleVo:roleList) {
                cloudFileRoleMapper.deleteById(cloudFileRoleVo.getId());
            }

            if(null!=data.getIds()){
                for (Integer userId:data.getIds()) {
                    CloudFileRole cloudFileRole = new CloudFileRole();
                    cloudFileRole.setFileId(updateData.getId());
                    cloudFileRole.setUserId(userId);
                    cloudFileRoleMapper.insert(cloudFileRole);
                }
            }



            return 1;
        }
        return 0;
    }
    @Override
    public int recover(String id) {
        LocalDateTime localDateTime = LocalDateTime.now();

        CloudFile updateData = cloudFileMapper.selectById(id);
        updateData.setDeleteId(null);
        updateData.setDeleteName(null);
        updateData.setDeleteTime(null);

        SysUser sysUser = sysUserMapper.selectById(StpUtil.getLoginIdAsInt());
        updateData.setUpdateTime(localDateTime);
        updateData.setUpdaterId(sysUser.getId());
        updateData.setUpdaterName(sysUser.getUsername());
        if(cloudFileMapper.updateById(updateData)==1){

            ReqCloudFileTrace reqCloudFileTrace = new ReqCloudFileTrace();
            reqCloudFileTrace.setFileId(id);
            reqCloudFileTrace.setTraceName("恢复了 "+updateData.getFileName()+" 文件");
            iCloudFileTraceService.saveData(reqCloudFileTrace);

            return 1;
        }
        return 0;
    }
    @Override
    public int deleteById(String id) {
        if (null == id) {
            throw new ServiceException("删除的ID不能为空！");
        }
        LocalDateTime localDateTime = LocalDateTime.now();
        SysUser sysUser = sysUserMapper.selectById(StpUtil.getLoginIdAsInt());
        CloudFile data = cloudFileMapper.selectById(id);
        if(null!=data){
            data.setDeleteId(sysUser.getId());
            data.setDeleteName(sysUser.getUsername());
            data.setDeleteTime(localDateTime);


            ReqCloudFileTrace reqCloudFileTrace = new ReqCloudFileTrace();
            reqCloudFileTrace.setFileId(id);
            reqCloudFileTrace.setTraceName("删除了 "+data.getFileName()+" 文件");
            iCloudFileTraceService.saveData(reqCloudFileTrace);
            return cloudFileMapper.updateById(data);
        }else{
            return 0;
        }
    }

    @Override
    public int[] changeDeleteStatus(Integer newStatus, String[] ids) {
        /// 信息不能为空
        if (null == newStatus || null == ids) {
            throw new ServiceException("新状态或ID不能为空");
        }
        // 新状态只能为 0 | 1
        if (newStatus == 0 || newStatus == 1) {
            int[] result = new int[2];
            for (String id : ids) {
                CloudFile data = cloudFileMapper.selectById(id);
                data.setFileTop(newStatus);
                if (cloudFileMapper.updateById(data) > 0) {
                    result[0]++;
                } else result[1]++;
            }
            // 返回结果
            return result;
        } else {
            throw new ServiceException("新状态只能为0或1！");
        }
    }

    @Override
    public PageList<CloudFileVo> queryByIndexPage(Integer page, Integer limit, ReqCloudFile data) {
        Integer pages = limit * (page - 1);
        ArrayList<CloudFileVo> list = cloudFileMapper.queryByIndexPage(pages, limit,data);
        Integer count = cloudFileMapper.queryByIndexPageCount(data);
        return new PageList<CloudFileVo>(list,page,limit,count);
    }


    @Override
    public List<CloudFileVo> queryFileByData(ReqCloudFile data) {
        return cloudFileMapper.queryFileByData(data);
    }
}
