package com.ruoyi.web.controller.invest;

import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.enums.FileType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.invest.domain.TProjectCirculation;
import com.ruoyi.invest.domain.TProjectCompany;
import com.ruoyi.invest.domain.TProjectContacts;
import com.ruoyi.invest.domain.TProjectPool;
import com.ruoyi.invest.service.*;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.tool.domain.TUnifyFile;
import com.ruoyi.tool.service.ITUnifyFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 项目池Controller
 * 
 * @author ruoyi
 * @date 2024-02-21
 */
@Api(tags = "项目池")
@RestController
@RequestMapping("/invest/pool")
public class TProjectPoolController extends BaseController
{
    @Autowired
    private ITProjectPoolService tProjectPoolService;

    @Autowired
    private ITProjectCompanyService tProjectCompanyService;

    @Autowired
    private ITProjectContactsService tProjectContactsService;

    @Autowired
    private ITProjectCirculationService tProjectCirculationService;

    @Autowired
    private ITUnifyFileService tUnifyFileService;

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private ITProjectInvestigateService tProjectInvestigateService;

    @Autowired
    private ITProjectInvestigatePersonService tProjectInvestigatePersonService;

    @Autowired
    private ITProjectMeetingService tProjectMeetingService;

    @Autowired
    private ITProjectScoringService tProjectScoringService;


    /**
     * 查询项目池列表
     */
    @ApiOperation("查询项目池列表")
    @PreAuthorize("@ss.hasPermi('invest:pool:list')")
    @GetMapping("/list")
    public TableDataInfo list(TProjectPool tProjectPool)
    {
        startPage();
        List<TProjectPool> list = tProjectPoolService.selectTProjectPoolList(tProjectPool);
        return getDataTable(list);
    }

    /**
     * 查询项目池列表
     */
    @ApiOperation("查询项目阶段列表")
    @PreAuthorize("@ss.hasPermi('invest:pool:list')")
    @GetMapping("/listStage")
    public TableDataInfo listStage(TProjectPool tProjectPool)
    {
        startPage();
        List<TProjectPool> list = tProjectPoolService.selectTProjectPoolListStage(tProjectPool);
        return getDataTable(list);
    }

    /**
     * 查询评估考察列表
     */
    @ApiOperation("查询评估考察列表")
    @PreAuthorize("@ss.hasPermi('invest:pool:list')")
    @GetMapping("/listReview")
    public TableDataInfo listReview(TProjectPool tProjectPool)
    {
        startPage();
        tProjectPool.setDelFlag("0");
        tProjectPool.setProjectStage("2");
        tProjectPool.setCreateBy(getUserId().toString());
        List<TProjectPool> list = tProjectPoolService.selectTProjectPoolReviewList(tProjectPool);
        return getDataTable(list);
    }

    /**
     * 查询项目立项列表
     */
    @ApiOperation("查询项目立项列表")
    @PreAuthorize("@ss.hasPermi('invest:pool:list')")
    @GetMapping("/listApproval")
    public TableDataInfo listApproval(TProjectPool tProjectPool)
    {
        startPage();
        tProjectPool.setProjectStage("3");
        tProjectPool.setDelFlag("0");
        List<TProjectPool> list = tProjectPoolService.selectTProjectPoolList(tProjectPool)
                            .stream().map(n -> {
                                n.settProjectMeeting(tProjectMeetingService.listProjectPoolIdNew(n.getId(),"LX"));
                                if(null != n.gettProjectMeeting()){
                                    n.settProjectScoring(tProjectScoringService.getCanScoringMeetingId(n.gettProjectMeeting().getId(),getUserId()));
                                }
                                return n;
                            }).collect(Collectors.toList());
        return getDataTable(list);
    }

    /**
     * 查询尽职背调列表
     */
    @ApiOperation("查询尽职背调列表")
    @PreAuthorize("@ss.hasPermi('invest:pool:list')")
    @GetMapping("/listInvestigate")
    public TableDataInfo listInvestigate(TProjectPool tProjectPool)
    {
        startPage();
        tProjectPool.setProjectStage("4");
        tProjectPool.setDelFlag("0");
        List<TProjectPool> list = tProjectPoolService.selectTProjectPoolList(tProjectPool)
                .stream().map(n -> {
                    n.settProjectInvestigate(tProjectInvestigateService.listProjectPoolIdNew(n.getId()));
                    if(null != n.gettProjectInvestigate()){
                        n.settProjectInvestigatePerson(tProjectInvestigatePersonService.selectByProjectInvestigateId(n.gettProjectInvestigate().getId(),getUserId()));
                    }
                    return n;
                }).collect(Collectors.toList());
        return getDataTable(list);
    }

