package com.jeeplus.finance.invoice.controller;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.aop.demo.annotation.DemoMode;
import com.jeeplus.common.excel.ExcelOptions;
import com.jeeplus.common.excel.annotation.ExportMode;
import com.jeeplus.common.utils.ResponseUtil;
import com.jeeplus.finance.invoice.domain.CwFinanceInvoice;
import com.jeeplus.finance.invoice.domain.CwFinanceInvoiceBase;
import com.jeeplus.finance.invoice.service.CwFinanceInvoiceService;
import com.jeeplus.finance.invoice.service.dto.CwFinanceDTO;
import com.jeeplus.finance.invoice.service.dto.CwFinanceImportDTO;
import com.jeeplus.finance.invoice.service.dto.CwFinanceInvoiceDTO;
import com.jeeplus.finance.invoice.service.dto.CwFinanceInvoiceDetailDTO;
import com.jeeplus.finance.invoice.util.EasyPoiUtil;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.logging.annotation.ApiLog;
import com.jeeplus.logging.constant.enums.LogTypeEnum;
//import com.jeeplus.sys.utils.DictUtils;
//import com.jeeplus.sys.utils.SpringContextHolder;
import com.jeeplus.sys.feign.IDictApi;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@Api("财务管理-发票")
@RestController
@RequestMapping(value = "/cw_finance/invoice")
public class CwFinanceInvoiceController {

    private static Logger log = LoggerFactory.getLogger(CwFinanceInvoiceController.class);

    @Resource
    private CwFinanceInvoiceService cwFinanceInvoiceService;

    @Resource
    private IFlowableApi flowTaskService;

    /**
     * 查询发票列表
     * @param cwFinanceInvoiceDTO
     * @param page
     * @return
     * @throws Exception
     */
    @ApiLog("查询发票列表")
    @PreAuthorize("hasAuthority('cw_finance:invoice:list')")
    @GetMapping("list")
    public ResponseEntity<IPage<CwFinanceInvoiceDTO>> data(CwFinanceInvoiceDTO cwFinanceInvoiceDTO, Page<CwFinanceInvoiceDTO> page) throws Exception {
        IPage<CwFinanceInvoiceDTO> result = new Page<CwFinanceInvoiceDTO>();
        result = cwFinanceInvoiceService.findList (page, cwFinanceInvoiceDTO,"");
        System.out.println("当前时间1："+System.currentTimeMillis());
        result.getRecords().stream().forEach(i -> {
            // 发票申请
            if (StringUtils.isNotBlank(i.getTaskId()) && StringUtils.isNotBlank(i.getStatus())) {
                if ("2".equals(i.getStatus())) { // “审核中”的数据要获取数据审核人
                    i.setAuditUserIds(flowTaskService.getTaskAuditUsers(i.getTaskId()));  // 获取数据审核人
                }
            }
            // 发票作废
            if (StringUtils.isNotBlank(i.getInvalidTaskId()) && StringUtils.isNotBlank(i.getStatus())) {
                if ("6".equals(i.getStatus())) { // “审核中”的数据要获取数据审核人
                    i.setAuditUserIdsInvalid(flowTaskService.getTaskAuditUsers(i.getInvalidTaskId()));  // 获取数据审核人
                }
            }
            if(StringUtils.isNotBlank(i.getBillingType()) && "2".equals(i.getBillingType()) && StringUtils.isNotBlank(i.getName())){
                i.setBillingWorkplaceReal(i.getName());
            }
        });
        System.out.println("当前时间2："+System.currentTimeMillis());
        return ResponseEntity.ok (result);
    }

    /**
     * 查询发票列表
     * @param cwFinanceInvoiceDTO
     * @param page
     * @return
     * @throws Exception
     */
    @ApiLog("查询发票列表")
    @PreAuthorize("hasAuthority('cw_finance:invoice:list')")
    @GetMapping("redList")
    public ResponseEntity<IPage<CwFinanceInvoiceDTO>> redList(CwFinanceInvoiceDTO cwFinanceInvoiceDTO, Page<CwFinanceInvoiceDTO> page) throws Exception {
        IPage<CwFinanceInvoiceDTO> result = new Page<CwFinanceInvoiceDTO>();
        result = cwFinanceInvoiceService.findRedList (page, cwFinanceInvoiceDTO,"");
        return ResponseEntity.ok (result);
    }

