package com.jeeplus.finance.projectRecords.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.common.excel.ExcelOptions;
import com.jeeplus.common.excel.annotation.ExportMode;
import com.jeeplus.common.utils.ResponseUtil;
import com.jeeplus.finance.invoice.util.EasyPoiUtil;
import com.jeeplus.finance.projectRecords.domain.CwProjectPlan;
import com.jeeplus.finance.projectRecords.domain.CwProjectPlanDetails;
import com.jeeplus.finance.projectRecords.domain.CwProjectRecords;
import com.jeeplus.finance.projectRecords.domain.PartialCustomerInfo;
import com.jeeplus.finance.projectRecords.service.CwProjectRecordsService;
import com.jeeplus.finance.projectRecords.service.dto.CwProjectRecordsDTO;
import com.jeeplus.finance.projectRecords.service.dto.CwTreeUserDto;
import com.jeeplus.logging.annotation.ApiLog;
import com.jeeplus.logging.constant.enums.LogTypeEnum;
//import com.jeeplus.sys.utils.DictUtils;
import com.jeeplus.sys.feign.IDictApi;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 财务项目登记controller
 * @author: 徐滕
 * @version: 2022-11-10 14:55
 */
@RestController
@Api("财务项目信息")
@RequestMapping(value = "/cwProjectRecords")
public class CwProjectRecordsController {

    @Resource
    private CwProjectRecordsService cwProjectRecordsService;

    /**
     * 查询部分客户信息数据列表
     * @param customerInfo
     * @param page
     * @return
     */
    @ApiLog("查询部分客户信息数据列表")
    @GetMapping("partialCustomerInfoList")
    public ResponseEntity<IPage<PartialCustomerInfo>> partialCustomerInfoList(PartialCustomerInfo customerInfo, Page<PartialCustomerInfo> page) throws Exception {
        IPage<PartialCustomerInfo> result = new Page<PartialCustomerInfo>();
        result = cwProjectRecordsService.partialCustomerInfoList (page,customerInfo);
        return ResponseEntity.ok (result);
    }

    /**
     * 查询财务项目信息列表
     * @return
     */
    @ApiLog("查询财务项目信息列表")
    @GetMapping("getCwProjectData")
    public List<String> getCwProjectData(String id) throws Exception {
        List<String> idList = cwProjectRecordsService.findAllList (id);
        return idList;
    }

    /**
     * 查询项目组成员id
     * @return
     */
    @ApiLog("查询项目组成员id")
    @GetMapping("getMembersId")
    public List<String> getMembersId(String id) throws Exception {
        List<String> idList = cwProjectRecordsService.getMembersId(id);
        return idList;
    }

    /**
     * 添加项目组成员
     * @return
     */
    @ApiLog("添加项目组成员")
    @PostMapping("insertMembers")
    public void insertMembers(String projectId,String membersId,String userId) throws Exception {
        cwProjectRecordsService.addMembers(projectId,membersId,userId);
    }

    /**
     * 查询财务项目信息列表
     * @param cwProjectRecordsDTO
     * @param page
     * @return
     */
    @ApiLog("查询财务项目信息列表")
    // @PreAuthorize("hasAuthority('cwProjectRecords:list')")
    @GetMapping("list")
    public ResponseEntity<IPage<CwProjectRecordsDTO>> data(CwProjectRecordsDTO cwProjectRecordsDTO, Page<CwProjectRecordsDTO> page) throws Exception {
        IPage<CwProjectRecordsDTO> result = new Page<CwProjectRecordsDTO>();
        result = cwProjectRecordsService.findList (page,cwProjectRecordsDTO);
        return ResponseEntity.ok (result);
    }

    /**
     * 查询财务项目信息列表
     * @param cwProjectRecordsDTO
     * @param page
     * @return
     */
    @ApiLog("查询全部财务项目信息列表")
    // @PreAuthorize("hasAuthority('cwProjectRecords:list')")
    @GetMapping("getAllList")
    public ResponseEntity<IPage<CwProjectRecordsDTO>> getAllList(CwProjectRecordsDTO cwProjectRecordsDTO, Page<CwProjectRecordsDTO> page) throws Exception {
        IPage<CwProjectRecordsDTO> result = new Page<CwProjectRecordsDTO>();
        result = cwProjectRecordsService.getAllList (page,cwProjectRecordsDTO);
        return ResponseEntity.ok (result);
    }

