package com.jeeplus.test.reimbursementAssess.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.aop.demo.annotation.DemoMode;
import com.jeeplus.aop.logging.annotation.ApiLog;
import com.jeeplus.core.excel.ExcelOptions;
import com.jeeplus.core.excel.ExportMode;
import com.jeeplus.core.excel.utils.EasyPoiUtil;
import com.jeeplus.sys.service.dto.RoleDTO;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.utils.StringUtils;
import com.jeeplus.test.reimbursementAssess.domain.dto.AssessReimbursementDTO;
import com.jeeplus.test.reimbursementAssess.service.AssessReimbursementSysService;
import com.jeeplus.test.reimbursementProject.domain.dto.ProjectReimbursementDTO;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author li-peike
 * @version 1.0.0
 * @ClassName ReimbursementSysController.java
 * @Description TODO 发票信息
 * @createTime 2022年05月05日 20:41:00
 */
@RestController
@RequestMapping("/assess/reimbursement")
public class AssessReimbursementSysController {

    @Autowired
    private AssessReimbursementSysService service;

    /**
     * 根据id查询业务信息
     * @param id
     * @return
     */
    @ApiLog("查询业务具体信息")
    @PreAuthorize("hasAnyAuthority('assess:reimbursement:view','assess:reimbursement:add','assess:reimbursement:edit')")
    @GetMapping("queryBusinessById")
    public ResponseEntity queryBusinessById(@RequestParam String id) {
        AssessReimbursementDTO reimbursementDTO = service.queryBusinessById (id);
        return ResponseEntity.ok (reimbursementDTO);
    }

    /**
     * 根据发票id查询业务信息
     * @param id
     * @return
     */
    @ApiLog("根据发票id查询业务具体信息")
    @PreAuthorize("hasAnyAuthority('assess:reimbursement:view','assess:reimbursement:add','assess:reimbursement:edit')")
    @GetMapping("queryBusinessByInvoiceId")
    public ResponseEntity queryBusinessByInvoiceId(@RequestParam String id) {
        AssessReimbursementDTO reimbursementDTO = service.queryBusinessByInvoiceId (id);
        return ResponseEntity.ok (reimbursementDTO);
    }
    /**
     * 根据id查询部门
     * @param id
     * @return
     */
    @ApiLog("查询发票具体信息")
    @PreAuthorize("hasAnyAuthority('assess:reimbursement:view','assess:reimbursement:add','assess:reimbursement:edit')")
    @GetMapping("queryInvoiceById")
    public ResponseEntity queryInvoiceById(@RequestParam String id) {
        AssessReimbursementDTO reimbursementDTO = service.queryInvoiceById (id);
        return ResponseEntity.ok (reimbursementDTO);
    }


    /**
     * 查询报销信息
     * @return
     */
    @ApiLog("查询未进行报销流程的发票信息集合")
    @GetMapping("list")
    public ResponseEntity list(AssessReimbursementDTO reimbursementDTO,  Page<AssessReimbursementDTO> page) {
        IPage<AssessReimbursementDTO> list = service.findList(page,reimbursementDTO);
        return ResponseEntity.ok(list);
    }


    /**
     * 查询报销信息
     * @return
     */
    @ApiLog("查询业务报销信息")
    @GetMapping("treeData")
    public ResponseEntity treeData(AssessReimbursementDTO reimbursementDTO,  Page<AssessReimbursementDTO> page) {
        IPage<AssessReimbursementDTO> list = service.treeData(page,reimbursementDTO);
        return ResponseEntity.ok(list);
    }

    /**
     * 上传文件
     * @return
     * @throws IOException
     */
    @ApiLog("上传文件")
    @RequestMapping("uploadFile")
    public Map<String,Object> uploadFile(HttpServletRequest request, MultipartFile file) {
        Map<String,Object> map = new HashMap<>();
        try {
            List <AssessReimbursementDTO> list = EasyPoiUtil.importExcel ( file, 0, 1, AssessReimbursementDTO.class );
            /*ImportExcel ei = new ImportExcel(file, 0, 0);
            List<AssessReimbursementDTO> list = ei.getDataList(AssessReimbursementDTO.class);*/
            map = service.save(list);
            return map;
        } catch (Exception e) {
            map.put("message", "文件上传失败。失败原因："+ e.getMessage());
            map.put("success", false);
            return map;
        }
    }


    /**
     * 保存业务报销编码
     * @return
     */
    @ApiLog("保存业务报销编码")
    @PostMapping("saveBusiness")
    public ResponseEntity saveBusiness(@Valid @RequestBody AssessReimbursementDTO reimbursementDTO) {
        if(!"1".equals(reimbursementDTO.getRandomType()) && StringUtils.isBlank(reimbursementDTO.getBusinessCode())){
            return ResponseEntity.badRequest ().body ("报销批次不可为空，请重新填写!");
        }
        service.saveBusiness(reimbursementDTO);
        return ResponseEntity.ok("保存报销批次" + reimbursementDTO.getBusinessCode() + "成功");
    }
    /**
     * 保存业务报销编码
     * @return
     */
    @ApiLog("保存业务报销比例")
    @PostMapping("updateReimbursementRatio")
    public ResponseEntity updateReimbursementRatio(@Valid @RequestBody AssessReimbursementDTO reimbursementDTO) {
        if(StringUtils.isBlank(reimbursementDTO.getReimbursementRatio())){
            return ResponseEntity.badRequest ().body ("报销比例不可为空，请重新填写!");
        }
        service.updateReimbursementRatio(reimbursementDTO);
        return ResponseEntity.ok("保存报销比例" + reimbursementDTO.getBusinessCode() + "成功");
    }