    /**
     * 查询发票数据
     * @param id
     * @return
     */
    @ApiLog("查询发票数据")
    //@PreAuthorize ("hasAnyAuthority('cw_finance:invoice:view','cw_finance:invoice:add','cw_finance:invoice:edit')")
    @GetMapping("queryById")
    public ResponseEntity queryById(@RequestParam("id") String id) {
        CwFinanceInvoiceDTO cwFinanceInvoiceDTO = cwFinanceInvoiceService.queryById ( id );
        return ResponseEntity.ok (cwFinanceInvoiceDTO);
    }

    /**
     * 查询发票号是否存在
     * @param number
     * @return
     */
    @ApiLog("查询发票号是否存在")
    @GetMapping("queryByNumber")
    public ResponseEntity queryByNumber(@RequestParam("number") String number, @RequestParam(value="id", required = false) String id) {
        Boolean bool = cwFinanceInvoiceService.queryByNumber ( number, id );
        return ResponseEntity.ok (bool);
    }

    /**
     * 保存发票数据
     * @param cwFinanceInvoiceDTO
     * @return
     */
    @ApiLog(value = "修改/新增发票数据", type = LogTypeEnum.SAVE)
    @PreAuthorize("hasAnyAuthority('cw_finance:invoice:add','cw_finance:invoice:edit')")
    @PostMapping("save")
    public ResponseEntity save(@Valid @RequestBody CwFinanceInvoiceDTO cwFinanceInvoiceDTO) throws Exception {
        cwFinanceInvoiceService.saveInvoice(cwFinanceInvoiceDTO);
        return ResponseEntity.ok ("操作成功");
    }

    /**
     * 保存发票数据-流程
     * @param cwFinanceInvoiceDTO
     * @return
     */
    @ApiLog(value = "保存发票数据-流程", type = LogTypeEnum.SAVE)
    @PreAuthorize("hasAnyAuthority('cw_finance:invoice:add','cw_finance:invoice:edit')")
    @PostMapping("saveForm")
    public ResponseEntity saveForm(@Valid @RequestBody CwFinanceInvoiceDTO cwFinanceInvoiceDTO) throws Exception {
        CwFinanceInvoice cwFinanceInvoice = cwFinanceInvoiceService.saveForm(cwFinanceInvoiceDTO);
        return ResponseUtil.newInstance().add("businessTable", "cw_finance_invoice")
                .add("businessId", cwFinanceInvoice.getId())
                .add("recordType",cwFinanceInvoice.getRecordType())
                .add("no", cwFinanceInvoice.getNo())
                .ok ("操作成功");
    }

    /**
     * 作废发票数据-流程
     * @param cwFinanceInvoiceDTO
     * @return
     */
    @ApiLog(value = "作废发票数据-流程", type = LogTypeEnum.SAVE)
    @PreAuthorize("hasAnyAuthority('cw_finance:invoice:add','cw_finance:invoice:edit')")
    @PostMapping("saveFormInvalid")
    public ResponseEntity saveFormInvalid(@Valid @RequestBody CwFinanceInvoiceDTO cwFinanceInvoiceDTO) throws Exception {
        String id = cwFinanceInvoiceService.saveFormInvalid(cwFinanceInvoiceDTO);
        return ResponseUtil.newInstance().add("businessTable", "cw_finance_invoice_invalid").add("businessId", id).ok ("操作成功");
    }

    /**
     * 根据发票作废数据的id查询发票id
     * @param id
     * @return
     */
    @GetMapping("queryIdByInvalidId")
    @ApiOperation(value = "查询发票号是否存在")
    public ResponseEntity<CwFinanceDTO> queryIdByInvalidId(@RequestParam String id) {
        String businessId = cwFinanceInvoiceService.queryIdByInvalidId ( id );
        CwFinanceDTO cwFinanceDTO = new CwFinanceDTO();
        cwFinanceDTO.setBusinessId(businessId);
        return ResponseEntity.ok(cwFinanceDTO);
    }

    /**
     * 删除附件类型
     * @param ids
     * @return
     */
    @ApiLog(value = "删除附件类型", type = LogTypeEnum.SAVE)
    @PreAuthorize ("hasAuthority('cw_finance:invoice:del')")
    @DeleteMapping("delete")
    public ResponseEntity delete(String ids) {
        return cwFinanceInvoiceService.deleteByIds(ids);
    }