    /**
     * 查询财务项目信息列表(咨询)
     * @param cwProjectRecordsDTO
     * @param page
     * @return
     */
    @ApiLog("查询财务项目信息列表(咨询)")
    // @PreAuthorize("hasAuthority('cwProjectRecords:list')")
    @GetMapping("zxList")
    public ResponseEntity<IPage<CwProjectRecordsDTO>> zxData(CwProjectRecordsDTO cwProjectRecordsDTO, Page<CwProjectRecordsDTO> page) throws Exception {
        IPage<CwProjectRecordsDTO> result = new Page<CwProjectRecordsDTO>();
        result = cwProjectRecordsService.findZXList (page,cwProjectRecordsDTO);
        return ResponseEntity.ok (result);
    }
    /**
     * 查询项目数据集合,和上面list接口是一样的，目的是跳过findList mapper接口的数据规则（比如仅部门可见、仅自己可见之类的）
     */
    @GetMapping("list2")
    public ResponseEntity<IPage<CwProjectRecordsDTO>> data2(CwProjectRecordsDTO cwProjectRecordsDTO, Page<CwProjectRecordsDTO> page) throws Exception {
        IPage<CwProjectRecordsDTO> result = new Page<CwProjectRecordsDTO>();
        result = cwProjectRecordsService.findList2 (page,cwProjectRecordsDTO);
        return ResponseEntity.ok (result);
    }

    /**
     * 查询财务项目详情
     * @param id
     * @return
     */
    @ApiLog("查询财务项目详情")
//    @PreAuthorize ("hasAnyAuthority('cwProjectRecords:view','cwProjectRecords:add','cwProjectRecords:edit')")
    @GetMapping("queryById")
    public ResponseEntity queryById(@RequestParam("id") String id) {
        CwProjectRecordsDTO cwProjectRecordsDTO = cwProjectRecordsService.queryById ( id );
        return ResponseEntity.ok (cwProjectRecordsDTO);
    }

    /**
     * 保存财务项目信息
     * @param cwProjectRecordsDTO
     * @return
     */
    @ApiLog(value = "修改/新增财务项目信息", type = LogTypeEnum.SAVE)
    @PreAuthorize("hasAnyAuthority('cwProjectRecords:add','cwProjectRecords:edit')")
    @PostMapping("save")
    public ResponseEntity save(@Valid @RequestBody CwProjectRecordsDTO cwProjectRecordsDTO) throws Exception {
        cwProjectRecordsService.save(cwProjectRecordsDTO);
        return ResponseEntity.ok ("操作成功");
    }

    /**
     * 保存财务项目信息-流程
     * @param cwProjectRecordsDTO
     * @return
     */
    @ApiLog(value = "保存财务项目信息-流程", type = LogTypeEnum.SAVE)
    @PreAuthorize("hasAnyAuthority('cwProjectRecords:add','cwProjectRecords:edit')")
    @PostMapping("saveForm")
    public ResponseEntity saveForm(@Valid @RequestBody CwProjectRecordsDTO cwProjectRecordsDTO) throws Exception {
        String id = cwProjectRecordsService.saveForm(cwProjectRecordsDTO);
        return ResponseUtil.newInstance().add("businessTable", "cw_project_records").add("businessId", id).ok ("操作成功");
    }

    /**
     * 保存财务项目组成员信息
     * @param cwProjectRecordsDTO
     * @return
     */
    @ApiLog(value = "保存财务项目组成员信息", type = LogTypeEnum.SAVE)
    @PreAuthorize("hasAnyAuthority('cwProjectRecords:add','cwProjectRecords:edit')")
    @PostMapping("updateMembers")
    public ResponseEntity updateMembers(@Valid @RequestBody CwProjectRecordsDTO cwProjectRecordsDTO) {
        return cwProjectRecordsService.updateMembers(cwProjectRecordsDTO);
    }

    /**
     * 删除财务项目信息
     * @param ids
     * @return
     */
    @ApiLog(value = "删除财务项目信息", type = LogTypeEnum.SAVE)
    @PreAuthorize ("hasAuthority('cwProjectRecords:del')")
    @DeleteMapping("delete")
    public ResponseEntity delete(String ids) {
        return cwProjectRecordsService.deleteByIds(ids);
    }

