package com.jeeplus.test.cw.invoice.controller;

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.aop.logging.annotation.ApiLog;
import com.jeeplus.common.utils.ResponseUtil;
import com.jeeplus.core.excel.ExcelOptions;
import com.jeeplus.core.excel.ExportMode;
import com.jeeplus.core.excel.utils.EasyPoiUtil;
import com.jeeplus.flowable.service.FlowTaskService;
import com.jeeplus.sys.constant.enums.LogTypeEnum;
import com.jeeplus.sys.utils.DictUtils;
import com.jeeplus.sys.utils.StringUtils;
import com.jeeplus.test.cw.invoice.domain.CwFinanceInvoice;
import com.jeeplus.test.cw.invoice.service.CwFinanceInvoiceService;
import com.jeeplus.test.cw.invoice.service.dto.CwFinanceDTO;
import com.jeeplus.test.cw.invoice.service.dto.CwFinanceInvoiceDTO;
import com.jeeplus.test.cw.invoice.service.dto.CwFinanceInvoiceDetailDTO;
import com.jeeplus.test.cw.projectRecords.service.dto.CwProjectRecordsDTO;
import com.jeeplus.test.cw.reimbursementApproval.approvalInfo.service.dto.QueryListDto;
import com.jeeplus.test.cw.reimbursementApproval.approvalInfo.service.dto.RetureListDto;
import com.jeeplus.test.zs.zsReimbursement.approvalInfo.service.dto.ZsRetureListDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import static com.jeeplus.test.jobPosion.utils.BeanUtils.objectCheckIsNull;

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

    @Resource
    private CwFinanceInvoiceService cwFinanceInvoiceService;

    @Resource
    private FlowTaskService 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);
        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()));  // 获取数据审核人
                }
            }
        });
        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("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 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).getRecords();
        } else if (ExportMode.selected.equals ( options.getMode() )) {
            result = cwFinanceInvoiceService.findList (page,cwFinanceInvoiceDTO).getRecords().stream ( ).filter ( item ->
                    options.getSelectIds ( ).contains ( item.getId ( ) )
            ).collect ( Collectors.toList ( ) );
        } else {
            page.setSize (-1);
            page.setCurrent (0);
            result = cwFinanceInvoiceService.findList (page,cwFinanceInvoiceDTO).getRecords();
        }
        EasyPoiUtil.exportExcel ( result, sheetName,  sheetName, CwFinanceInvoiceDTO.class, fileName, response );

    }
}
