package com.jeeplus.finance.reimbursementApproval.approvalInfo.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
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.CwProjectRecords;
import com.jeeplus.finance.reimbursementApproval.approvalInfo.domain.CwReimbursementInfo;
import com.jeeplus.finance.reimbursementApproval.approvalInfo.domain.ProgramProjectListInfo;
import com.jeeplus.finance.reimbursementApproval.approvalInfo.service.CwReimbursementInfoService;
import com.jeeplus.finance.reimbursementApproval.approvalInfo.service.dto.*;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.logging.annotation.ApiLog;
import com.jeeplus.logging.constant.enums.LogTypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: 王强
 * @create: 2022-11-24 16:44
 **/
@RestController
@Api(tags ="财务-报销申请")
@RequestMapping(value = "/reimbursementApproval/info")
public class CwReimbursementInfoController {

    @Resource
    private CwReimbursementInfoService service;
    @Resource
    private IFlowableApi flowTaskService;


    /**
     * 报告号查询
     * @param dto
     * @return
     */
    @ApiOperation(value = "报告号查询")
    @GetMapping("/reportNoList")
    public ResponseEntity<IPage<ReportNoDto>> reportNoList(Page<ReportNoDto> page, ReportNoDto dto) throws Exception{
        IPage<ReportNoDto> iPage = service.getReportNoList(page, dto);
        return ResponseEntity.ok(iPage);
    }

    /**
     * 列表查询
     * @param dto/reimbursementApproval/type/bxList
     * @return
     */
    @ApiOperation(value = "列表查询")
    @GetMapping("/list")
    public ResponseEntity<IPage<RetureListDto>> list(Page<RetureListDto> page, QueryListDto dto) throws Exception{
        IPage<RetureListDto> iPage = service.list(page, dto);
        iPage.getRecords().stream().forEach(i -> {
            // 报销审批
            if (StringUtils.isNotBlank(i.getTaskId()) && StringUtils.isNotBlank(i.getType())) {
                if ("2".equals(i.getType())) { // “审核中”的数据要获取数据审核人
                    i.setAuditUserIds(flowTaskService.getTaskAuditUsers(i.getTaskId()));  // 获取数据审核人
                }
            }
        });
        return ResponseEntity.ok(iPage);
    }

