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.IApprovalService;
import com.ruoyi.flowable.service.IInvestmentOpportunityService;
import com.ruoyi.invest.domain.*;
import com.ruoyi.invest.domain.dto.ApprovalDto;
import com.ruoyi.invest.domain.vo.ProjectApprovalVo;
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/approval")
public class ApprovalController extends BaseController {
    @Autowired
    private IApprovalService approvalService;
    @Autowired
    private IInvestmentOpportunityService investmentOpportunityService;
    @Autowired
    private ITProjectMeetingService tProjectMeetingService;

    @Autowired
    private ITProjectScoringService tProjectScoringService;
    @Autowired
    private ISysDictDataService dictDataService;
    //项目立项阶段列表

    //所有项目立项流程列表
    @ApiOperation("所有项目立项流程列表")
    @GetMapping("/listAll")
    public TableDataInfo listAll(TProjectApproval tProjectApproval)
    {
        startPage();
        List<ProjectApprovalVo> list=approvalService.selectAllApprovalList(tProjectApproval);
        return getDataTable(list);
    }
    /**
     * 导出所有项目立项流程列表
     */
    @ApiOperation("导出所有项目立项流程列表")
    @Log(title = "所有项目立项流程列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TProjectApproval tProjectApproval)
    {
        List<ProjectApprovalVo> list=approvalService.selectAllApprovalList(tProjectApproval)
                .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<ProjectApprovalVo> util = new ExcelUtil<ProjectApprovalVo>(ProjectApprovalVo.class);
        util.exportExcel(response, list, "所有项目立项流程数据");
    }
    /**
     * 查询可申请的项目立项列表
     */
    @ApiOperation("查询可申请项目立项列表")
    @GetMapping("/applicableList")
    public TableDataInfo applicableList( TProjectPool tProjectPool)
    {
        startPage();
        tProjectPool.setProjectStage("3");
        tProjectPool.setDelFlag("0");
        tProjectPool.setApprovalFlag("0");//未发起立项的
        tProjectPool.setStatus(3);//项目机会流程状态为审批通过
        tProjectPool.setProjectStatus(tProjectPool.getProjectStatus());
        tProjectPool.setTerminationFlag("0");//未发起终止的
        List<TProjectPool> list = investmentOpportunityService.selectApplicableProjectList(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("我的待办任务列表")
    @GetMapping("/getMyTaskList")
    public TableDataInfo getMyTaskList(TProjectApproval tProjectApproval)
    {
        startPage();
        //tProjectPool.setProjectStage("1");
        List<ProjectApprovalVo> list=approvalService.getMyTaskList(getUserId().toString(),tProjectApproval);
        return getDataTable(list);
    }
    //我的已办任务
    @ApiOperation("我的已办任务列表")
    @GetMapping("/getMyDoneTaskList")
    public TableDataInfo getMyDoneTaskList(TProjectApproval tProjectApproval)
    {
        startPage();
        //tProjectPool.setProjectStage("1");
        List<ProjectApprovalVo> list=approvalService.getMyDoneTaskList(getUserId().toString(),tProjectApproval);
        return getDataTable(list);
    }
    //我的待办任务
    @ApiOperation("我的单据列表")
    @GetMapping("/getMyList")
    public TableDataInfo getMyList(TProjectApproval tProjectApproval)
    {
        startPage();
        //tProjectPool.setProjectStage("1");
        List<ProjectApprovalVo> list=approvalService.getMyList(getUserId().toString(),tProjectApproval);
        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(approvalService.selectTProjectApprovalByProcInstId(pInstId));
    }
    //发起流程
    @ApiOperation(value = "投资机会申请发起流程")
    @Log(title = "发起流程", businessType = BusinessType.INSERT)
    @PostMapping("/start")
    public AjaxResult start(@RequestBody TProjectApproval tProjectApproval) {

        return approvalService.start(tProjectApproval);
    }
    @ApiOperation(value = "审批任务")
    @PutMapping(value = "/complete")
    public AjaxResult complete(@RequestBody ApprovalDto dto, HttpServletRequest request) throws Exception  {
        // 从 DTO 中拆分参数
        TProjectApproval tProjectApproval = dto.getProjectApproval();
        TProjectMeeting tProjectMeeting = dto.getProjectMeeting();
        TProjectScoring tProjectScoring =dto.getProjectScoring();
        FlowBaseInfo flowBaseInfo= dto.getFlowBaseInfo();
        return approvalService.complete(tProjectApproval,tProjectMeeting,tProjectScoring,flowBaseInfo,request);
    }
    /**
     * 获取通过流程id会议记录详细信息 （会议）
     */
    @ApiOperation("获取会议记录详细信息")
    @GetMapping(value = "/getMeetingInfo/{pInstId}")
    public AjaxResult getMeetingInfo(@PathVariable("pInstId") String pInstId) {

        return success(approvalService.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(approvalService.selectSumScore(pInstId));
    }
}
