package com.ruoyi.web.controller.file;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SnowFlake;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.file.domain.FilesAchievement;
import com.ruoyi.file.domain.FilesStorage;
import com.ruoyi.file.service.IFilesAchievementService;
import com.ruoyi.file.service.IFilesStorageService;
import com.ruoyi.oa.domain.CmcProject;
import com.ruoyi.oa.service.ICmcProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 成果表Controller
 *
 * @author cmc
 * @date 2022-09-06
 */
@RestController
@RequestMapping("/file/achievement")
public class FilesAchievementController extends BaseController
{
    @Autowired
    private IFilesAchievementService filesAchievementService;

    @Autowired
    private ICmcProjectService cmcProjectService;

    @Autowired
    private IFilesStorageService filesStorageService;

    @Value("${cmc.profile}")
    private String profile;
    /**
     * 查询成果表列表
     */
    @GetMapping("/list")
    public TableDataInfo list(FilesAchievement filesAchievement)
    {
        startPage();
        List<FilesAchievement> list = filesAchievementService.selectFilesAchievementList(filesAchievement);
        return getDataTable(list);
    }

    /**
     * 导出成果表列表
     */
    @Log(title = "成果表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FilesAchievement filesAchievement)
    {
        List<FilesAchievement> list = filesAchievementService.selectFilesAchievementList(filesAchievement);
        ExcelUtil<FilesAchievement> util = new ExcelUtil<FilesAchievement>(FilesAchievement.class);
        util.exportExcel(response, list, "成果表数据");
    }

    /**
     * 导出选中成果表列表
     */
    @Log(title = "成果表", businessType = BusinessType.EXPORT)
    @PostMapping("/exportBatch/{ids}")
    public void exportBatch(HttpServletResponse response, FilesAchievement filesAchievement, @PathVariable("ids") String[] ids)
    {
        List<FilesAchievement> list = new ArrayList<>();
        for (String achievementId : ids)
            list.add(filesAchievementService.selectFilesAchievementById(achievementId));
        ExcelUtil<FilesAchievement> util = new ExcelUtil<FilesAchievement>(FilesAchievement.class);
        util.exportExcel(response, list, "成果表数据");
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<FilesAchievement> util = new ExcelUtil<FilesAchievement>(FilesAchievement.class);
        util.importTemplateExcel(response, "成果表模板");
    }

    /**
     * 获取成果表详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(filesAchievementService.selectFilesAchievementById(id));
    }

    /**
     * 获取项目对应成果列表
     */
    @GetMapping( "/getAchievementByProject")
    public AjaxResult getAchievementByProject(String projectId)
    {
        FilesAchievement filesAchievement = new FilesAchievement();
        filesAchievement.setProjectId(projectId);
        return AjaxResult.success(filesAchievementService.selectFilesAchievementList(filesAchievement));
    }

    /**
     * 上传成果excel文件
     */
    @PostMapping("/uploadSheet")
    public AjaxResult uploadAchievementSheet(MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return AjaxResult.error("文件内容为空！");
        }
        else {
            ExcelUtil<FilesAchievement> util = new ExcelUtil<FilesAchievement>(FilesAchievement.class);
            List<FilesAchievement> filesAchievementList = util.importExcel(file.getInputStream());
            List<String> IdList = new ArrayList<>();
            for (FilesAchievement filesAchievement :  filesAchievementService.selectFilesAchievementList(new FilesAchievement())) {
                IdList.add(filesAchievement.getId());
            }
            for (FilesAchievement filesAchievement : filesAchievementList)
            {
                if (filesAchievement.getId() == null || !IdList.contains(filesAchievement.getId()))
                    filesAchievement.setId(new SnowFlake().generateId());
                CmcProject cmcProject = new CmcProject();
                CmcProject project = new CmcProject();
                project.setProjectNumber(filesAchievement.getProjectNumber());
                if (cmcProjectService.selectCmcProjectByProjectNumbers(project).size() > 0)
                    cmcProject = cmcProjectService.selectCmcProjectByProjectNumbers(project).get(0);
                if (cmcProject != null)
                    filesAchievement.setProjectId(cmcProject.getProjectId());
                else
                    filesAchievement.setProjectId(null);
                filesAchievement.setResultType(DictUtils.getDictValue("cmc_achi_type", filesAchievement.getResultType()));
                filesAchievement.setScaleGrade(DictUtils.getDictValue("cmc_scale_grade", filesAchievement.getScaleGrade()));
                String storageAddress = filesAchievement.getStorageAddress();
                if (storageAddress != null && !storageAddress.equals("")) {
                    filesAchievement.setStorageId(new SnowFlake().generateId());
                    FilesStorage storage = new FilesStorage();
                    storage.setStorageAddress(storageAddress);
                    if (filesStorageService.selectFilesStorageListE(storage).size() > 0)
                        filesAchievement.setStorageId(filesStorageService.selectFilesStorageListE(storage).get(0).getId());
                    else {
                        FilesStorage filesStorage = new FilesStorage();
                        filesStorage.setId(filesAchievement.getStorageId());
                        filesStorage.setStorageAddress(filesAchievement.getStorageAddress());
                        filesStorage.setAdministrator(getLoginUser().getUsername());
                        filesStorage.setRemark("");
                        filesStorageService.insertFilesStorage(filesStorage);
                    }
                }
                if (IdList.contains(filesAchievement.getId()))
                    filesAchievementService.updateFilesAchievement(filesAchievement);
                else
                    filesAchievementService.insertFilesAchievement(filesAchievement);
            }
            return AjaxResult.success("上传成功");
        }
    }