    /**
     * 查询项目投决列表
     */
    @ApiOperation("查询项目投决列表")
    @PreAuthorize("@ss.hasPermi('invest:pool:list')")
    @GetMapping("/listDecision")
    public TableDataInfo listDecision(TProjectPool tProjectPool)
    {
        startPage();
        tProjectPool.setProjectStage("5");
        tProjectPool.setDelFlag("0");
        List<TProjectPool> list = tProjectPoolService.selectTProjectPoolList(tProjectPool).stream().map(n -> {
                                n.settProjectMeeting(tProjectMeetingService.listProjectPoolIdNew(n.getId(),"TJ"));
                                if(null != n.gettProjectMeeting()){
                                    n.settProjectScoring(tProjectScoringService.getCanScoringMeetingId(n.gettProjectMeeting().getId(),getUserId()));
                                }
                                return n;
                            }).collect(Collectors.toList());
        return getDataTable(list);
    }
    /**
     * 查询项目终止列表
     */
    @ApiOperation("查询项目终止列表")
    @PreAuthorize("@ss.hasPermi('invest:pool:list')")
    @GetMapping("/listTermination")
    public TableDataInfo listTermination(TProjectPool tProjectPool)
    {
        startPage();
        tProjectPool.setProjectStage("8");
        tProjectPool.setDelFlag("0");
        List<TProjectPool> list = tProjectPoolService.selectTProjectPoolList(tProjectPool);
        return getDataTable(list);
    }

    /**
     * 导出项目池列表
     */
    @ApiOperation("导出项目池列表")
    @PreAuthorize("@ss.hasPermi('invest:pool:export')")
    @Log(title = "项目池", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TProjectPool tProjectPool)
    {
        List<TProjectPool> list = tProjectPoolService.selectTProjectPoolList(tProjectPool)
                .stream().map(n -> {
                    if(null != n.gettProjectChannel()){
                        n.setChannel(n.gettProjectChannel().getChannelName());
                    }
                    if(StringUtils.isNotEmpty(n.getIndustry()))n.setIndustry(dictDataService.selectDictLabel("CUSTOMER_TRADE",n.getIndustry()));
                    if(null != n.gettProjectCompany()){
                        n.setCompany(n.gettProjectCompany().getCompanyName());
                    }
                    if(null != n.gettProjectContacts()){
                        n.setProjectContacts(n.gettProjectContacts().getName());
                    }
                    if(StringUtils.isNotEmpty(n.getInvestType()))n.setInvestType(dictDataService.selectDictLabel("INVEST_TYPE",n.getInvestType()));
                    if(StringUtils.isNotEmpty(n.getInvestPloy()))n.setInvestPloy(dictDataService.selectDictLabel("INVEST_PLOY",n.getInvestPloy()));
                    if(StringUtils.isNotEmpty(n.getInvestWorth()))n.setInvestWorth(dictDataService.selectDictLabel("INVEST_WORTH",n.getInvestWorth()));
                    if(StringUtils.isNotEmpty(n.getProjectStage()))n.setProjectStage(dictDataService.selectDictLabel("PROJECT_STAGE",n.getProjectStage()));
                    if(StringUtils.isNotEmpty(n.getProjectState()))n.setProjectState(dictDataService.selectDictLabel("PROJECT_STATE",n.getProjectState()));
                    return n;
                })
                .collect(Collectors.toList());
        ExcelUtil<TProjectPool> util = new ExcelUtil<TProjectPool>(TProjectPool.class);
        util.exportExcel(response, list, "项目池数据");
    }

    /**
     * 获取项目池详细信息
     */
    @ApiOperation("获取项目池详细信息")
    @PreAuthorize("@ss.hasPermi('invest:pool:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(tProjectPoolService.selectTProjectPoolById(id));
    }

