package cn.ezhizao.project.business.reportTax.controller;

import cn.ezhizao.common.exception.ServiceException;
import cn.ezhizao.common.utils.poi.ExcelUtil;
import cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
import cn.ezhizao.framework.lock.DistributionLock;
import cn.ezhizao.framework.lock.LockKey;
import cn.ezhizao.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.framework.web.page.TableDataInfo;
import cn.ezhizao.project.business.company.domain.BizCompany;
import cn.ezhizao.project.business.company.service.IBizCompanyService;
import cn.ezhizao.project.business.deduction.domain.BizDeduction;
import cn.ezhizao.project.business.deduction.service.IBizDeductionService;
import cn.ezhizao.project.business.entrust.domain.BizEntrust;
import cn.ezhizao.project.business.entrust.service.IBizEntrustService;
import cn.ezhizao.project.business.finance.IndividualIncomeTax.domain.BizFinancialIndividualIncomeTaxDetail;
import cn.ezhizao.project.business.finance.IndividualIncomeTax.service.IBizFinancialIndividualIncomeTaxDetailService;
import cn.ezhizao.project.business.finance.IndividualIncomeTaxIsZero.domain.BizFinancialIndividualIncomeTaxDetailIsZero;
import cn.ezhizao.project.business.finance.IndividualIncomeTaxIsZero.service.IBizFinancialIndividualIncomeTaxDetailIsZeroService;
import cn.ezhizao.project.business.financialBase.domain.BizFinancialMerge;
import cn.ezhizao.project.business.financialBase.service.IBizFinancialMergeService;
import cn.ezhizao.project.business.history.domain.BizHistory;
import cn.ezhizao.project.business.history.service.IBizHistoryService;
import cn.ezhizao.project.business.reportTax.domain.BizFinancialReportTaxNonZero;
import cn.ezhizao.project.business.reportTax.domain.BizFinancialReportTaxDetailNonZero;
import cn.ezhizao.project.business.reportTax.domain.BizFinancialReportTaxDetailReportNonZero;
import cn.ezhizao.project.business.reportTax.service.IBizFinancialReportTaxDetailNonZeroService;
import cn.ezhizao.project.business.reportTax.service.IBizFinancialReportTaxDetailReportNonZeroService;
import cn.ezhizao.project.business.reportTax.service.IBizFinancialReportTaxNonZeroService;
import cn.ezhizao.project.business.reportTaxIsZero.domain.BizFinancialReportTax;
import cn.ezhizao.project.business.reportTaxIsZero.domain.BizFinancialReportTaxDetail;
import cn.ezhizao.project.business.reportTaxIsZero.service.IBizFinancialReportTaxDetailReportService;
import cn.ezhizao.project.business.reportTaxIsZero.service.IBizFinancialReportTaxDetailService;
import cn.ezhizao.project.business.reportTaxIsZero.service.IBizFinancialReportTaxService;
import cn.ezhizao.project.system.domain.SysFileStorage;
import cn.ezhizao.project.system.domain.SysUser;
import cn.ezhizao.project.system.mapper.SysUserMapper;
import cn.ezhizao.project.system.service.ISysFileStorageService;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@Api(tags = "员工 数据接口")
@RequestMapping(value = "/business/financialReportTaxNonZero")
public class BizFinancialReportTaxNonZeroController extends BaseController {

    @Resource
    IBizFinancialReportTaxNonZeroService financialReportTaxService;
    @Resource
    IBizFinancialReportTaxService financialReportService;
    @Resource
    IBizFinancialReportTaxDetailNonZeroService financialReportTaxDetailService;

    @Resource
    IBizFinancialReportTaxDetailService financialReportTaxDetaiIsZerolService;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    IBizFinancialMergeService financialMergeService;
    @Resource
    IBizFinancialIndividualIncomeTaxDetailIsZeroService financialIndividualIncomeTaxDetailService;
    @Resource
    IBizFinancialReportTaxDetailReportNonZeroService financialReportTaxDetailReportService;
    @Resource
    IBizFinancialReportTaxDetailReportService financialReportTaxDetailReportIsZeroService;