    /**
     * 根据id修改状态值status
     * @param dto
     * @return
     */
    @ApiOperation(value = "根据id修改状态值status")
    @PostMapping(value = "/updateStatusById")
    public ResponseEntity<String> updateStatusById(@RequestBody CwFinanceInvoiceDTO dto) {
        String s = cwFinanceInvoiceService.updateStatusById(dto);
        return ResponseEntity.ok(s);
    }

    /**
     * 确认收款
     * @param dto
     * @return
     */
    @ApiOperation(value = "确认收款")
    @PostMapping(value = "/isReceivables")
    public ResponseEntity<String> isReceivables(@RequestBody CwFinanceInvoiceDTO dto) {
        String s = cwFinanceInvoiceService.isReceivables(dto);
        return ResponseEntity.ok(s);
    }

    /**
     * 下载发票明细导入模板
     *
     * @param response
     * @return
     */
    @GetMapping("/importDetail/template")
    @ApiOperation(value = "下载模板")
    public void importFileTemplate(HttpServletResponse response, HttpServletRequest request) {
        try {
            InputStream inputStream = this.getClass().getResourceAsStream("/dot/发票明细导入模板.xlsx");
            //强制下载不打开
            response.setContentType("application/force-download");
            OutputStream out = response.getOutputStream();
            //使用URLEncoder来防止文件名乱码或者读取错误
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("finance_invoice_detail_template.xlsx", "UTF-8"));
            int b = 0;
            byte[] buffer = new byte[1000000];
            while (b != -1) {
                b = inputStream.read(buffer);
                if (b != -1) out.write(buffer, 0, b);
            }
            inputStream.close();
            out.close();
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入发票明细数据
     *
     * @return
     */
    @DemoMode
    @PostMapping("/importDetail")
    @ApiLog(value = "导入发票明细数据excel", type = LogTypeEnum.IMPORT)
    public ResponseEntity importDetail(MultipartFile file, HttpServletRequest request) throws IOException {

        ArrayList<CwFinanceInvoiceDetailDTO> arrayList = new ArrayList<>();
        HashMap<String,String> hashMap = new HashMap<>();

        List<CwFinanceInvoiceDetailDTO> listA = new ArrayList<>();
        //获取sheet
        listA = EasyPoiUtil.importExcel(file, 0, 1, CwFinanceInvoiceDetailDTO.class);
        //去除excel中的空行
        listA = getExcelList(listA);
        //导入前检测数据
        String resultA = cwFinanceInvoiceService.importDecide(listA, arrayList, hashMap);
        if(StringUtils.isNotBlank(resultA)){
            //有返回值，说明导入的数据不正确。向用户抛提示
            return ResponseEntity.badRequest().body  (resultA);
        }
        //判断文件中是否有重复的发票号
        if(hashMap.size() != listA.size()){
            return ResponseEntity.badRequest().body  ("文件中存在重复的发票号");
        }

        return ResponseEntity.ok(arrayList);
    }

    /**
     * 去除excel中的空行
     * @param list
     * @return
     */
    public ArrayList<CwFinanceInvoiceDetailDTO> getExcelList(List<CwFinanceInvoiceDetailDTO> list){

        ArrayList<CwFinanceInvoiceDetailDTO> cwFinanceInvoiceDetailDTOS = new ArrayList<>();

        list.stream().forEach(item->{
            if(objectCheckIsNull(item)){
                cwFinanceInvoiceDetailDTOS.add(item);
            }
        });

        return cwFinanceInvoiceDetailDTOS;
    }

    /**
     * 根据项目id查询项目关联发票
     * @param projectId
     * @param cwFinanceInvoiceDTO
     * @return
     * @throws Exception
     */
    @GetMapping("getByIds")
    @ApiOperation(value = "根据项目id查询项目关联发票")
    public ResponseEntity<List<CwFinanceInvoiceDTO>> getByIds(String projectId,CwFinanceInvoiceDTO cwFinanceInvoiceDTO) throws Exception {
        List<CwFinanceInvoiceDTO> cwFinanceDTO = cwFinanceInvoiceService.getByIds(projectId, cwFinanceInvoiceDTO);
        return ResponseEntity.ok(cwFinanceDTO);
    }

    /**
     * 根据项目id查询项目关联发票(用于项目登记修改)
     * @param projectId
     * @param cwFinanceInvoiceDTO
     * @return
     * @throws Exception
     */
    @GetMapping("getByIds2")
    @ApiOperation(value = "根据项目id查询项目关联发票")
    public ResponseEntity<List<CwFinanceInvoiceDTO>> getByIds2(String projectId,CwFinanceInvoiceDTO cwFinanceInvoiceDTO) throws Exception {
        List<CwFinanceInvoiceDTO> cwFinanceDTO = cwFinanceInvoiceService.getByIds2(projectId, cwFinanceInvoiceDTO);
        return ResponseEntity.ok(cwFinanceDTO);
    }

    /**
     * 根据合同id查询项目关联发票
     * @param contractId
     * @param cwFinanceInvoiceDTO
     * @return
     * @throws Exception
     */
    @GetMapping("getByContractId")
    @ApiOperation(value = "根据合同id查询项目关联发票")
    public ResponseEntity<List<CwFinanceInvoiceDTO>> getByContractId(String contractId,CwFinanceInvoiceDTO cwFinanceInvoiceDTO) throws Exception {
        List<CwFinanceInvoiceDTO> cwFinanceDTO = cwFinanceInvoiceService.getByContractId(contractId, cwFinanceInvoiceDTO);
        return ResponseEntity.ok(cwFinanceDTO);
    }

    /**
     * 根据客户id查询项目关联发票
     * @param clientId
     * @param cwFinanceInvoiceDTO
     * @return
     * @throws Exception
     */
    @GetMapping("getIdByClientId")
    @ApiOperation(value = "根据客户id查询项目关联发票")
    public ResponseEntity<List<CwFinanceInvoiceDTO>> getIdByClientId(String clientId,CwFinanceInvoiceDTO cwFinanceInvoiceDTO) throws Exception {
        List<CwFinanceInvoiceDTO> cwFinanceDTO = cwFinanceInvoiceService.getIdByClientId(clientId, cwFinanceInvoiceDTO);
        return ResponseEntity.ok(cwFinanceDTO);
    }

    @ApiLog(value = "导出发票数据", type = LogTypeEnum.EXPORT)
    @GetMapping("export")
    //@PreAuthorize ("hasAuthority('cw_finance:invoice:export')")
    @ApiOperation(value = "导出发票数据")
    public void exportFile(CwFinanceInvoiceDTO cwFinanceInvoiceDTO, Page <CwFinanceInvoiceDTO> page, ExcelOptions options, HttpServletResponse response) throws Exception {
        String fileName = options.getFilename();
        String sheetName = options.getSheetName();
        List<CwFinanceInvoiceDTO> result = new ArrayList<>();
        if ( ExportMode.current.equals ( options.getMode() ) ) {
            result = cwFinanceInvoiceService.findList (page,cwFinanceInvoiceDTO,"export").getRecords();
        } else if (ExportMode.selected.equals ( options.getMode() )) {
            result = cwFinanceInvoiceService.findList (page,cwFinanceInvoiceDTO,"export").getRecords().stream ( ).filter ( item ->
                    options.getSelectIds ( ).contains ( item.getId ( ) )
            ).collect ( Collectors.toList ( ) );
        } else {
            page.setSize (-1);
            page.setCurrent (0);
            result = cwFinanceInvoiceService.findList (page,cwFinanceInvoiceDTO,"export").getRecords();
        }
        //对导出数据进行处理
        List<CwFinanceInvoiceDTO> resultList = cwFinanceInvoiceService.disposeExportList(result);


        //获取字典数据
        String cwWorkClientReportTypeDatas = SpringUtil.getBean ( IDictApi.class ).getDictListMapByDict ("cw_work_client_report_type");
        Map<String,Object> cwWorkClientReportTypeValueDTOs = JSON.parseObject(cwWorkClientReportTypeDatas, new TypeReference<Map<String,Object>>() {});

        String projectClassificationDatas = SpringUtil.getBean ( IDictApi.class ).getDictListMapByDict ("project_classification");
        Map<String,Object> projectClassificationValueDTOs = JSON.parseObject(projectClassificationDatas, new TypeReference<Map<String,Object>>() {});

        String invoiceBillingContentDatas = SpringUtil.getBean ( IDictApi.class ).getDictListMapByDict ("invoice_billing_content");
        Map<String,Object> invoiceBillingContentValueDTOs = JSON.parseObject(invoiceBillingContentDatas, new TypeReference<Map<String,Object>>() {});

        String invoiceTypeDatas = SpringUtil.getBean ( IDictApi.class ).getDictListMapByDict ("invoice_type");
        Map<String,Object> invoiceTypeValueDTOs = JSON.parseObject(invoiceTypeDatas, new TypeReference<Map<String,Object>>() {});

        String invoiceStatusDatas = SpringUtil.getBean ( IDictApi.class ).getDictListMapByDict ("invoice_status");
        Map<String,Object> invoiceStatusValueDTOs = JSON.parseObject(invoiceStatusDatas, new TypeReference<Map<String,Object>>() {});

        for (CwFinanceInvoiceDTO info : resultList) {
            //处理开票类型
            String billingType = info.getBillingType();
            if(StringUtils.isNotBlank(billingType)){
                switch (billingType){
                    case "1":
                        info.setBillingType("企业开票");
                        break;
                    case "2":
                        info.setBillingType("个人开票");
                        info.setBillingWorkplaceReal(info.getName());
                        break;
                    default:
                        info.setBillingType("");
                        break;
                }
            }


            if(StringUtils.isNotBlank(info.getReportType())){
                for (String key : cwWorkClientReportTypeValueDTOs.keySet()) {
                    if(info.getReportType().equals(key)){
                        info.setReportType(String.valueOf(cwWorkClientReportTypeValueDTOs.get(key)));
                        break;
                    }
                }
            }
            if(StringUtils.isNotBlank(info.getProjectClassification())){
                for (String key : projectClassificationValueDTOs.keySet()) {
                    if(info.getProjectClassification().equals(key)){
                        info.setProjectClassification(String.valueOf(projectClassificationValueDTOs.get(key)));
                        break;
                    }
                }
            }
            if(StringUtils.isNotBlank(info.getBillingContent())){
                for (String key : invoiceBillingContentValueDTOs.keySet()) {
                    if(info.getBillingContent().equals(key)){
                        info.setBillingContent(String.valueOf(invoiceBillingContentValueDTOs.get(key)));
                        break;
                    }
                }
            }
            if(StringUtils.isNotBlank(info.getType())){
                for (String key : invoiceTypeValueDTOs.keySet()) {
                    if(info.getType().equals(key)){
                        info.setType(String.valueOf(invoiceTypeValueDTOs.get(key)));
                        break;
                    }
                }
            }
            if(StringUtils.isNotBlank(info.getStatus())){
                for (String key : invoiceStatusValueDTOs.keySet()) {
                    if(info.getStatus().equals(key)){
                        info.setStatus(String.valueOf(invoiceStatusValueDTOs.get(key)));
                        break;
                    }
                }
            }

            if(StringUtils.isNotBlank(info.getReceivablesStatus())){
                switch (info.getReceivablesStatus()){
                    case "1":
                        info.setReceivablesStatus("是");
                        break;
                    case "0":
                        info.setReceivablesStatus("否");
                        break;
                    default:
                        info.setReceivablesStatus("");
                        break;
                }
            }else{
                info.setReceivablesStatus("");
            }

            if(StringUtils.isNotBlank(info.getIsPreInvoice())){
                switch (info.getIsPreInvoice()){
                    case "1":
                        info.setIsPreInvoice("是");
                        break;
                    case "0":
                        info.setIsPreInvoice("否");
                        break;
                    default:
                        info.setIsPreInvoice("");
                        break;
                }
            }else{
                info.setIsPreInvoice("");
            }

            if(StringUtils.isNotBlank(info.getIsCompleteInvoice())){
                switch (info.getIsCompleteInvoice()){
                    case "1":
                    case "2":
                        info.setIsCompleteInvoice("是");
                        break;
                    case "0":
                        info.setIsCompleteInvoice("否");
                        break;
                    default:
                        info.setIsCompleteInvoice("");
                        break;
                }
            }else{
                info.setIsCompleteInvoice("");
            }

        }
        EasyPoiUtil.exportExcel ( resultList, sheetName,  sheetName, CwFinanceInvoiceDTO.class, fileName, response );

    }

    public static boolean objectCheckIsNull(Object object) {
        boolean flag = false; //定义返回结果，默认为true

        if (Objects.isNull(object)) {
            flag = false;
        } else {
            Class clazz = (Class) object.getClass(); // 得到类对象
            Field fields[] = clazz.getDeclaredFields(); // 得到所有属性
            for (Field field : fields) {
                if("serialVersionUID".equals(field.getName()) || "BIZ_CODE".equalsIgnoreCase(field.getName())){
                    continue;
                }
                field.setAccessible(true);
                Object fieldValue = null;
                try {
                    fieldValue = field.get(object); //得到属性值
                    Type fieldType = field.getGenericType();//得到属性类型
                    String fieldName = field.getName(); // 得到属性名
                    log.info("属性类型：" + fieldType + ",属性名：" + fieldName + ",属性值：" + fieldValue);
                } catch (IllegalArgumentException e) {
                    log.error(e.getMessage(), e);
                } catch (IllegalAccessException e) {
                    log.error(e.getMessage(), e);
                }
                if (fieldValue != null && fieldValue != "") {  //只要有一个属性值不为null 就返回false 表示对象不为null
                    flag = true;
                    break;
                }
            }
        }

        return flag;
    }

    /**
     * 根据项目id查询发票信息
     * @param cwFinanceInvoiceDTO
     * @param page
     * @return
     * @throws Exception
     */
    @ApiLog("根据项目id查询发票信息")
    @GetMapping("listByProgramId")
    public ResponseEntity<IPage<CwFinanceInvoiceDTO>> listByProgramId(CwFinanceInvoiceDTO cwFinanceInvoiceDTO, Page<CwFinanceInvoiceDTO> page) throws Exception {
        IPage<CwFinanceInvoiceDTO> result = new Page<CwFinanceInvoiceDTO>();
        result = cwFinanceInvoiceService.listByProgramId (page, cwFinanceInvoiceDTO);
        return ResponseEntity.ok(result);
    }


    /**
     * 根据发票编号查询是否与预开票项目下的报告完成关联
     */
    @ApiLog("根据发票编号查询是否与预开票项目下的报告完成关联")
    @GetMapping("getByNo")
    public Boolean getByNo(String no){
        boolean data = cwFinanceInvoiceService.getByNo(no);
        return data;
    }


    /**
     * 查询开票时间距今超过1个月的开票数据
     */
    @ApiLog("查询开票时间距今超过1个月的开票数据")
    @GetMapping("getExceedCwFinance")
    public String getExceedCwFinance(){
        List<CwFinanceInvoiceDTO> invoiceList = cwFinanceInvoiceService.getExceedCwFinance();
        return JSON.toJSONString(invoiceList);
    }



    /**
     * 下载发票导入模板
     *
     * @param response
     * @return
     */
    @GetMapping("/importFinance/template")
    @ApiOperation(value = "下载模板")
    public void importFinanceTemplate(HttpServletResponse response, HttpServletRequest request) {
        try {
            InputStream inputStream = this.getClass().getResourceAsStream("/dot/发票导入模板.xlsx");
            //强制下载不打开
            response.setContentType("application/force-download");
            OutputStream out = response.getOutputStream();
            //使用URLEncoder来防止文件名乱码或者读取错误
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("finance_invoice_template.xlsx", "UTF-8"));
            int b = 0;
            byte[] buffer = new byte[1000000];
            while (b != -1) {
                b = inputStream.read(buffer);
                if (b != -1) out.write(buffer, 0, b);
            }
            inputStream.close();
            out.close();
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }




    /**
     * 导入发票数据
     *
     * @return
     */
    @DemoMode
    @PostMapping("/importFinance")
    @ApiLog(value = "导入发票数据excel", type = LogTypeEnum.IMPORT)
    public ResponseEntity importFinance(MultipartFile file, HttpServletRequest request) throws IOException {

        ArrayList<CwFinanceImportDTO> arrayList = new ArrayList<>();
        HashMap<String,String> hashMap = new HashMap<>();

        List<CwFinanceImportDTO> listA = new ArrayList<>();
        //获取sheet
        listA = EasyPoiUtil.importExcel(file, 1, 1, CwFinanceImportDTO.class);
        //去除excel中的空行
        listA = getExList(listA);
        //去除示例行
        listA.removeIf(item -> {
            String number = (item).getReportNo();
            return number != null && number.contains("例");
        });
        //导入前检测数据
        String resultA = cwFinanceInvoiceService.importFinance(listA, arrayList, hashMap);
        if(StringUtils.isNotBlank(resultA)){
            //有返回值，说明导入的数据不正确。向用户抛提示
            return ResponseEntity.badRequest().body  (resultA);
        }

        return ResponseEntity.ok("导入成功");
    }

    /**
     * 去除excel中的空行
     * @param list
     * @return
     */
    public ArrayList<CwFinanceImportDTO> getExList(List<CwFinanceImportDTO> list){

        ArrayList<CwFinanceImportDTO> cwFinanceImportDTOS = new ArrayList<>();

        list.stream().forEach(item->{
            if(objectCheckIsNull(item)){
                cwFinanceImportDTOS.add(item);
            }
        });

        return cwFinanceImportDTOS;
    }









}
