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.SnowFlake;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.oa.domain.CmcProject;
import com.ruoyi.oa.service.ICmcProjectService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
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-05
 */
@RestController
@RequestMapping("/file/project")
public class FilesProjectController extends BaseController {
    @Autowired
    private ICmcProjectService cmcProjectService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysUserService userService;

    @Value("${cmc.profile}")
    private String profile;

    /**
     * 查询项目管理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(CmcProject cmcProject) {
        startPage();
        List<CmcProject> list = cmcProjectService.selectCmcProjectList(cmcProject);
        for (CmcProject project : list) {
            project.setUndertakingDeptName(deptIdToName(project));
        }
        return getDataTable(list);
    }

    /**
     * 导出项目管理列表
     */
    @Log(title = "项目管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CmcProject cmcProject) {
        List<CmcProject> list = cmcProjectService.selectCmcProjectList(cmcProject);
        for (CmcProject project : list) {
            project.setUndertakingDeptName(deptIdToName(project));
            project.setQualityInspectorName(inspectorIdToName(project));
        }
        ExcelUtil<CmcProject> util = new ExcelUtil<CmcProject>(CmcProject.class);
        util.exportExcel(response, list, "项目管理数据");
    }

    /**
     * 导出选中项目管理列表
     */
    @Log(title = "成果表", businessType = BusinessType.EXPORT)
    @PostMapping("/exportBatch/{ids}")
    public void exportBatch(HttpServletResponse response, CmcProject cmcProject, @PathVariable("ids") String[] ids)
    {
        List<CmcProject> list = new ArrayList<>();
        for (String projectId : ids)
            list.add(cmcProjectService.selectCmcProjectByProjectId(projectId));
        ExcelUtil<CmcProject> util = new ExcelUtil<CmcProject>(CmcProject.class);
        util.exportExcel(response, list, "成果表数据");
    }

    /**
     * 下载项目表模版
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<CmcProject> util = new ExcelUtil<CmcProject>(CmcProject.class);
        util.importTemplateExcel(response, "项目表模板");
    }

    /**
     * 获取项目管理详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(cmcProjectService.selectCmcProjectByProjectId(id));
    }

    /**
     * 上传项目excel文件
     */
    @PostMapping("/uploadSheet")
    public AjaxResult uploadProjectSheet(MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return AjaxResult.error("文件内容为空！");
        } else {
            ExcelUtil<CmcProject> util = new ExcelUtil<CmcProject>(CmcProject.class);
            List<CmcProject> cmcProjectList = util.importExcel(file.getInputStream());
            List<String> IdList = new ArrayList<>();
            for (CmcProject fileProject :  cmcProjectService.selectCmcProjectList(new CmcProject())) {
                IdList.add(fileProject.getProjectId());
            }
            for (CmcProject fileProject : cmcProjectList)
            {
                if (fileProject.getProjectId() == null || !IdList.contains(fileProject.getProjectId()))
                    fileProject.setProjectId(new SnowFlake().generateId());
                if (IdList.contains(fileProject.getProjectId()))
                    cmcProjectService.updateCmcProject(fileProject);
                else
                    cmcProjectService.insertCmcProject(fileProject);
            }
            return AjaxResult.success("上传成功");
        }
    }

    /**
     * 新增项目管理
     */
    @Log(title = "项目管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(CmcProject cmcProject, @RequestParam(value = "kmlfile",required = false) MultipartFile uploadProjectKmlFile, @RequestParam(value = "cpfile",required = false) MultipartFile uploadCpKmlFile) throws IOException {
        cmcProject.setProjectId(new SnowFlake().generateId());
        if (uploadProjectKmlFile(cmcProject, uploadProjectKmlFile) )
            return AjaxResult.error("项目范围kml文件内容为空");
        if (uploadCpKmlFile(cmcProject, uploadCpKmlFile))
            return AjaxResult.error("项目控制点kml文件内容为空");
        return toAjax(cmcProjectService.insertCmcProject(cmcProject));
    }

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

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

    /**
     * 修改项目管理
     */
    @Log(title = "项目管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(CmcProject cmcProject, @RequestParam(value = "kmlfile",required = false) MultipartFile uploadProjectKmlFile, @RequestParam(value = "cpfile",required = false) MultipartFile uploadCpKmlFile) throws IOException {
        String msg = "";
        if (uploadProjectKmlFile(cmcProject, uploadProjectKmlFile) )
            msg = "项目范围kml文件内容为空";
        if (uploadCpKmlFile(cmcProject, uploadCpKmlFile))
            msg = "项目控制点kml文件内容为空";
        return AjaxResult.success(msg, cmcProjectService.updateCmcProject(cmcProject));
    }

    /**
     * 删除项目管理
     */
    @Log(title = "项目管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(cmcProjectService.deleteCmcProjectByProjectIds(ids));
    }

    /**
     * 根据项目编号查询项目信息
     */
    @GetMapping("/query")
    public TableDataInfo getInfoByProjectNumber(CmcProject cmcProject) {
        startPage();
        return getDataTable(cmcProjectService.selectCmcProjectByProjectNumbers(cmcProject));
    }

    public String deptIdToName(CmcProject cmcProject) {
        String underTakingDept = cmcProject.getUndertakingDept();
        String undertakingDeptName = cmcProject.getUndertakingDeptName();
        StringBuilder underTakingDeptNames = new StringBuilder();
        if (underTakingDept != null && !underTakingDept.equals("") && (undertakingDeptName == null || undertakingDeptName.equals(""))) {
            for (String dept : underTakingDept.split(","))
                underTakingDeptNames.append(deptService.selectDeptById(Long.parseLong(dept)).getDeptName()).append(",");
            cmcProject.setUndertakingDeptName(underTakingDeptNames.substring(0, underTakingDeptNames.length() - 1));
        }
        return cmcProject.getUndertakingDeptName();
    }

    public String inspectorIdToName(CmcProject cmcProject) {
        String qualityInspector = cmcProject.getQualityInspector();
        String qualityInspectorName = cmcProject.getQualityInspectorName();
        StringBuilder qualityInspectorNames = new StringBuilder();
        if (qualityInspector != null && !qualityInspector.equals("") && (qualityInspectorName == null || qualityInspectorName.equals(""))) {
            for (String inspector : qualityInspector.split(","))
                qualityInspectorNames.append(userService.selectUserById(Long.parseLong(inspector)).getNickName()).append(",");
            cmcProject.setQualityInspectorName(qualityInspectorNames.substring(0, qualityInspectorNames.length() - 1));
        }
        return cmcProject.getQualityInspectorName();
    }

}