    @Resource
    IBizFinancialIndividualIncomeTaxDetailService financialIndividualIncomeTaxDetailIsZeroService;

    @Resource
    ISysFileStorageService fileStorageService;
    @Resource
    IBizDeductionService deductionService;
    @Resource
    IBizCompanyService companyService;
    @Resource
    IBizHistoryService bizHistoryService;
    @Resource
    private IBizEntrustService bizEntrustService;


    @ApiOperation(value = "查询FinancialReceiveTicket", notes = "根据id查询Channel")
    @GetMapping("/getById/{id}")
    @ResponseBody
    public AjaxResult getById(@PathVariable Long id) {
        AjaxResult result;
//        Map<String, Object> map = new HashMap<>(16);
        try {
            BizFinancialReportTaxNonZero financialReportTax = financialReportTaxService.getById(id);
            result = success(financialReportTax);
        } catch (Exception ex) {
            result = error(ex.getMessage());
        }
        return result;

    }

    @ApiOperation("根据id获得明细")
    @PreAuthorize("@ss.hasPermi('business:financialReportTaxNonZero:query')")
    @GetMapping("/getDetailById/{id}/{year}/{month}")
    @ResponseBody
    public AjaxResult getDetailById(@PathVariable Long id, @PathVariable("year") String year, @PathVariable("month") String month) {
        int nowYear = LocalDate.now().getYear();
        int nowMonth = LocalDate.now().getMonthValue()-1;
        String formattedMonth = String.format("%02d", nowMonth);
        BizFinancialReportTaxDetailNonZero conditions = new BizFinancialReportTaxDetailNonZero();
        conditions.setFinancialReportTaxId(id);
        conditions.setYear(year);
        conditions.setMonth(month);
        List<BizFinancialReportTaxDetailNonZero> details = financialReportTaxDetailService.getList(conditions);
        BizFinancialReportTaxDetailNonZero detail = details.isEmpty() ? null : details.get(0);
        String s1= year+month;
        String s2 = nowYear+ formattedMonth;
        if(s1.equals(s2) && detail == null){
            return success(new BizFinancialReportTaxDetail());
        }
        if (detail==null  ) {
            return error("当前月未找到数据");
        }
        Long fatherId = detail.getFinancialReportTaxId();
        Long workOrderId = financialReportService.getById(fatherId).getWorkOrderId();
        String s3 = year +"-"+ month+ "-01";
        BizEntrust one = bizEntrustService.getOne(new LambdaQueryWrapper<BizEntrust>()
                .eq(BizEntrust::getWorkOrderId, workOrderId)
                .eq(BizEntrust::getDeleted, 0)
                .eq(BizEntrust::getCurrentMonth, s3 ).orderByDesc(BizEntrust::getCreateTime).last("limit 1"));
        detail.setEntrust(one);
        return success(detail);
    }

