package com.ruoyi.web.controller.project;

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.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.flowable.service.IInvestigateService;
import com.ruoyi.flowable.service.IInvestmentOpportunityService;
import com.ruoyi.invest.domain.*;
import com.ruoyi.invest.domain.dto.InvestigateDto;
import com.ruoyi.invest.domain.vo.ProjectInvestigateVo;
import com.ruoyi.invest.domain.vo.TProjectPoolVo;
import com.ruoyi.invest.service.*;
import com.ruoyi.system.service.ISysDictDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

/**
 * 尽职背调Controller
 * 
 * @author ruoyi
 * @date 2025-08-08
 */
@Api(tags = "尽职背调")
@RestController
@RequestMapping("/project/investigate")
public class InvestigateController extends BaseController {
    @Autowired
    private IInvestigateService investigateService;
    @Autowired
    private IInvestmentOpportunityService investmentOpportunityService;
    @Autowired
    private ITProjectInvestigateService tProjectInvestigateService;

    @Autowired
    private ITProjectInvestigatePersonService tProjectInvestigatePersonService;
    @Autowired
    private ISysDictDataService dictDataService;

    //所有尽职背调流程列表
    @ApiOperation("所有尽职背调流程列表")
    @GetMapping("/listAll")
    public TableDataInfo listAll(TProjectInvestigate tProjectInvestigate)
    {
        startPage();
        List<ProjectInvestigateVo> list=investigateService.selectAllInvestigateList(tProjectInvestigate);
        return getDataTable(list);
    }
    /**
     * 导出所有项目背调流程列表
     */
    @ApiOperation("导出所有项目背调流程列表")
    @Log(title = "所有项目背调流程列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TProjectInvestigate tProjectInvestigate)
    {
        List<ProjectInvestigateVo> list=investigateService.selectAllInvestigateList(tProjectInvestigate)
                .stream().map(n -> {
                    if(StringUtils.isNotEmpty(n.getIndustry()))n.setIndustry(dictDataService.selectDictLabel("CUSTOMER_TRADE",n.getIndustry()));
                    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()));
                    if(StringUtils.isNotEmpty(n.getProjectStatus())){
                        if("0".equals(n.getProjectStatus())){
                            n.setProjectStatus("正常");
                        }else if("1".equals(n.getProjectStatus())){
                            n.setProjectStatus("终止");
                        }else if("2".equals(n.getProjectStatus())){
                            n.setProjectStatus("观望");
                        }
                    }
                    return n;
                })
                .collect(Collectors.toList());
        ExcelUtil<ProjectInvestigateVo> util = new ExcelUtil<ProjectInvestigateVo>(ProjectInvestigateVo.class);
        util.exportExcel(response, list, "所有项目背调流程数据");
    }
    /**
     * 查询可申请尽职背调列表
     */
    @ApiOperation("查询可申请尽职背调列表")
    @GetMapping("/applicableList")
    public TableDataInfo applicableList(TProjectPool tProjectPool)
    {
        startPage();
        tProjectPool.setProjectStage("4");
        tProjectPool.setDelFlag("0");
        tProjectPool.setInvestigateFlag("0");//未发起背调的
        tProjectPool.setStatus(3);//项目机会流程状态为审批通过
        tProjectPool.setProjectStatus(tProjectPool.getProjectStatus());
        tProjectPool.setTerminationFlag("0");//未发起终止的
        List<TProjectPool> list = investmentOpportunityService.selectApplicableProjectList(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("我的待办任务列表")
    @GetMapping("/getMyTaskList")
    public TableDataInfo getMyTaskList(TProjectInvestigate tProjectInvestigate)
    {
        startPage();
        //tProjectPool.setProjectStage("1");
        List<ProjectInvestigateVo> list=investigateService.getMyTaskList(getUserId().toString(),tProjectInvestigate);
        return getDataTable(list);
    }
    //我的已办任务
    @ApiOperation("我的已办任务列表")
    @GetMapping("/getMyDoneTaskList")
    public TableDataInfo getMyDoneTaskList(TProjectInvestigate tProjectInvestigate)
    {
        startPage();
        //tProjectPool.setProjectStage("1");
        List<ProjectInvestigateVo> list=investigateService.getMyDoneTaskList(getUserId().toString(),tProjectInvestigate);
        return getDataTable(list);
    }
    //我的待办任务
    @ApiOperation("我的单据列表")
    @GetMapping("/getMyList")
    public TableDataInfo getMyList(TProjectInvestigate tProjectInvestigate)
    {
        startPage();
        //tProjectPool.setProjectStage("1");
        List<ProjectInvestigateVo> list=investigateService.getMyList(getUserId().toString(),tProjectInvestigate);
        return getDataTable(list);
    }
    /**
     * 导出我的已办任务列表
     */
    @ApiOperation("导出我的待办任务列表")
    @Log(title = "我的待办任务列表", businessType = BusinessType.EXPORT)
    @PostMapping("/exportMyTask")
    public void exportMyTask(HttpServletResponse response, TProjectPool tProjectPool)
    {
        List<TProjectPoolVo> list=investmentOpportunityService.getMyTaskList(getUserId().toString(),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()));
                    if(StringUtils.isNotEmpty(n.getProjectStatus())){
                        if("0".equals(n.getProjectStatus())){
                            n.setProjectStatus("正常");
                        }else if("1".equals(n.getProjectStatus())){
                            n.setProjectStatus("终止");
                        }else if("2".equals(n.getProjectStatus())){
                            n.setProjectStatus("观望");
                        }
                    }
                    return n;
                })
                .collect(Collectors.toList());
        ExcelUtil<TProjectPoolVo> util = new ExcelUtil<TProjectPoolVo>(TProjectPoolVo.class);
        util.exportExcel(response, list, "我的待办任务数据");
    }

    /**
     * 导出我的已办任务列表
     */
    @ApiOperation("导出我的已办任务列表")
    @Log(title = "我的已办任务列表", businessType = BusinessType.EXPORT)
    @PostMapping("/exportMyDoneTask")
    public void exportMyDoneTask(HttpServletResponse response, TProjectPool tProjectPool)
    {
        List<TProjectPoolVo> list=investmentOpportunityService.getMyDoneTaskList(getUserId().toString(),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()));
                    if(StringUtils.isNotEmpty(n.getProjectStatus())){
                        if("0".equals(n.getProjectStatus())){
                            n.setProjectStatus("正常");
                        }else if("1".equals(n.getProjectStatus())){
                            n.setProjectStatus("终止");
                        }else if("2".equals(n.getProjectStatus())){
                            n.setProjectStatus("观望");
                        }
                    }
                    return n;
                })
                .collect(Collectors.toList());
        ExcelUtil<TProjectPoolVo> util = new ExcelUtil<TProjectPoolVo>(TProjectPoolVo.class);
        util.exportExcel(response, list, "我的已办任务数据");
    }
    /**
     * 导出我的单据列表
     */
    @ApiOperation("导出我的单据列表")
    @Log(title = "我的单据列表", businessType = BusinessType.EXPORT)
    @PostMapping("/exportMy")
    public void exportMy(HttpServletResponse response, TProjectPool tProjectPool)
    {
        List<TProjectPoolVo> list=investmentOpportunityService.getMyList(getUserId().toString(),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()));
                    if(StringUtils.isNotEmpty(n.getProjectStatus())){
                        if("0".equals(n.getProjectStatus())){
                            n.setProjectStatus("正常");
                        }else if("1".equals(n.getProjectStatus())){
                            n.setProjectStatus("终止");
                        }else if("2".equals(n.getProjectStatus())){
                            n.setProjectStatus("观望");
                        }
                    }
                    return n;
                })
                .collect(Collectors.toList());
        ExcelUtil<TProjectPoolVo> util = new ExcelUtil<TProjectPoolVo>(TProjectPoolVo.class);
        util.exportExcel(response, list, "我的单据数据");
    }
    /**
     * 获取项目池详细信息
     */
    @ApiOperation("获取项目池详细信息")
    @GetMapping(value = "/{pInstId}")
    public AjaxResult getInfo(@PathVariable("pInstId") String pInstId)
    {
        return success(investigateService.selectTProjectInvestigateByProcInstId(pInstId));
    }
    //发起流程
    @ApiOperation(value = "投资机会申请发起流程")
    @Log(title = "发起流程", businessType = BusinessType.INSERT)
    @PostMapping("/start")
    public AjaxResult start(@RequestBody TProjectInvestigate tProjectInvestigate) {

       //return InvestigateService.set
        return investigateService.start(tProjectInvestigate);
    }
    @ApiOperation(value = "审批任务")
    @PutMapping(value = "/complete")
    public AjaxResult complete(@RequestBody InvestigateDto dto, HttpServletRequest request) throws Exception {
        // 从 DTO 中拆分参数
        TProjectInvestigate tProjectInvestigate= dto.getProjectInvestigate();
        TProjectInvestigatePerson tProjectInvestigatePerson = dto.getProjectInvestigatePerson();
        FlowBaseInfo flowBaseInfo= dto.getFlowBaseInfo();
        return investigateService.complete(tProjectInvestigate,tProjectInvestigatePerson,flowBaseInfo,request);
    }
    /**
     * 获取通过流程id会议记录详细信息 （会议投决）
     */
    @ApiOperation("获取会议记录详细信息")
    @GetMapping(value = "/getMeetingInfo/{pInstId}")
    public AjaxResult getMeetingInfo(@PathVariable("pInstId") String pInstId) {

        return success(investigateService.selectTProjectMeetingByProcInstId(pInstId));
    }
    /**
     * 根据流程Id查询汇总分数和平均分数 （总裁室）
     */
    @ApiOperation("根据会议ID查询汇总分数和平均分数")
    @GetMapping(value = "/getSumScore/{pInstId}")
    public AjaxResult getSumScore(@PathVariable("pInstId") String pInstId)
    {
        if (StringUtils.isEmpty(pInstId))
        {
            return error("查询打分数据'" + getNickName() + "'失败，请选择会议！");
        }
        return success(investigateService.selectSumScore(pInstId));
    }
}