    /**
     * 保存发票收款时间
     * @return
     */
    @ApiLog("保存发票收款时间")
    @PostMapping("saveInvoice")
    public ResponseEntity saveInvoice(@Valid @RequestBody AssessReimbursementDTO reimbursementDTO) {
        service.saveInvoice(reimbursementDTO);
        return ResponseEntity.ok("保存发票收款时间成功");
    }


    /**
     * 保存发票收款时间
     * @return
     */
    @ApiLog("修改发票信息")
    @PostMapping("modifyInvoice")
    public ResponseEntity modifyInvoice(@Valid @RequestBody AssessReimbursementDTO reimbursementDTO) {
        service.modifyInvoice(reimbursementDTO);
        return ResponseEntity.ok("修改发票信息成功");
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @DemoMode
    @ApiLog("批量删除")
    @PreAuthorize("hasAuthority('assess:reimbursement:del')")
    @DeleteMapping("delete")
    public ResponseEntity delete(String ids) {
        String idArray[] =ids.split(",");
        service.removeBusinessByIds ( Lists.newArrayList (idArray) );
        return ResponseEntity.ok ("删除成功！");
    }

    /**
     * 保存业务报销编码
     * @return
     */
    @ApiLog("保存收款时间信息")
    @PostMapping("saveGatheringTime")
    public ResponseEntity saveGatheringTime(@Valid @RequestBody AssessReimbursementDTO reimbursementDTO) {
        if(StringUtils.isBlank(reimbursementDTO.getId())){
            return ResponseEntity.badRequest ().body ("未选择发票信息!");
        }
        if(null == reimbursementDTO.getGatheringTime()){
            return ResponseEntity.badRequest ().body ("未选择收款时间!");
        }
        Map<String, Object> map = service.saveGatheringTime(reimbursementDTO);
        Boolean success = (Boolean) map.get("success");
        if(success){
            return ResponseEntity.ok("保存收款时间" + reimbursementDTO.getBusinessCode() + "成功");
        }
        return ResponseEntity.badRequest().body ( map.get("message"));
    }

    /**
     * 删除业务信息
     * @param ids
     * @return
     */
    @DemoMode
    @ApiLog("删除业务信息")
    @PreAuthorize("hasAuthority('assess:reimbursement:del')")
    @DeleteMapping("deleteBusiness")
    public ResponseEntity deleteBusiness(String ids) {
        String idArray[] =ids.split(",");
        service.removeBusinessByIds ( Lists.newArrayList (idArray) );
        return ResponseEntity.ok ("删除成功！");
    }

    /**
     * 删除发票信息
     * @param ids
     * @return
     */
    @DemoMode
    @ApiLog("删除发票信息")
    @PreAuthorize("hasAuthority('assess:reimbursement:del')")
    @DeleteMapping("deleteInvoice")
    public ResponseEntity deleteInvoice(String ids) {
        String idArray[] =ids.split(",");
        service.removeInvoiceByIds ( Lists.newArrayList (idArray) );
        return ResponseEntity.ok ("删除成功！");
    }

    /**
     * 批次报销
     * @param invoiceNumbers
     * @return
     */
    @DemoMode
    @ApiLog("批次报销")
    @PreAuthorize("hasAuthority('assess:reimbursement:addBatchReimbursement')")
    @PutMapping("addBatchReimbursement")
    public ResponseEntity addBatchReimbursement(String[] invoiceNumbers) {
        ArrayList<String> invoiceIdList = Lists.newArrayList(invoiceNumbers);
        if(invoiceIdList.size()<=0){
            return ResponseEntity.badRequest().body ("请选择需要批量报销的发票信息");
        }
        service.addBatchReimbursement (invoiceIdList);
        return ResponseEntity.ok ("批量报销操作成功");
    }

    /**
     * 导出分所报销数据
     * @param reimbursementDTO
     * @param page
     * @param response
     * @throws Exception
     */
    @ApiLog("导出兴光评估报销数据")
    @GetMapping("export")
    @ApiOperation(value = "导出兴光评估报销数据excel")
    public void exportFile(AssessReimbursementDTO reimbursementDTO, Page <AssessReimbursementDTO> page, ExcelOptions options, HttpServletResponse response) {
        String fileName = options.getFilename ( );

        List <AssessReimbursementDTO> result;
        if ( ExportMode.current.equals ( options.getMode ( ) ) ) {
            result = service.findPage ( page, reimbursementDTO );
        } else if ( ExportMode.selected.equals ( options.getMode ( ) ) ) {
            result = service.findPage ( page, reimbursementDTO ).stream ( ).filter ( reimbursement ->
                    options.getSelectIds ( ).contains ( reimbursement.getId ( ) )
            ).collect ( Collectors.toList ( ) );
        } else {
            page.setSize ( -1 );
            page.setCurrent ( 0 );
            result = service.findPage ( page, reimbursementDTO );
        }
        EasyPoiUtil.exportExcel ( result, "兴光评估报销数据",  options.getSheetName ( ), AssessReimbursementDTO.class, fileName, response );
    }
}