    @ApiOperation("保存detail")
    @PreAuthorize("@ss.hasPermi('business:financialReportTaxNonZero:saveDetail')")
    @PostMapping("/saveDetail")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult saveDetail(@RequestBody BizFinancialReportTaxDetail detail) {
        String join = LockKey.join(LockKey.REPORTTAXNONZERODETAIL,detail.getFinancialReportTaxId(),detail.getYear(),detail.getMonth(),detail.getCompanyId());
        DistributionLock lock = new DistributionLock(join);
        try {
            lock.lock();
            if(null == detail.getId()){
                Long count = financialReportTaxDetaiIsZerolService
                        .lambdaQuery()
                        .eq(BizFinancialReportTaxDetail::getDeleted,0)
                        .eq(BizFinancialReportTaxDetail::getYear,detail.getYear())
                        .eq(BizFinancialReportTaxDetail::getMonth,detail.getMonth())
                        .eq(BizFinancialReportTaxDetail::getFinancialReportTaxId,detail.getFinancialReportTaxId())
                        .count();
                if(null != count && count > 0) {
                    return error("已经保存过数据，不可重复提交");
                }
            }
            detail.setVerifierTime(new Date());
            detail.setVerifierId(getUserId());
            boolean bool = financialReportTaxDetaiIsZerolService.saveOrUpdate(detail);
            Map<String, Object> conditions = new HashMap<>(1);
            conditions.put("financialReportTaxDetailId", detail.getId());
            detail.setVerifierId(getUserId());
            financialReportTaxDetailReportIsZeroService.physicallyDelete(conditions);
            detail.getReportFiles().forEach(l -> {
                l.setFinancialReportTaxId(detail.getFinancialReportTaxId());
                l.setFinancialReportTaxDetailId(detail.getId());
            });
            bool = bool && (detail.getReportFiles().isEmpty() || financialReportTaxDetailReportIsZeroService.saveBatch(detail.getReportFiles()));

            Map<String, Object> delCondition = new HashMap<>();
            delCondition.put("financialReportTaxDetailId", detail.getId());
            financialMergeService.physicallyDelete(delCondition);

            bool = bool && checkDeduction(detail);

            SysFileStorage delConditions = new SysFileStorage();
            delConditions.setMasterId(detail.getId());
            delConditions.setMasterTableName("biz_financial_report_tax_detail");
            fileStorageService.physicalDelete(delConditions);
            List<SysFileStorage> fileStorages = detail.getFiles();

            fileStorages.forEach(l -> {
                l.setMasterId(detail.getId());
                l.setMasterTableName("biz_financial_report_tax_detail");
            });
            BizHistory bizHistory = new BizHistory();
            bizHistory.setTableName("biz_financial_report_tax");
            bizHistory.setCompanyId(detail.getCompanyId());
            bizHistory.setBelongPeriod(detail.getYear() + "-" + String.format("%02d", Integer.valueOf(detail.getMonth())) );
            bizHistory.setEvent("保存");
            bizHistory.setTenantId(getTenantId());
            bizHistoryService.save(bizHistory);
            bool = bool && (fileStorages.isEmpty() || fileStorageService.saveOrUpdateBatch(fileStorages));
            return bool ? success(detail) : error();
        } catch (Exception e) {
            e.printStackTrace();
            return error("保存失败");
        } finally {
            lock.unlock();
        }
    }