    /**
     * 新增项目池
     */
    @ApiOperation("新增项目池")
    @PreAuthorize("@ss.hasPermi('invest:pool:add')")
    @Log(title = "项目池", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TProjectPool tProjectPool)
    {
        // todo 设置主键及创建人
        tProjectPool.setCreateBy(getNickName());
        tProjectPool.setId(IdUtils.fastSimpleUUID());
        int number = tProjectPoolService.selectTProjectPoolCode(DateUtils.lastTwoDigits()+"-");
        tProjectPool.setProjectCode(tProjectPool.getProjectGroup() + "-" + DateUtils.lastTwoDigits() + "-" + String.format("%03d",number+1));
        TProjectCompany tProjectCompany = tProjectPool.gettProjectCompany();
        tProjectCompany.setCreateBy(getNickName());
        tProjectCompany.setId(IdUtils.fastSimpleUUID());
        TProjectContacts tProjectContacts = tProjectPool.gettProjectContacts();
        tProjectContacts.setCreateBy(getNickName());
        tProjectContacts.setId(IdUtils.fastSimpleUUID());
        // todo 设置项目联系人
        tProjectPool.setProjectContacts(tProjectContacts.getId());
        // todo 设置公司信息关联关系
        tProjectCompany.setProjectPoolId(tProjectPool.getId());

        // todo 保存公司附件信息
        tUnifyFileService.insertTUnifyFileList(tProjectPool.getListFile(),
                tProjectPool.getId(),
                tProjectCompany.getId(),
                String.valueOf(FileType.COMPANY.ordinal()),
                getNickName());

        // todo 保存BP附件信息
        tUnifyFileService.insertTUnifyFileList(tProjectPool.getBpFile(),
                tProjectPool.getId(),
                tProjectPool.getId(),
                String.valueOf(FileType.BP.ordinal()),
                getNickName());

        // todo 保存其他附件信息
        tUnifyFileService.insertTUnifyFileList(tProjectPool.getOtherFile(),
                tProjectPool.getId(),
                tProjectPool.getId(),
                String.valueOf(FileType.OTHER.ordinal()),
                getNickName());

        tProjectCompanyService.insertTProjectCompany(tProjectCompany);
        tProjectContactsService.insertTProjectContacts(tProjectContacts);
        // todo 增加项目创建记录
        tProjectCirculationService.insertTProjectCirculation(tProjectPool.getId(),"项目报备",getNickName());

        return toAjax(tProjectPoolService.insertTProjectPool(tProjectPool));
    }

    /**
     * 修改项目池
     */
    @ApiOperation("修改项目池")
    @PreAuthorize("@ss.hasPermi('invest:pool:edit')")
    @Log(title = "项目池", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TProjectPool tProjectPool)
    {
        tProjectPool.setUpdateBy(getNickName());
        TProjectCompany tProjectCompany = tProjectPool.gettProjectCompany();
        tProjectCompany.setUpdateBy(getNickName());
        TProjectContacts tProjectContacts = tProjectPool.gettProjectContacts();
        tProjectContacts.setUpdateBy(getNickName());
        tProjectContacts.setId(tProjectPool.getProjectContacts());
        // 上传并返回新文件名称
        // todo 保存公司附件信息
        tUnifyFileService.insertTUnifyFileList(tProjectPool.getListFile(),
                tProjectPool.getId(),
                tProjectCompany.getCompanyId(),
                String.valueOf(FileType.COMPANY.ordinal()),
                getNickName());

        // todo 保存BP附件信息
        tUnifyFileService.insertTUnifyFileList(tProjectPool.getBpFile(),
                tProjectPool.getId(),
                tProjectPool.getId(),
                String.valueOf(FileType.BP.ordinal()),
                getNickName());

        // todo 保存其他附件信息
        tUnifyFileService.insertTUnifyFileList(tProjectPool.getOtherFile(),
                tProjectPool.getId(),
                tProjectPool.getId(),
                String.valueOf(FileType.OTHER.ordinal()),
                getNickName());

        tProjectCompanyService.updateTProjectCompany(tProjectCompany);
        tProjectContactsService.updateTProjectContacts(tProjectContacts);
        return toAjax(tProjectPoolService.updateTProjectPool(tProjectPool));
    }

    /**
     * 删除项目池
     */
    @ApiOperation("删除项目池")
    @PreAuthorize("@ss.hasPermi('invest:pool:remove')")
    @Log(title = "项目池", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(tProjectPoolService.updateTProjectPoolByIds(ids));
    }

    /**
     * 修改项目池状态
     */
    @ApiOperation("修改项目池状态")
    @PreAuthorize("@ss.hasPermi('invest:pool:edit')")
    @Log(title = "项目池", businessType = BusinessType.UPDATE)
    @PutMapping("/editStage")
    public AjaxResult editStage(@RequestBody TProjectPool tProjectPool)
    {
        tProjectPool.setUpdateBy(getNickName());
        // todo 增加项目创建记录
        TProjectCirculation tProjectCirculation = new TProjectCirculation();
        tProjectCirculation.setProjectPoolId(tProjectPool.getId());
        tProjectCirculation.setStageName(tProjectPool.getStageName() + "-" + tProjectPool.getStateName());
        tProjectCirculation.setCreateBy(getNickName());
        tProjectCirculationService.insertTProjectCirculation(tProjectCirculation);

        return toAjax(tProjectPoolService.updateTProjectPool(tProjectPool));
    }