    /**
     * 根据id修改状态值status
     * @param dto
     * @return
     */
    @ApiOperation(value = "根据id修改状态值status")
    @PostMapping(value = "/updateStatusById")
    public ResponseEntity<String> updateStatusById(@RequestBody CwProjectRecordsDTO dto) {
        String s = cwProjectRecordsService.updateStatusById(dto);
        return ResponseEntity.ok(s);
    }
    /**
     * 根据id修改项目等级
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id修改项目等级")
    @PostMapping(value = "/projectUpgrade")
    public ResponseEntity<String> projectUpgrade(@RequestParam("id") String id) {
        String s = cwProjectRecordsService.projectUpgrade(id);
        return ResponseEntity.ok(s);
    }

    /**
     * 导出项目数据
     *
     * @param cwProjectRecordsDTO
     * @param page
     * @param response
     * @throws Exception
     */
    @ApiLog(value = "导出项目数据", type = LogTypeEnum.EXPORT)
    @GetMapping("export")
    @PreAuthorize ("hasAuthority('cwProjectRecords:export')")
    @ApiOperation(value = "导出项目数据")
    public void exportFile(CwProjectRecordsDTO cwProjectRecordsDTO, Page <CwProjectRecordsDTO> page, ExcelOptions options, HttpServletResponse response) throws Exception {
        String fileName = options.getFilename();
        String sheetName = options.getSheetName();
        List<CwProjectRecordsDTO> result = new ArrayList<>();
        if ( ExportMode.current.equals ( options.getMode() ) ) {
            result = cwProjectRecordsService.findList (page,cwProjectRecordsDTO).getRecords();
        } else if (ExportMode.selected.equals ( options.getMode() )) {
            result = cwProjectRecordsService.findList (page,cwProjectRecordsDTO).getRecords().stream ( ).filter ( item ->
                    options.getSelectIds ( ).contains ( item.getId ( ) )
            ).collect ( Collectors.toList ( ) );
        } else {
            page.setSize (-1);
            page.setCurrent (0);
            result = cwProjectRecordsService.findList (page,cwProjectRecordsDTO).getRecords();
        }
        result.stream().forEach(item -> {
            if (StringUtils.isNotBlank(item.getStatus())){
                item.setStatus(SpringUtil.getBean ( IDictApi.class ).getDictLabel(item.getStatus(),"cw_status",""));
            }
        });
        EasyPoiUtil.exportExcel ( result, sheetName,  sheetName, CwProjectRecordsDTO.class, fileName, response );

    }

    /**
     * 根据客户id获取关联的项目信息
     * @param clientId
     * @return
     */
    @ApiOperation(value = "根据客户id获取关联的项目信息")
    @GetMapping(value = "/getByClientId")
    public ResponseEntity<List<CwProjectRecordsDTO>> getByClientId(String clientId, CwProjectRecordsDTO cwProjectRecordsDTO) throws Exception {
        List<CwProjectRecordsDTO> cwProjectRecordsDTOList = cwProjectRecordsService.getByClientId(clientId,cwProjectRecordsDTO);
        return ResponseEntity.ok(cwProjectRecordsDTOList);
    }

    /**
     * 根据合同id获取关联的项目信息
     * @param contractId
     * @return
     */
    @ApiOperation(value = "根据合同id获取关联的项目信息")
    @GetMapping(value = "/getByContractId")
    public ResponseEntity<List<CwProjectRecordsDTO>> getByContractId(String contractId,CwProjectRecordsDTO cwProjectRecordsDTO) throws Exception {
        List<CwProjectRecordsDTO> cwProjectRecordsDTOList = cwProjectRecordsService.getByContractId(contractId,cwProjectRecordsDTO);
        return ResponseEntity.ok(cwProjectRecordsDTOList);
    }

    /**
     * 查询当前登录人创建的项目 以及 所属项目组的项目(当前登录人未被移除项目组)
     * @return
     */
    @ApiOperation(value = "查询当前登录人创建的项目以及所属项目组的项目")
    @GetMapping(value = "/getHaveProjectIds")
    public ResponseEntity<List<String>> getHaveProjectIds() {
        return cwProjectRecordsService.getHaveProjectIds();
    }