    /**
     * 新增成果表
     */
    @Log(title = "成果表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(FilesAchievement filesAchievement, MultipartFile uploadKmlFile) throws IOException {
        FilesStorage storage = new FilesStorage();
        storage.setStorageAddress(filesAchievement.getStorageAddress());
        if (filesAchievement.getStorageAddress() != null && !filesAchievement.getStorageAddress().equals("")) {
            filesAchievement.setStorageId(new SnowFlake().generateId());
            if (filesStorageService.selectFilesStorageListE(storage).size() > 0)
                filesAchievement.setStorageId(filesStorageService.selectFilesStorageListE(storage).get(0).getId());
            else {
                FilesStorage filesStorage = new FilesStorage();
                filesStorage.setId(filesAchievement.getStorageId());
                filesStorage.setStorageAddress(filesAchievement.getStorageAddress());
                filesStorage.setAdministrator(getLoginUser().getUsername());
                filesStorage.setRemark("");
                filesStorageService.insertFilesStorage(filesStorage);
            }
        }
        if (filesAchievement.getProjectNumber() != null && !filesAchievement.getProjectNumber().equals("")) {
            CmcProject cmcProject = new CmcProject();
            cmcProject.setProjectNumber(filesAchievement.getProjectNumber());
            if (cmcProjectService.selectCmcProjectList(cmcProject).size() > 0)
                filesAchievement.setProjectId(cmcProjectService.selectCmcProjectList(cmcProject).get(0).getProjectId());
        }
        if (uploadKmlFile(filesAchievement, uploadKmlFile)) return AjaxResult.error("文件内容为空");
        filesAchievement.setId(new SnowFlake().generateId());
        return toAjax(filesAchievementService.insertFilesAchievement(filesAchievement));
    }

    /**
     * 修改成果表
     */
    @Log(title = "成果表", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(FilesAchievement filesAchievement, MultipartFile uploadKmlFile) throws IOException {
        FilesStorage filesStorage = new FilesStorage();
        filesStorage.setStorageAddress(filesAchievement.getStorageAddress());
        if (filesStorageService.selectFilesStorageListE(filesStorage).size() > 0)
            filesAchievement.setStorageId(filesStorageService.selectFilesStorageListE(filesStorage).get(0).getId());
        CmcProject cmcProject = new CmcProject();
        cmcProject = cmcProjectService.selectCmcProjectByProjectId(filesAchievement.getProjectId());
        filesAchievement.setProjectNumber(cmcProject.getProjectNumber());
        if (uploadKmlFile(filesAchievement, uploadKmlFile))
            return AjaxResult.error("文件内容为空");
        return toAjax(filesAchievementService.updateFilesAchievement(filesAchievement));
    }

    private boolean uploadKmlFile(FilesAchievement filesAchievement, MultipartFile uploadKmlFile) throws IOException {
        if (uploadKmlFile != null) {
            if (!uploadKmlFile.isEmpty()) {
                File profilePath = new File(profile + "/upload/uploadKmlFiles/");
                if (!profilePath.exists())//若此目录不存在，则创建之
                    profilePath.mkdirs();
                File transferFile = new File( profilePath + "/" + uploadKmlFile.getOriginalFilename());
                if (!transferFile.exists())
                    uploadKmlFile.transferTo(transferFile);
                filesAchievement.setKmlUrl("/uploadKmlFiles/" + transferFile.getName());
                return false;
            }
            else
            {
                filesAchievement.setKmlUrl(null);
                return true;
            }
        }
        else
        {
            filesAchievement.setKmlUrl(null);
            return false;
        }
    }

    /**
     * 删除成果表
     */
    @Log(title = "成果表", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(filesAchievementService.deleteFilesAchievementByIds(ids));
    }
}