    /**
     * 查询评估考察列表数量
     */
    @ApiOperation("查询评估考察列表数量")
    @PreAuthorize("@ss.hasPermi('invest:pool:list')")
    @GetMapping(value = "/getReviewNumber")
    public AjaxResult getReviewNumber()
    {
        TProjectPool tProjectPool = new TProjectPool();
        tProjectPool.setProjectStage("2");
        tProjectPool.setCreateBy(getUserId().toString());
        tProjectPool.setDelFlag("0");
        Long number = tProjectPoolService.selectTProjectPoolReviewList(tProjectPool).stream().filter(n -> null == n.gettProjectReview()).count();

        return success(number);
    }

    /**
     * 查询项目立项列表数量
     */
    @ApiOperation("查询项目立项列表数量")
    @PreAuthorize("@ss.hasPermi('invest:pool:list')")
    @GetMapping(value = "/getApprovalNumber")
    public AjaxResult getApprovalNumber()
    {
        TProjectPool tProjectPool = new TProjectPool();
        tProjectPool.setProjectStage("3");
        tProjectPool.setDelFlag("0");
        List<TProjectPool> list = tProjectPoolService.selectTProjectPoolList(tProjectPool).stream().map(n -> {
                    n.settProjectMeeting(tProjectMeetingService.listProjectPoolIdNew(n.getId(),"LX"));
                    if(null != n.gettProjectMeeting()){
                        n.settProjectScoring(tProjectScoringService.getCanScoringMeetingId(n.gettProjectMeeting().getId(),getUserId()));
                    }
                    return n;
                }).collect(Collectors.toList());
        //逻辑验证数量
        Long number = list.stream().filter(n ->
                getNickName().equals(n.getInvestHead()) ||
                (
                    null != n.gettProjectMeeting() &&
                    n.gettProjectMeeting().getParticipants().contains(getNickName()) &&
                    null == n.gettProjectScoring()
                )).count();
        return success(number);
    }

    /**
     * 查询项目立项列表数量
     */
    @ApiOperation("查询项目投决列表数量")
    @PreAuthorize("@ss.hasPermi('invest:pool:list')")
    @GetMapping(value = "/getDecisionNumber")
    public AjaxResult getDecisionNumber()
    {
        TProjectPool tProjectPool = new TProjectPool();
        tProjectPool.setProjectStage("5");
        tProjectPool.setDelFlag("0");
        List<TProjectPool> list = tProjectPoolService.selectTProjectPoolList(tProjectPool).stream().map(n -> {
            n.settProjectMeeting(tProjectMeetingService.listProjectPoolIdNew(n.getId(),"TJ"));
            if(null != n.gettProjectMeeting()){
                n.settProjectScoring(tProjectScoringService.getCanScoringMeetingId(n.gettProjectMeeting().getId(),getUserId()));
            }
            return n;
        }).collect(Collectors.toList());
        // 逻辑验证数量
        Long number = list.stream().filter(n ->
                getNickName().equals(n.getInvestHead()) ||
                        (null != n.gettProjectMeeting() &&
                        n.gettProjectMeeting().getParticipants().contains(getNickName()) &&
                        null == n.gettProjectScoring()
                        )).count();
        return success(number);
    }

    /**
     * 查询项目立项列表数量
     */
    @ApiOperation("查询尽职背调列表数量")
    @PreAuthorize("@ss.hasPermi('invest:pool:list')")
    @GetMapping(value = "/getInvestigateNumber")
    public AjaxResult getInvestigateNumber()
    {
        TProjectPool tProjectPool = new TProjectPool();
        tProjectPool.setProjectStage("4");
        tProjectPool.setDelFlag("0");
        List<TProjectPool> list = tProjectPoolService.selectTProjectPoolList(tProjectPool)
                .stream().map(n -> {
                    n.settProjectInvestigate(tProjectInvestigateService.listProjectPoolIdNew(n.getId()));
                    if(null != n.gettProjectInvestigate()){
                        n.settProjectInvestigatePerson(tProjectInvestigatePersonService.selectByProjectInvestigateId(n.gettProjectInvestigate().getId(),getUserId()));
                    }
                    return n;
                }).collect(Collectors.toList());
        // 逻辑验证数量
        Long number = list.stream().filter(n ->
                getNickName().equals(n.getInvestHead()) ||
                        (null != n.gettProjectInvestigate() &&
                        n.gettProjectInvestigate().getInvestigatePerson().contains(getNickName()) &&
                        null == n.gettProjectInvestigatePerson()
                        )).count();
        return success(number);
    }

}