    /**
     * 查找该报告及报告对应项目下的开票列表
     */
    @ApiOperation(value = "查询该报告及报告对应项目下的开票列表")
    @GetMapping(value = "/getReportById")
    public ResponseEntity<List<CwProjectRecordsDTO>> getReportById(String id,CwProjectRecordsDTO cwProjectRecordsDTO) throws Exception {
        List<CwProjectRecordsDTO> reportList=  cwProjectRecordsService.getReportById(id,cwProjectRecordsDTO);
        return ResponseEntity.ok(reportList);
    }


    /**
     * 该项目下审计收费不为0的报告信息
     */
    @ApiOperation(value = "该项目下审计收费不为0的报告信息")
    @GetMapping(value = "/getReportByProjectId")
    public ResponseEntity<List<CwProjectRecordsDTO>> getReportByProjectId(String id,String projectId) throws Exception {
        List<CwProjectRecordsDTO> reportList=  cwProjectRecordsService.getReportByProjectId(id,projectId);
        return ResponseEntity.ok(reportList);
    }

    /**
     * 查询财务项目计划详情
     * @param id
     * @return
     */
    @ApiLog("查询财务项目计划详情")
//    @PreAuthorize ("hasAnyAuthority('cwProjectRecords:view','cwProjectRecords:add','cwProjectRecords:edit')")
    @GetMapping("queryPlanById")
    public ResponseEntity queryPlanById(@RequestParam("id") String id) {
        CwProjectRecordsDTO cwProjectRecordsDTO = cwProjectRecordsService.queryPlanById ( id );
        return ResponseEntity.ok (cwProjectRecordsDTO);
    }

    /**
     * 导出项目计划数据
     *
     * @param cwProjectRecordsDTO
     * @param page
     * @param response
     * @throws Exception
     */
    @ApiLog(value = "导出项目计划数据", type = LogTypeEnum.EXPORT)
    @GetMapping("exportPlan")
//    @PreAuthorize ("hasAuthority('cwProjectRecords:export')")
    @ApiOperation(value = "导出项目计划数据")
    public void exportPlan(CwProjectRecordsDTO cwProjectRecordsDTO,  ExcelOptions options, HttpServletResponse response) throws Exception {
        CwProjectRecords records = cwProjectRecordsService.getById(cwProjectRecordsDTO.getId());
        String fileName = records.getProjectName()+"-项目计划.xlsx";
        String sheetName = records.getProjectName()+"-项目计划.xlsx";
        List<CwProjectPlanDetails> result = new ArrayList<>();
        if (ExportMode.selected.equals ( options.getMode() )) {
            result = cwProjectRecordsService.findPlanList(cwProjectRecordsDTO.getId());
        }

        EasyPoiUtil.exportExcel ( result, sheetName,  sheetName, CwProjectPlanDetails.class, fileName, response );

    }

    @ApiOperation(value = "用户树形")
    @GetMapping(value = "/userTree")
    public ResponseEntity<List<CwTreeUserDto>> userTree(@RequestParam String name,@RequestParam String id) {
        List<CwTreeUserDto> list = cwProjectRecordsService.userTree(name,id);
        return ResponseEntity.ok(list);
    }

    /**
     * 保存财务项目计划信息
     * @param cwProjectRecordsDTO
     * @return
     */
    @ApiLog(value = "修改/新增财务项目计划信息", type = LogTypeEnum.SAVE)
//    @PreAuthorize("hasAnyAuthority('cwProjectRecords:add','cwProjectRecords:edit')")
    @PostMapping("savePlanForm")
    public ResponseEntity savePlanForm(@Valid @RequestBody CwProjectRecordsDTO cwProjectRecordsDTO) throws Exception {
        cwProjectRecordsService.savePlanForm(cwProjectRecordsDTO);
        return ResponseEntity.ok ("操作成功");
    }

    /**
     * 获取项目计划中的任务阶段
     */
    @ApiOperation(value = "获取项目计划中的任务阶段")
    @GetMapping(value = "/getTaskPhase")
    public List<String> getTaskPhase(){
        List<String> data = cwProjectRecordsService.getTaskPhase();
        return data;
    }

    /**
     * 获取项目计划详情
     */
    @ApiOperation(value = "获取项目计划详情")
    @GetMapping(value = "/getPlanDetails")
    public String getPlanDetails(){
       List<CwProjectPlanDetails> list= cwProjectRecordsService.getPlanDetails();
       return JSON.toJSONString(list);
    }









}