    /**
     * 项目登记列表
     * @param info
     * @param page
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "项目登记列表")
    @GetMapping(value = "/projectList")
    public ResponseEntity<IPage<ProgramProjectListInfo>> projectList(ProgramProjectListInfo info, Page<ProgramProjectListInfo> page) throws Exception {
        IPage<ProgramProjectListInfo> list = service.projectList(page, info, "1");
        return ResponseEntity.ok (list);
    }

    /**
     * 新增/修改
     * @param dto
     * @return
     */
    @ApiOperation(value = "新增、修改")
    @PostMapping("/save")
    public ResponseEntity<String> save(@RequestBody SaveInfoDto dto) throws Exception{
        CwReimbursementInfo s = service.save(dto);
        return ResponseUtil.newInstance().add("businessTable", "cw_reimbursement_info")
                .add("businessId", s.getId())
                .add("no", s.getNo())
                .ok ("操作成功");
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @ApiOperation(value = "删除")
    @GetMapping("/remove")
    public ResponseEntity<String> remove(@RequestParam String id){
        String s = service.remove(id);
        return ResponseEntity.ok(s);
    }

    /**
     * 查询
     * @param id
     * @return
     */
    @ApiOperation(value = "查询")
    @GetMapping("/findById")
    public ResponseEntity<SaveInfoDto> findById(@RequestParam String id) throws Exception{
        SaveInfoDto dto = service.findById(id);
        return ResponseEntity.ok(dto);
    }

    @ApiOperation(value = "发票号判断")
    @GetMapping("/checkNumber")
    public ResponseEntity<Boolean> checkNumber(@RequestParam String number) {
        Boolean is = service.checkNumber(number);
        return ResponseEntity.ok(is);
    }

    /**
     * 根据id修改状态status
     */
    @ApiOperation(value = "根据id修改状态status")
    @PostMapping(value = "updateStatusById")
    public void updateStatusById(@RequestBody RetureListDto dto) {
        service.updateStatusById(dto);
    }

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


    @ApiLog(value = "财务报销数据", type = LogTypeEnum.EXPORT)
    @GetMapping("exportFile")
    @ApiOperation(value = "财务报销数据")
    public void exportFile(QueryListDto cwDTO, Page <RetureListDto> page, ExcelOptions options, HttpServletResponse response) throws Exception {
        String fileName = options.getFilename();
        String sheetName = options.getSheetName();
        List<RetureListDto> result = new ArrayList<>();
        if ( ExportMode.current.equals ( options.getMode() ) ) {
            result = service.list (page,cwDTO).getRecords();
        } else if (ExportMode.selected.equals ( options.getMode() )) {
            result = service.list (page,cwDTO).getRecords().stream ( ).filter ( item ->
                    options.getSelectIds ( ).contains ( item.getId ( ) )
            ).collect ( Collectors.toList ( ) );
        } else {
            page.setSize (-1);
            page.setCurrent (0);
            result = service.list (page,cwDTO).getRecords();
        }
        EasyPoiUtil.exportExcel ( result, sheetName,  sheetName, RetureListDto.class, fileName, response );

    }

    @ApiLog(value = "财务电子发票报销数据")
    @GetMapping("exportInvoiceReimbursementFile")
    @ApiOperation(value = "财务电子发票报销数据")
    public void exportInvoiceReimbursementFile(QueryListDto cwDTO, Page <RetureListDto> page, ExcelOptions options, HttpServletResponse response) throws Exception {
        String fileName = "财务电子发票报销数据表";
        String sheetName = "财务电子发票报销列表";
        List<RetureListDto> result = new ArrayList<>();
        if ( com.jeeplus.common.excel.ExportMode.current.equals ( options.getMode() ) ) {
            result = service.list (page,cwDTO).getRecords();
        } else if (com.jeeplus.common.excel.ExportMode.selected.equals ( options.getMode() )) {
            result = service.list (page,cwDTO).getRecords().stream ( ).filter ( item ->
                    options.getSelectIds ( ).contains ( item.getId ( ) )
            ).collect ( Collectors.toList ( ) );
        } else {
            page.setSize (-1);
            page.setCurrent (0);
            if(com.jeeplus.utils.StringUtils.isBlank(cwDTO.getReimbursementType())){
                cwDTO.setReimbursementType("1");
            }
            result = service.list (page,cwDTO).getRecords();
        }
        List<String> idList = Lists.newArrayList();
        for (RetureListDto listDto : result) {
            idList.add(listDto.getId());
        }
        List<CwReimbursementAmountInfoDTO> invoiceReimbursementAmountList = Lists.newArrayList();
        if(idList.size()>0){
            invoiceReimbursementAmountList = service.getInvoiceReimbursementAmountList(idList);
        }
        for (int i = 1;i <=invoiceReimbursementAmountList.size();i ++){
            CwReimbursementAmountInfoDTO reimbursementAmountInfoDTO = invoiceReimbursementAmountList.get(i - 1);
            reimbursementAmountInfoDTO.setSerialNumber(i);
        }

        EasyPoiUtil.exportExcel ( invoiceReimbursementAmountList, sheetName,  sheetName, CwReimbursementAmountInfoDTO.class, fileName, response );

    }

    @ApiOperation(value = "关联报销")
    @GetMapping(value = "/relationReimbursementList")
    public ResponseEntity<IPage<RetureListDto>> relationReimbursementList(Page<RetureListDto> page, @RequestParam("id") String id) {
        IPage<RetureListDto> listDtoIPage = service.relationReimbursementList(page, id);
        return ResponseEntity.ok(listDtoIPage);
    }

    @ApiOperation(value = "列表查询")
    @GetMapping("/queryByProIds")
    public ResponseEntity<List<CwProjectRecords>> queryByProIds(String ids){
        List<CwProjectRecords> cwProjectRecords = service.queryByProIds(ids);
        return ResponseEntity.ok(cwProjectRecords);
    }

    /**
     * 根据发票号查询是否已经或正在报销
     * @return
     */
    @ApiLog(value = "根据发票号查询是否已经或正在报销")
    @GetMapping("getEffectiveDataByInvoiceNumber")
    @ApiOperation(value = "根据发票号查询是否已经或正在报销")
    public Map<String,Object> getEffectiveDataByInvoiceNumber(String invoiceNumber,String id){
        Map map = new HashMap();
        Integer count = service.getEffectiveDataByInvoiceNumber(invoiceNumber,id);
        if(count>0){
            map.put("success",false);
            map.put("message","发票号：" + invoiceNumber + " 已发起或完成报销，请勿重复报销");
        }else{
            map.put("success",true);
        }
        return map;
    }
}
