package com.citygis.web.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.citygis.common.annotation.DataScope;
import com.citygis.common.config.CitygisConfig;
import com.citygis.common.core.domain.AjaxResult;
import com.citygis.common.utils.file.FileUploadUtils;
import com.citygis.web.domain.TabFileInfo;
import com.citygis.web.mapper.TabFileInfoMapper;
import com.citygis.web.service.ITabFileInfoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import static com.citygis.common.utils.SecurityUtils.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author citygis
 * @since 2025-01-02
 */
@Service
public class TabFileInfoServiceImpl extends ServiceImpl<TabFileInfoMapper, TabFileInfo> implements ITabFileInfoService {

    @Resource
    TabFileInfoMapper tabFileInfoMapper;

    @Override
    @DataScope(deptAlias = "tfi", userAlias = "tfi")
    public List<TabFileInfo> getTabFileInfoList(TabFileInfo tabFileInfo) {
        return tabFileInfoMapper.getTabFileInfoList(tabFileInfo);

    }

    @Override
    @Transactional
    public AjaxResult insertTabFileInfo(MultipartFile file, TabFileInfo tabFileInfo) throws Exception {
        String filePath = CitygisConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        tabFileInfo.setFilePath(fileName);
        tabFileInfo.setFileName(file.getOriginalFilename());

        tabFileInfo.setCreateBy(getUsername());
        tabFileInfo.setCreateTime(new Date());
        tabFileInfo.setUserId(getUserId());
        tabFileInfo.setDeptId(getDeptId());

        boolean b = this.save(tabFileInfo);
        if (b) {
            return AjaxResult.success("上传成功");
        } else {
            return AjaxResult.success("上传失败");
        }
    }

    @Override
    public String getFilePathById(String fileId) {
        TabFileInfo byId = this.getById(fileId);
        return byId.getFilePath();
    }

    @Override
    public AjaxResult updateTabFileInfoById(TabFileInfo tabFileInfo) {
        tabFileInfo.setUpdateBy(getUsername());
        tabFileInfo.setUpdateTime(new Date());
        boolean b = this.updateById(tabFileInfo);
        if (b) {
            return AjaxResult.success("修改成功");
        } else {
            return AjaxResult.success("修改失败");
        }
    }

    @Override
    public AjaxResult falseDeleteTabFileInfoById(Integer fileId) {
        TabFileInfo tabFileInfo = new TabFileInfo();
        tabFileInfo.setFileId(fileId);
        tabFileInfo.setIsDel(1);
        boolean b = this.updateById(tabFileInfo);
        if (b) {
            return AjaxResult.success("删除成功");
        } else {
            return AjaxResult.success("删除失败");
        }
    }
}