    /**
     * 导出报税任务列表
     */
    @PreAuthorize("@ss.hasPermi('business:financialReportTaxNonZero:export')")
    @Log(title = "报税零申报", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizFinancialReportTaxNonZero financialReportTax) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(financialReportTax);
        List<BizFinancialReportTaxNonZero> list = financialReportTaxService.getList(financialReportTax);
        for (BizFinancialReportTaxNonZero l : list) {
            l.setCurrentPeriod(financialReportTax.getYear() + "-" + financialReportTax.getMonth());
            BizFinancialReportTaxDetailNonZero detail = new BizFinancialReportTaxDetailNonZero();
            detail.setFinancialReportTaxId(l.getId());
            detail.setYear(financialReportTax.getYear());
            detail.setMonth(financialReportTax.getMonth());
            List<BizFinancialReportTaxDetailNonZero> details = financialReportTaxDetailService.getList(detail);
            l.setZero(l.getIsZero() == 1 ? "是" : "否");
            if (details.size() >0) {
                l.setDetail(details.get(0));
                detail=details.get(0);
                SysUser sysUser = sysUserMapper.selectUserById(detail.getVerifierId());
                l.setServiceName(sysUser==null?"":sysUser.getNickName());
                switch (detail.getStatus()) {
                    case 0:
                        l.setStatusText("未开始");
                        l.setMakeOut("未填写");
                        break;
                    case 1:
                        l.setStatusText("进行中");
                        l.setMakeOut("进行中");
                        break;
                    case 3:
                        l.setStatusText("已完成");
                        l.setMakeOut("已填写");
                        break;
                    default:
                        break;
                }
            } else {
                l.setStatusText("未开始");
                l.setMakeOut("未填写");
            }

        }
        ExcelUtil<BizFinancialReportTaxNonZero> util = new ExcelUtil<BizFinancialReportTaxNonZero>(BizFinancialReportTaxNonZero.class);
        util.exportExcel(response, list, "报税非零申报数据");
    }

    /**
     * 修改报税详情
     */
    @Log(title = "报税详情", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizFinancialReportTaxDetailNonZero detail) throws NoSuchFieldException, IllegalAccessException {
        //查询文件报表文件
        List<BizFinancialReportTaxDetailReportNonZero> fileStorages = detail.getReportFiles();
        boolean bool = true;
        for (BizFinancialReportTaxDetailReportNonZero l : fileStorages) {
            bool = financialReportTaxDetailReportService.updateById(l);
            if (!bool) {
                break;
            }
        }
        return toAjax(financialReportTaxDetailService.updateById(detail) && bool);
    }

    @ApiOperation(value = "带条件List 分页查询", notes = "带条件List 分页查询")
    @PreAuthorize("@ss.hasPermi('business:financialReportTaxNonZero:list')")
    @GetMapping("/list")
    public TableDataInfo getList(BizFinancialReportTaxNonZero financialReportTax) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(financialReportTax);
        startPage();
        List<BizFinancialReportTaxNonZero> list = financialReportTaxService.getList(financialReportTax);
        if (!list.isEmpty()) {

            BizFinancialReportTaxDetailNonZero detailConditions = new BizFinancialReportTaxDetailNonZero();
            detailConditions.setMainIds(list.stream().map(BizFinancialReportTaxNonZero::getId).collect(Collectors.toList()));
            detailConditions.setYear(financialReportTax.getYear());
            detailConditions.setMonth(financialReportTax.getMonth());

            List<BizFinancialReportTaxDetailNonZero> details = financialReportTaxDetailService.getList(detailConditions);
            list.forEach(l -> {
                List<BizFinancialReportTaxDetailNonZero> lDetail = details.stream().filter(v -> v.getFinancialReportTaxId().equals(l.getId())).collect(Collectors.toList());
                l.setDetail(lDetail.isEmpty() ? null : lDetail.get(0));
            });
        }

        return getDataTable(list);
    }

    @ApiOperation(value = "带条件List 分页查询", notes = "带条件List 分页查询")
    @PostMapping("/getDetailList")
    @ResponseBody
    public TableDataInfo getDetailList(@RequestBody BizFinancialReportTaxDetailNonZero conditions) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(conditions);
        List<BizFinancialReportTaxDetailNonZero> list = financialReportTaxDetailService.getList(conditions);
        return getDataTable(list);
    }


    /**
     * 获取票据列表
     *
     * @param conditions
     * @return
     */

    @ApiOperation(value = "带条件List 分页查询", notes = "带条件List 分页查询")
    @PostMapping("/getTicketReport")
    @ResponseBody
    public TableDataInfo getTicketReport(@RequestBody BizFinancialReportTaxDetailNonZero conditions) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(conditions);
        List<BizFinancialReportTaxDetailNonZero> list = financialReportTaxDetailService.getList(conditions);
        return getDataTable(list);
    }

    @ApiOperation(value = "带条件List 分页查询", notes = "带条件List 分页查询")
    @PostMapping("/getListForYear")
    @ResponseBody
    public TableDataInfo getListForYear(@RequestBody BizFinancialReportTaxNonZero conditions) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(conditions);

        List<BizFinancialReportTaxNonZero> list = financialReportTaxService.getList(conditions);
        if (!list.isEmpty()) {
            BizFinancialReportTaxDetailNonZero detailConditions = new BizFinancialReportTaxDetailNonZero();
            detailConditions.setMainIds(list.stream().map(BizFinancialReportTaxNonZero::getId).collect(Collectors.toList()));
            detailConditions.setYear(conditions.getYear());
            List<BizFinancialReportTaxDetailNonZero> details = financialReportTaxDetailService.getList(detailConditions);
            list.forEach(l -> {
                List<BizFinancialReportTaxDetailNonZero> lDetail = details.stream().filter(v -> v.getFinancialReportTaxId().equals(l.getId())).collect(Collectors.toList());
                l.setDetails(lDetail);
            });
        }

        return getDataTable(list);
    }

    @ApiOperation(value = "删除Channel", notes = "根据id删除Channel")
    @DeleteMapping("/deleteById/{id}")
    @ResponseBody
    public AjaxResult deleteById(@PathVariable Long id) {
        try {
            if (financialReportTaxService.removeById(id)) {
                return success();
            } else {
                return error();
            }
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    @ApiOperation(value = "整体保存", notes = "整体保存")
    @PostMapping("/save")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public AjaxResult save(@RequestBody BizFinancialReportTaxNonZero financialReportTax) {
        AjaxResult result = null;
        Map<String, Object> map = new HashMap<>(16);
        try {
            boolean bool = financialReportTaxService.saveOrUpdate(financialReportTax);
            if (!bool) {
                throw new RuntimeException("保存主订单发生错误!");
            }
            map.put("id", financialReportTax.getId());
            result = success(map);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
        return result;
    }

    @ApiOperation(value = "整体保存", notes = "整体保存")
    @PostMapping("/saveFile")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public AjaxResult saveFile(@RequestBody SysFileStorage fileStorage) {
        boolean bool = fileStorageService.saveOrUpdate(fileStorage);
        return bool ? success(fileStorage) : error();
    }

    @ApiOperation(value = "零报税/取消零报税")
    @PostMapping("/setZero")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public AjaxResult setZero(@RequestBody List<BizFinancialReportTaxNonZero> financialReportTaxes) {
        List<BizFinancialReportTaxDetailNonZero> details = new ArrayList<>();
        financialReportTaxes.forEach(l -> {
            BizFinancialReportTaxDetailNonZero detail = l.getDetail();
            detail = detail.getId() == null ? detail : financialReportTaxDetailService.getById(detail.getId());
            detail.setFinancialReportTaxId(l.getId());
            detail.setCompanyId(l.getCompanyId());
            detail.setIsZero(detail.getIsZero().equals(0) ? 1 : 0);
            if (detail.getIsZero().equals(1)) {
                detail.setExcise(BigDecimal.ZERO);
                detail.setCityConstructTax(BigDecimal.ZERO);
                detail.setBusinessIncomeTax(BigDecimal.ZERO);
                detail.setAdditionsTaxOfEducation(BigDecimal.ZERO);
                detail.setCulturalConstructTax(BigDecimal.ZERO);
                detail.setIndividualIncomeTax(BigDecimal.ZERO);
                detail.setLAdditionsTaxOfEducation(BigDecimal.ZERO);
                detail.setStampTax(BigDecimal.ZERO);
                detail.setValueAddedTax(BigDecimal.ZERO);
            }
            detail.setStatus(2);
            details.add(detail);
        });
        return financialReportTaxDetailService.saveOrUpdateBatch(details) ? success() : error();
    }


    @ApiOperation("审核")
    @PostMapping("/verify")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public AjaxResult verify(@RequestBody BizFinancialReportTaxDetailNonZero detail) {
//        if(detail.getValueAddedTax())
        BigDecimal amount = detail.getValueAddedTax().add(detail.getStampTax()).add(detail.getAdditionsTaxOfEducation()).add(detail.getExcise()).add(detail.getLAdditionsTaxOfEducation()).add(detail.getBusinessIncomeTax()).add(detail.getCityConstructTax()).add(detail.getCulturalConstructTax()).add(detail.getIndividualIncomeTax());
        boolean res1 = true;
        if (amount.compareTo(BigDecimal.ZERO) > 0 && detail.getStatus().equals(3)) {
            BizDeduction deduction = new BizDeduction();
            deduction.setSourceName("报税");
            deduction.setDeductible(1);
            deduction.setSourceTableName("biz_financial_report_tax_detail");
            deduction.setAmount(amount);
            deduction.setYear(detail.getYear());
            deduction.setMonth(detail.getMonth());
            deduction.setSourceId(detail.getId());
            deduction.setCompanyId(detail.getCompanyId());
            res1 = deductionService.save(deduction);
        }
        boolean res2 = financialReportTaxDetailService.updateById(detail);
        return (res1 && res2) ? success() : error();
//        return error();
    }

    private Boolean checkDeduction01(BizFinancialReportTaxDetailNonZero detail) {
        BizFinancialReportTaxNonZero main = financialReportTaxService.getById(detail.getFinancialReportTaxId());
        // 判断当前月是否报税
        QueryWrapper<BizFinancialIndividualIncomeTaxDetailIsZero> individualIncomeTaxDetailQueryWrapper = new QueryWrapper<>();
        individualIncomeTaxDetailQueryWrapper.eq("company_id", detail.getCompanyId());
        individualIncomeTaxDetailQueryWrapper.eq("year", detail.getYear());
        individualIncomeTaxDetailQueryWrapper.eq("month", detail.getMonth());
        BizFinancialIndividualIncomeTaxDetailIsZero individualIncomeTaxDetail = financialIndividualIncomeTaxDetailService.getOne(individualIncomeTaxDetailQueryWrapper);
        if (individualIncomeTaxDetail != null && individualIncomeTaxDetail.getStatus().equals(3) && detail.getStatus().equals(3)) {
            if (individualIncomeTaxDetail.getAmount().add(detail.getSumTax() == null ? BigDecimal.ZERO : detail.getSumTax()).compareTo(BigDecimal.ZERO) > 0) {
                BizFinancialMerge financialMerge = new BizFinancialMerge();
                financialMerge.setFinancialIndividualIncomeTaxDetailId(individualIncomeTaxDetail.getId());
                financialMerge.setFinancialReportTaxDetailId(detail.getId());
                financialMerge.setType("税款");
                financialMergeService.save(financialMerge);
                BizDeduction deduction = new BizDeduction();
                deduction.setWorkOrderId(main.getId());
                deduction.setSourceName("税款");
                deduction.setDeductible(1);
                deduction.setSourceTableName("financial_merge");
                deduction.setAmount(individualIncomeTaxDetail.getAmount().add(detail.getSumTax() == null ? BigDecimal.ZERO : detail.getSumTax()));
                deduction.setYear(detail.getYear());
                deduction.setMonth(detail.getMonth());
                deduction.setSourceId(financialMerge.getId());
                deduction.setCompanyId(detail.getCompanyId());
                return deductionService.save(deduction);
            }
        }
        return true;
    }

    private Boolean checkDeduction(BizFinancialReportTaxDetail detail) {
        // 判断当前月是否报税
        // 20230915 假设未报税也插入一条税款，合并税款记录中的是否可扣款未0
        // 判断是否有一条merge
        boolean bool;

        QueryWrapper<BizFinancialIndividualIncomeTaxDetail> individualIncomeTaxDetailQueryWrapper = new QueryWrapper<>();
        individualIncomeTaxDetailQueryWrapper.eq("company_id", detail.getCompanyId());
        individualIncomeTaxDetailQueryWrapper.eq("year", detail.getYear());
        individualIncomeTaxDetailQueryWrapper.eq("month", detail.getMonth());
        individualIncomeTaxDetailQueryWrapper.eq("status", 3);
        BizFinancialIndividualIncomeTaxDetail individualIncomeTaxDetail = financialIndividualIncomeTaxDetailIsZeroService.getOne(individualIncomeTaxDetailQueryWrapper);
        List<BizFinancialMerge> financialMerges = financialMergeService.query().eq(individualIncomeTaxDetail != null, "financial_individual_income_tax_detail_id", individualIncomeTaxDetail == null ? 0L : individualIncomeTaxDetail.getId()).or().eq("financial_report_tax_detail_id", detail.getId()).list();
        List<BizDeduction> deductions;
        if (financialMerges.isEmpty()) {
            deductions = new ArrayList<>();
        } else {
            deductions = deductionService.query().in("source_id", financialMerges.stream().map(BizFinancialMerge::getId).collect(Collectors.toList())).list();
        }
        BigDecimal amount = individualIncomeTaxDetail == null ? detail.getSumTax() == null ? BigDecimal.ZERO : detail.getSumTax() : individualIncomeTaxDetail.getAmount().add(detail.getSumTax() == null ? BigDecimal.ZERO : detail.getSumTax());
        if (amount.doubleValue() > 0) {
            if (deductions.isEmpty()) {
                BizFinancialMerge financialMerge = financialMerges.isEmpty() ? new BizFinancialMerge() : financialMerges.get(0);
                financialMerge.setFinancialReportTaxDetailId(detail.getId());
                financialMerge.setFinancialIndividualIncomeTaxDetailId(individualIncomeTaxDetail == null ? 0L : individualIncomeTaxDetail.getId());
                financialMerge.setType("税款");
                bool = financialMerge.getId() == null ? financialMergeService.save(financialMerge) : financialMergeService.updateById(financialMerge);
                BizDeduction deduction = new BizDeduction();
                deduction.setDeductible(financialMerge.getFinancialIndividualIncomeTaxDetailId().equals(0L) || financialMerge.getFinancialReportTaxDetailId().equals(0L) ? 0 : 1);
                deduction.setSourceName("税款");
                deduction.setSourceTableName("financial_merge");
                deduction.setAmount(individualIncomeTaxDetail == null ? detail.getSumTax() == null ? BigDecimal.ZERO : detail.getSumTax() : individualIncomeTaxDetail.getAmount().add(detail.getSumTax() == null ? BigDecimal.ZERO : detail.getSumTax()));
                deduction.setYear(detail.getYear());
                deduction.setMonth(detail.getMonth());
                deduction.setWorkOrderId(detail.getWorkOrderId());
                deduction.setSourceId(financialMerge.getId());
                deduction.setCompanyId(detail.getCompanyId());
                BizCompany company = companyService.getById(detail.getCompanyId());
                deduction.setTenantId(company.getTenantId());
                return bool && deductionService.save(deduction);
            } else {
                BizFinancialMerge financialMerge = financialMerges.get(0);
                financialMerge.setFinancialReportTaxDetailId(detail.getId());
                financialMerge.setFinancialIndividualIncomeTaxDetailId(individualIncomeTaxDetail.getId());
                financialMerge.setType("税款");
                bool = financialMerge.getId() == null ? financialMergeService.save(financialMerge) : financialMergeService.updateById(financialMerge);
                BizDeduction deduction = deductions.get(0);
                deduction.setDeductible(financialMerge.getFinancialIndividualIncomeTaxDetailId().equals(0L) || financialMerge.getFinancialReportTaxDetailId().equals(0L) ? 0 : 1);
                deduction.setSourceName("税款");
                deduction.setSourceTableName("financial_merge");
                deduction.setAmount(individualIncomeTaxDetail == null ? detail.getSumTax() == null ? BigDecimal.ZERO : detail.getSumTax() : individualIncomeTaxDetail.getAmount().add(detail.getSumTax() == null ? BigDecimal.ZERO : detail.getSumTax()));
                deduction.setYear(detail.getYear());
                deduction.setWorkOrderId(detail.getWorkOrderId());
                deduction.setMonth(detail.getMonth());
                deduction.setSourceId(financialMerge.getId());
                deduction.setCompanyId(detail.getCompanyId());
                BizCompany company = companyService.getById(detail.getCompanyId());
                deduction.setTenantId(company.getTenantId());
                return bool && deductionService.updateById(deduction);
            }
        }
        return true;
    }

    @ApiOperation(value = "带条件List 分页查询", notes = "带条件List 分页查询")
    @PostMapping("/getPrevDetail")
    @ResponseBody
    public AjaxResult getPrevDetail(@RequestBody BizFinancialReportTaxDetailNonZero detail) {
        BizFinancialReportTaxDetailNonZero financialReportTaxDetail = financialReportTaxDetailService.query().eq("company_id", detail.getCompanyId()).lt("concat(year,'-',month)", detail.getYear() + "-" + detail.getMonth()).last("limit 1").one();
        return success(financialReportTaxDetail);
    }

    @ApiOperation("退回")
    @PreAuthorize("@ss.hasPermi('business:financialReportTaxNonZero:back')")
    @PostMapping("/deductionTurnBack")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    @Log(title = "扣款任务-退回", businessType = BusinessType.UPDATE)
    public AjaxResult deductionTurnBack(@RequestBody BizFinancialReportTaxDetail detail) {
        detail.setStatus(1);
        BizFinancialMerge merge = financialMergeService.query().eq("financial_report_tax_detail_id", detail.getId()).one();
        if (merge != null) {
            merge.setFinancialReportTaxDetailId(0L);
            if (merge.getFinancialReportTaxDetailId().equals(0L) && merge.getFinancialIndividualIncomeTaxDetailId().equals(0L)) {
                removeDeductionByMerge(merge);
            } else {
                BizFinancialIndividualIncomeTaxDetailIsZero financialIndividualIncomeTaxDetail = financialIndividualIncomeTaxDetailService.getById(merge.getFinancialIndividualIncomeTaxDetailId());
                if (financialIndividualIncomeTaxDetail.getAmount().doubleValue() > 0) {
                    financialMergeService.updateById(merge);
                    List<BizDeduction> deductions = deductionService.query().eq("source_table_name", "financial_merge").eq("source_id", merge.getId()).list();
                    deductions.forEach(l -> {
                        l.setDeductible(0);
                    });
                    deductionService.updateBatchById(deductions);
                } else {
                    removeDeductionByMerge(merge);
                }
            }
        }
        BizHistory bizHistory = new BizHistory();
        bizHistory.setTableName("biz_financial_report_tax");
        bizHistory.setCompanyId(detail.getCompanyId());
        bizHistory.setBelongPeriod(detail.getYear() + "-" + String.format("%02d", Integer.valueOf(detail.getMonth())) );
        bizHistory.setEvent("退回");
        bizHistory.setReason(detail.getRefuseReason());
        bizHistory.setTenantId(getTenantId());
        bizHistoryService.save(bizHistory);
        return financialReportTaxDetaiIsZerolService.updateById(detail) ? success() : error();
    }

    private boolean removeDeductionByMerge(BizFinancialMerge merge) {
        Map<String, Object> delCondition = new HashMap<>(2);
        delCondition.put("id", merge.getId());
        List<BizDeduction> deductions = deductionService.query().eq("source_table_name", "financial_merge").eq("source_id", merge.getId()).list();
        if (deductions.isEmpty()) {
            return false;
        } else {
            return financialMergeService.physicallyDelete(delCondition) > 0 && deductionService.removeBatchByIds(deductions.stream().map(BizDeduction::getId).collect(Collectors.toList()));
        }
    }
}
