package com.jeeplus.centrecareful.approvalInfo.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.google.common.collect.Lists;
import com.jeeplus.centrecareful.approvalInfo.domain.ZSProgramProjectListInfo;
import com.jeeplus.centrecareful.approvalInfo.domain.ZsReimbursementFileSupplement;
import com.jeeplus.centrecareful.approvalInfo.domain.ZsReimbursementInfo;
import com.jeeplus.centrecareful.approvalInfo.domain.ZsReimbursementInfoUpHi;
import com.jeeplus.centrecareful.approvalInfo.service.ZsReimbursementInfoService;
import com.jeeplus.centrecareful.approvalInfo.service.dto.*;
import com.jeeplus.centrecareful.approvalInfo.util.ZSEasyPoiUtil;
import com.jeeplus.common.excel.ExcelOptions;
import com.jeeplus.common.excel.ExportMode;
import com.jeeplus.common.utils.ResponseUtil;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.logging.annotation.ApiLog;
import com.jeeplus.logging.constant.enums.LogTypeEnum;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.IDictApi;
import com.jeeplus.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

import static com.mysql.cj.util.TimeUtil.DATE_FORMATTER;

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

    @Resource
    private ZsReimbursementInfoService service;

    @Resource
    private IFlowableApi flowTaskService;

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

    /**
     * 列表查询
     * @param dto/reimbursementApproval/type/bxList
     * @return
     */
    @ApiOperation(value = "列表查询")
    @GetMapping("/list")
    public ResponseEntity<IPage<ZsRetureListDto>> list(Page<ZsRetureListDto> page, ZsQueryListDto dto) throws Exception{
        IPage<ZsRetureListDto> iPage = service.list(page, dto,false);
        iPage.getRecords().stream().forEach(i -> {
            if (StringUtils.isNotBlank(i.getProcInsId()) && StringUtils.isNotBlank(i.getTaskId())) {
                i.setAuditUserIds(flowTaskService.getTaskAuditUsers(i.getTaskId()));  // 获取数据审核人
                String currentTaskName = flowTaskService.getCurrentTaskName(i.getProcInsId());
                if (i.getType().equals("2") && StringUtils.isNotBlank(currentTaskName) && !currentTaskName.contains("综合管理部主任") && !currentTaskName.contains("部门主任")){
                    i.setApplyFile(true);
                }
            }

            //文件补充
            if (org.apache.commons.lang3.StringUtils.isNotBlank(i.getTaskIdFile()) && org.apache.commons.lang3.StringUtils.isNotBlank(i.getFileStatus())) {
                if ("2".equals(i.getFileStatus()) || "4".equals(i.getFileStatus())) { // “审核中”的数据要获取数据审核人
                    i.setAuditFileUserIds(flowTaskService.getTaskAuditUsers(i.getTaskIdFile()));  // 获取数据审核人
                }
            }
        });
        return ResponseEntity.ok(iPage);
    }

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

    /**
     * 新增/修改
     * @param dto
     * @return
     */
    @ApiOperation(value = "新增、修改")
    @PostMapping("/save")
    public ResponseEntity<String> save(@RequestBody ZsSaveInfoDto dto) throws Exception{
        ZsReimbursementInfo s = service.save(dto);
        return ResponseUtil.newInstance().add("businessTable", "zs_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<ZsSaveInfoDto> findById(@RequestParam String id) throws Exception{
        ZsSaveInfoDto 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 ZsRetureListDto dto) {
        service.updateStatusById(dto);
    }

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



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

        if(result.size()>0){
            //获取字典数据
            String statusDatas = SpringUtil.getBean ( IDictApi.class ).getDictListMapByDict ("status");
            String newVersionReimbursementDate = SpringUtil.getBean(IDictApi.class).getDictLabel("1", "new_version_reimbursement_date", null);
            Map<String,Object> statusValueDTOs = JSON.parseObject(statusDatas, new TypeReference<Map<String,Object>>() {});

            String cwReimbursementSourceTypeDatas = SpringUtil.getBean ( IDictApi.class ).getDictListMapByDict ("zs_cw_reimbursement_source_type");
            Map<String,Object> cwReimbursementSourceTypeValueDTOs = JSON.parseObject(cwReimbursementSourceTypeDatas, new TypeReference<Map<String,Object>>() {});

            String paymentStatusDatas = SpringUtil.getBean ( IDictApi.class ).getDictListMapByDict ("payment_status");
            Map<String,Object> paymentStatusValueDTOs = JSON.parseObject(paymentStatusDatas, new TypeReference<Map<String,Object>>() {});

            for (ZsRetureListDto info : result) {

                if(StringUtils.isNotBlank(info.getType())){
                    for (String key : statusValueDTOs.keySet()) {
                        if(info.getType().equals(key)){
                            info.setType(String.valueOf(statusValueDTOs.get(key)));
                            break;
                        }
                    }
                }
                if(StringUtils.isNotBlank(info.getSourceType())){
                    for (String key : cwReimbursementSourceTypeValueDTOs.keySet()) {
                        if(info.getSourceType().equals(key)){
                            info.setSourceType(String.valueOf(cwReimbursementSourceTypeValueDTOs.get(key)));
                            break;
                        }
                    }
                }
                if(StringUtils.isNotBlank(info.getPaymentStatus())){
                    for (String key : paymentStatusValueDTOs.keySet()) {
                        if(info.getPaymentStatus().equals(key)){
                            info.setPaymentStatus(String.valueOf(paymentStatusValueDTOs.get(key)));
                            break;
                        }
                    }
                }else {
                    info.setPaymentStatus("未付款");
                }

                //处理新旧版本报销金额展示
                boolean newVersion = isNewVersion(info.getApprovalTime(), newVersionReimbursementDate);
                if(!newVersion){
                    info.setNumberCount(info.getNumber().toString());
                }
            }
        }
        ZSEasyPoiUtil.exportExcel ( result, sheetName,  sheetName, ZsRetureListDto.class, fileName, response );

    }

    /**
     * 判断是否为新版本。
     *
     * 规则：
     * approvalTime 等于或晚于 newStartDate，返回 true；
     * approvalTime 早于 newStartDate，返回 false。
     */
    public static boolean isNewVersion(Date approvalTime, String newStartDate) {
        if (approvalTime == null
                || newStartDate == null
                || newStartDate.trim().isEmpty()) {
            return true;
        }

        String compareResult = compareDate(approvalTime, newStartDate);

        return "same".equals(compareResult)
                || "after".equals(compareResult);
    }

    /**
     * 按“天”比较日期，忽略时、分、秒。
     *
     * @param date1    Date 类型日期
     * @param date2Str yyyy-MM-dd 格式日期字符串
     * @return before、after、same
     */
    public static String compareDate(Date date1, String date2Str) {
        if (date1 == null) {
            throw new IllegalArgumentException("date1 不能为空");
        }

        if (date2Str == null
                || date2Str.trim().isEmpty()
                || "-".equals(date2Str.trim())) {
            throw new IllegalArgumentException("date2Str 不能为空");
        }

        LocalDate d1 = date1.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();

        LocalDate d2 = LocalDate.parse(
                date2Str.trim(),
                DATE_FORMATTER
        );

        if (d1.isBefore(d2)) {
            return "before";
        }

        if (d1.isAfter(d2)) {
            return "after";
        }

        return "same";
    }

    @ApiLog(value = "中审电子发票报销数据")
    @GetMapping("exportInvoiceReimbursementFile")
    @ApiOperation(value = "中审电子发票报销数据")
    public void exportInvoiceReimbursementFile(ZsQueryListDto cwDTO, Page <ZsRetureListDto> page, ExcelOptions options, HttpServletResponse response) throws Exception {
        boolean isExport = true;
        String fileName = "中审数电发票报销数据表";
        String sheetName = "中审数电发票报销列表";
        List<ZsRetureListDto> result = new ArrayList<>();
        if (ExportMode.current.equals ( options.getMode() ) ) {
            result = service.list (page,cwDTO,isExport).getRecords();
        } else if (com.jeeplus.common.excel.ExportMode.selected.equals ( options.getMode() )) {
            result = service.list (page,cwDTO,isExport).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,isExport).getRecords();
        }
        List<String> idList = Lists.newArrayList();
        for (ZsRetureListDto listDto : result) {
            if("2".equals(listDto.getType()) || "5".equals(listDto.getType())){
                idList.add(listDto.getId());
            }
        }
        List<ZsReimbursementAmountInfoDTO> invoiceReimbursementAmountList = Lists.newArrayList();
        if(idList.size()>0){
            invoiceReimbursementAmountList = service.getInvoiceReimbursementAmountList(idList);
        }
        for (int i = 1;i <=invoiceReimbursementAmountList.size();i ++){
            ZsReimbursementAmountInfoDTO reimbursementAmountInfoDTO = invoiceReimbursementAmountList.get(i - 1);
            reimbursementAmountInfoDTO.setSerialNumber(i);
        }

        ZSEasyPoiUtil.exportExcel ( invoiceReimbursementAmountList, sheetName,  sheetName, ZsReimbursementAmountInfoDTO.class, fileName, response );

    }



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

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

    /**
     * 提交时根据发票号查询是否已经或正在报销
     * @return
     */
    @ApiLog(value = "根据发票号查询是否已经或正在报销")
    @GetMapping("getEffectiveDataByNumbers")
    @ApiOperation(value = "根据发票号查询是否已经或正在报销")
    public Map<String,Object> getEffectiveDataByNumbers(String invoiceNumber,String id){
        Map map = new HashMap();
        map.put("success",true);
        map.put("message","数电发票正常");
        if(org.apache.commons.lang3.StringUtils.isNotBlank(invoiceNumber)){
            String[] array = invoiceNumber.split(",");
            // 将数组转换为 List
            List<String> numberList = Arrays.asList(array);
            Set<String> set = new HashSet<>();
            if(numberList.size()>0){
                List<String> repetitionMessageList = service.getEffectiveDataByNumbers(numberList,id);
                for (String vatTax : repetitionMessageList) {
                    set.add(vatTax);
                }
            }
            ArrayList<String> strings = Lists.newArrayList(set);
            String result = String.join(",", strings);
            if(result.length()>0){
                map.put("success",false);
                map.put("message","数电发票编号为：" + result + "已经发起或已完成报销，无法重复报销");
            }

        }
        return map;
    }


    /**
     * 提交时根据发票号查询是否已经或正在报销
     * @return
     */
    @ApiLog(value = "根据发票号查询是否已经或正在报销")
    @PostMapping("getEffectiveDataByNumbers2")
    @ApiOperation(value = "根据发票号查询是否已经或正在报销")
    public Map<String,Object> getEffectiveDataByNumbers2(@RequestBody ZsQueryListDto dto){
        String invoiceNumber = dto.getFinanceNumber();
        String id = dto.getId();
        Map map = new HashMap();
        map.put("success",true);
        map.put("message","数电发票正常");
        if(org.apache.commons.lang3.StringUtils.isNotBlank(invoiceNumber)){
            String[] array = invoiceNumber.split(",");
            // 将数组转换为 List
            List<String> numberList = Arrays.asList(array);
            Set<String> set = new HashSet<>();
            if(numberList.size()>0){
                List<String> repetitionMessageList = service.getEffectiveDataByNumbers2(numberList, id);
                for (String vatTax : repetitionMessageList) {
                    set.add(vatTax);
                }
            }
            ArrayList<String> strings = Lists.newArrayList(set);
            String result = String.join(",", strings);
            if(result.length()>0){
                map.put("success",false);
                map.put("message","数电发票编号为：" + result + "已经发起或已完成报销，无法重复报销");
            }

        }
        return map;
    }


    /**
     * 根据发票号查询是否已经或正在报销
     * @return
     */
    @ApiLog(value = "根据报销id和发票编号删除数据记录")
    @PostMapping("deleteByIdAndNumber")
    @ApiOperation(value = "根据报销id和发票编号删除数据记录")
    public Map<String,Object> deleteByIdAndNumber(String id,String invoiceNumber){
        Map map = new HashMap();
        if(StringUtils.isBlank(invoiceNumber)){
            map.put("success",false);
            map.put("message","发票号不可为空");
        }else if(StringUtils.isBlank(id)){
            map.put("success",false);
            map.put("message","报销信息未选择");
        }else{
            Integer count = service.deleteByIdAndNumber(invoiceNumber,id);
            map.put("success",true);
        }
        return map;
    }

    /**
     * 查询有无历史数据
     * @param id
     * @return
     */
    @ApiOperation(value = "查询有无历史数据")
    @GetMapping("/findHistory")
    public ResponseEntity<List<ZsReimbursementInfoUpHi>> findHistory(@RequestParam String id) throws Exception{
        List<ZsReimbursementInfoUpHi> list=service.findHistory(id);
        return ResponseEntity.ok(list);
    }

    /**
     * 根据id查询历史数据
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id查询历史数据")
    @GetMapping("/findHiById")
    public ResponseEntity<ZsSaveInfoDto> findHiById(@RequestParam String id) throws Exception{
        ZsSaveInfoDto list=service.findHiById(id);
        return ResponseEntity.ok(list);
    }

    /**
     * 修改付款状态
     * @param
     * @return
     */
    @ApiOperation(value = "修改付款状态")
    @PostMapping("/updatePaymentStatus")
    public String updatePaymentStatus(@RequestBody ZsRetureListDto dto) {
        String data=service.updatePaymentStatus(dto.getId(),dto.getPaymentStatus());
        return data;
    }

    /**
     * 查询文件补充
     * @param id
     * @return
     */
    @ApiOperation(value = "查询文件补充")
    @GetMapping("/findFileById")
    public ResponseEntity<ZsSaveInfoDto> findFileById(@RequestParam String id) throws Exception{
        ZsSaveInfoDto dto = service.findFileById(id);
        return ResponseEntity.ok(dto);
    }

    /**
     * 新增/修改 文件补充
     * @param dto
     * @return
     */
    @ApiOperation(value = "新增、修改 文件补充")
    @PostMapping("/saveFile")
    public ResponseEntity<String> saveFile(@RequestBody ZsSaveInfoDto dto) throws Exception{
        ZsReimbursementFileSupplement s = service.saveFile(dto);
        return ResponseUtil.newInstance().add("businessTable", "zs_reimbursement_file_supplement")
                .add("businessId", s.getId())
                .add("no", s.getNo())
                .add("name",s.getName())
                .ok ("操作成功");
    }

    /**
     * 根据id修改文件补充状态status
     */
    @ApiOperation(value = "根据id修改文件补充状态status")
    @PostMapping(value = "updateFileStatusById")
    public void updateFileStatusById(@RequestBody ZsRetureListDto dto) {
        service.updateFileStatusById(dto);
    }



    /**
     * 修改数电发票报销数据(对老数据进行调整)
     */
    @ApiOperation(value = "修改数电发票报销数据(对老数据进行调整)")
    @GetMapping(value = "updateOldData")
    public void updateOldData(){
        service.updateOldData();
    }


    /**
     * 查询文件补充(最新一条)
     * @param id
     * @return
     */
    @ApiOperation(value = "查询文件补充")
    @GetMapping("/findFileByReimId")
    public ResponseEntity<ZsReimbursementFileSupplement> findFileByReimId(@RequestParam String id) throws Exception{
        ZsReimbursementFileSupplement dto = service.findFileByReimId(id);
        return ResponseEntity.ok(dto);
    }

    @ApiOperation(value = "根据流程id获取报销创建人id")
    @GetMapping(value = "/getReimbursementCreateUserIdByProcessInstanceId")
    public String getReimbursementCreateUserIdByProcessInstanceId(@RequestParam("id") String id) {
        String currentUserId = service.getReimbursementCreateUserIdByProcessInstanceId(id);
        return currentUserId;
    }


}
