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

import cn.ezhizao.common.utils.SecurityUtils;
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.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.history.domain.BizHistory;
import cn.ezhizao.project.business.history.service.IBizHistoryService;
import cn.ezhizao.project.business.housingFund.domain.BizHousingFundConfirmDetail;
import cn.ezhizao.project.business.housingFund.domain.BizHousingFundConfirmDetailEmployee;
import cn.ezhizao.project.business.housingFund.domain.BizHousingFundDeclare;
import cn.ezhizao.project.business.housingFund.domain.BizHousingFundDeclareDetail;
import cn.ezhizao.project.business.housingFund.domain.vo.EmployeeExcel;
import cn.ezhizao.project.business.housingFund.domain.vo.HousingFundEmployeeVo;
import cn.ezhizao.project.business.housingFund.service.IBizHousingFundConfirmDetailEmployeeService;
import cn.ezhizao.project.business.housingFund.service.IBizHousingFundConfirmDetailService;
import cn.ezhizao.project.business.housingFund.service.IBizHousingFundDeclareDetailService;
import cn.ezhizao.project.business.housingFund.service.IBizHousingFundDeclareService;
import cn.ezhizao.project.business.socialSecurity.domain.BizSocialSecurityDeclareDetail;
import cn.ezhizao.project.business.workOrder.domain.BizWorkOrderRecord;
import cn.ezhizao.project.business.workOrder.service.IBizWorkOrderRecordService;
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.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;


/**
 * @author 周晓
 */
@RestController
@Api(tags = "FinancialHousingFundDeclare数据接口")
@RequestMapping(value = "/business/housingFundDeclare")
public class BizHousingFundDeclareController extends BaseController {

    @Resource
    IBizHousingFundDeclareService housingFundDeclareService;
    @Resource
    IBizHousingFundConfirmDetailService housingFundConfirmDetailService;
    @Resource
    IBizHousingFundConfirmDetailEmployeeService housingFundConfirmDetailEmployeeService;
    @Resource
    IBizHousingFundDeclareDetailService housingFundDeclareDetailService;
    @Resource
    IBizCompanyService companyService;
    @Resource
    SysUserMapper sysUserMapper;
    @Resource
    ISysFileStorageService fileStorageService;
    @Resource
    IBizDeductionService deductionService;
    @Resource
    IBizWorkOrderRecordService bizWorkOrderRecordService;
    @Resource
    private IBizEntrustService bizEntrustService;

    @Resource
    private IBizHistoryService bizHistoryService;

    @ApiOperation(value = "根据id查询", notes = "根据id查询")
    @GetMapping("/getById/{id}")
    @ResponseBody
    public AjaxResult getById(@PathVariable Long id) {
        return success(housingFundDeclareService.getById(id));
    }

    @PostMapping("/save")
    @ApiOperation(value = "保存", notes = "保存")
    @ResponseBody
    public AjaxResult save(@RequestBody BizHousingFundDeclare housingFundDeclare) {
        return (housingFundDeclare.getId() == null ? housingFundDeclareService.save(housingFundDeclare) : housingFundDeclareService.updateById(housingFundDeclare)) ? success() : error();
    }

    @PostMapping("/exportDetail")
    public void exportDetail(HttpServletResponse response, HousingFundEmployeeVo vo) throws Exception {
        OutputStream out = null;
        BufferedOutputStream bos = null;
        List<BizHousingFundConfirmDetailEmployee> employees = new ArrayList<>();
        List<EmployeeExcel> employeeExcels = new ArrayList<>();
        try {
            ClassPathResource classPathResource = new ClassPathResource("importTemplate/公积金模板.xlsx");
            InputStream inputStream = classPathResource.getInputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("公积金明细导出.xls", "utf-8");
            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));

            out = response.getOutputStream();
            bos = new BufferedOutputStream(out);

            //读取Excel
            ExcelWriter excelWriter = EasyExcel.write(bos).withTemplate(inputStream).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();

            FillConfig fillConfig = FillConfig.builder()
                    // 开启填充换行
                    .forceNewRow(true)
                    .build();
            // 直接写入Excel数据
            List<EmployeeExcel> list = getList(vo, employees, employeeExcels);
            HashMap<String, Object> map = new HashMap<>();
            BizCompany company = companyService.getById(vo.getCompanyId());
            String titleName = vo.getYear() + "年" + vo.getMonth() + "月" + company.getName()+ "公积金明细";
            AtomicReference<BigDecimal> totat1 = new AtomicReference<>(BigDecimal.ZERO);
            AtomicReference<BigDecimal> totat2 = new AtomicReference<>(BigDecimal.ZERO);
            AtomicReference<BigDecimal> totat3 = new AtomicReference<>(BigDecimal.ZERO);
            list.forEach(item -> {
                totat1.updateAndGet(v -> v .add(item.getCompanyAmount()));
                totat2.updateAndGet(v -> v .add(item.getOneSelfAmount()));
                totat3.updateAndGet(v -> v .add(item.getTotalAmount()));
            });
            map.put("titleName", titleName);
            map.put("totat1", totat1.get());
            map.put("totat2", totat2.get());
            map.put("totat3", totat3.get());
            excelWriter.fill(list, fillConfig, writeSheet);
            excelWriter.fill(map, fillConfig, writeSheet);
            excelWriter.finish();
            bos.flush();

        } catch (Exception e) {
           e.printStackTrace();
        }finally {
            bos.close();
        }

    }

    private List<EmployeeExcel> getList(HousingFundEmployeeVo vo, List<BizHousingFundConfirmDetailEmployee> employees, List<EmployeeExcel> employeeExcels) {
        BizHousingFundConfirmDetail housingFundConfirmDetail = housingFundConfirmDetailService
                .query().eq("company_id", vo.getCompanyId())
                .eq("year", vo.getYear())
                .eq("month", vo.getMonth())
                .eq("deleted", 0).one();
        if (housingFundConfirmDetail != null) {
            employees = housingFundConfirmDetailEmployeeService.query()
                    .eq("housing_fund_confirm_detail_id", housingFundConfirmDetail.getId())
                    .eq("deleted", 0)
                    .ne("change_status", 2)
                    .list();
        }
        if (!CollectionUtils.isEmpty(employees)) {
            for (int i = 0; i < employees.size(); i++) {
                BizHousingFundConfirmDetailEmployee employee = employees.get(i);
                //去掉百分比
                BigDecimal ratio = employee.getRatio().divide(BigDecimal.valueOf(100)).setScale(2);
                EmployeeExcel employeeExcel = new EmployeeExcel();
                employeeExcel.setIndex(i + 1);
                employeeExcel.setEmployeeName(employee.getEmployeeName());
                employeeExcel.setCardinalNumber(employee.getCardinalNumber());
                employeeExcel.setRatio(ratio);
                employeeExcel.setCompanyAmount(employee.getCardinalNumber().multiply(ratio).setScale(2));
                employeeExcel.setOneSelfAmount(employee.getCardinalNumber().multiply(ratio).setScale(2));
                employeeExcel.setTotalAmount(employeeExcel.getCompanyAmount().add(employeeExcel.getOneSelfAmount()));
                employeeExcels.add(employeeExcel);
            }
        }
        return employeeExcels;
    }

    @PostMapping("/saveBatch")
    @ApiOperation(value = "批量保存", notes = "批量保存")
    @ResponseBody
    public AjaxResult saveBatch(@RequestBody List<BizHousingFundDeclare> list) {
        return housingFundDeclareService.saveOrUpdateBatch(list) ? success() : error();
    }

    @ApiOperation(value = "删除", notes = "删除")
    @GetMapping("/deleteById/{id}")
    @ResponseBody
    public AjaxResult deleteById(@PathVariable Long id) {
        return housingFundDeclareService.removeById(id) ? success() : error();
    }

    @ApiOperation(value = "批量删除", notes = "批量删除")
    @PostMapping("/batchDelete")
    @ResponseBody
    public AjaxResult batchDelete(@RequestBody List<Long> list) {
        return housingFundDeclareService.removeBatchByIds(list) ? success() : error();
    }

    @ApiOperation(value = "带条件List 分页查询", notes = "带条件List 分页查询")
    @PreAuthorize("@ss.hasPermi('business:housingFundDeclare:list')")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo getList(BizHousingFundDeclare conditions) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(conditions);
        startPage();
        startOrderBy();
        List<BizHousingFundDeclare> list = housingFundDeclareService.getListByBean(conditions);
        if (!list.isEmpty()) {
            BizHousingFundDeclareDetail detailConditions = new BizHousingFundDeclareDetail();
            detailConditions.setYear(conditions.getYear());
            detailConditions.setMonth(conditions.getMonth());
            detailConditions.setMainIds(list.stream().map(BizHousingFundDeclare::getId).collect(Collectors.toList()));
//            List<BizHousingFundDeclareDetail> details = housingFundDeclareDetailService.getListByBean(detailConditions);
            List<BizHousingFundDeclareDetail> details = housingFundDeclareDetailService.getListByBean2(detailConditions);
            list.forEach(l -> {
                List<BizHousingFundDeclareDetail> lDetail = details.stream().filter(v -> v.getHousingFundDeclareId().equals(l.getId())).collect(Collectors.toList());
                l.setDetail(lDetail.isEmpty() ? null : lDetail.get(0));
            });
        }

        //分页数据

        return getDataTable(list);
    }

    @ApiOperation(value = "带条件List 分页查询", notes = "带条件List 分页查询")
    @PostMapping("/getListForYear")
    @ResponseBody
    public TableDataInfo getListForYear(@RequestBody BizHousingFundDeclare conditions) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(conditions);
        List<BizHousingFundDeclare> list = housingFundDeclareService.getListByBean(conditions);
        if (!list.isEmpty()) {
            BizHousingFundDeclareDetail detailConditions = new BizHousingFundDeclareDetail();
            detailConditions.setYear(conditions.getYear());
            detailConditions.setMainIds(list.stream().map(BizHousingFundDeclare::getId).collect(Collectors.toList()));
            List<BizHousingFundDeclareDetail> details = housingFundDeclareDetailService.getListByBean(detailConditions);
            list.forEach(l -> {
                List<BizHousingFundDeclareDetail> lDetail = details.stream().filter(v -> v.getHousingFundDeclareId().equals(l.getId())).collect(Collectors.toList());
                l.setDetails(lDetail);
            });
        }


        return getDataTable(list);
    }

    @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();
    }

    @PreAuthorize("@ss.hasAnyPermi('business:housingFundDeclare:query,business:housingFundDeclare:verify')")
    @PostMapping("/getDetail")
    public AjaxResult getDetail(@RequestBody BizHousingFundDeclareDetail condition) {
        List<BizHousingFundDeclareDetail> housingFundDeclareDetails = housingFundDeclareDetailService.getListByBean(condition);
        BizCompany company = companyService.getById(condition.getCompanyId());
        int nowYear = LocalDate.now().getYear();
        int nowMonth = LocalDate.now().getMonthValue();
        String formattedMonth = String.format("%02d", nowMonth);
        String year = condition.getYear();
        String month = condition.getMonth();
        String s1 = year + month;
        String s2 = nowYear + formattedMonth;
        if (!s1.equals(s2) && housingFundDeclareDetails.isEmpty()) {
            return error("当前月未找到数据");
        }
        if (housingFundDeclareDetails.isEmpty()) {
            // 获取上个月的信息
            // 先获取之前的一个月是否已填报，然后获取填报后的信息
            BizHousingFundDeclareDetail detail = housingFundDeclareDetailService.query().eq("housing_fund_declare_id", condition.getHousingFundDeclareId()).lt("concat(year,month)", condition.getYear() + condition.getMonth()).orderByDesc("concat(year, month)").last("limit 1").one();
            if (detail != null) {
                List<SysFileStorage> files = fileStorageService.query().eq("master_table_name", "biz_housing_fund_declare_detail").eq("master_id", detail.getId()).list();
                files.forEach(l -> l.setId(null));
                condition.setEvidenceFiles(files);
            } else {
                condition.setEvidenceFiles(new ArrayList<>());
            }
            condition.setCompanyName(company.getName());
            condition.setHousingFundPassword(company.getHousingFundPassword());
            condition.setHousingFundUnitAccount(company.getHousingFundUnitAccount());
            condition.setHousingFundDeductionPassword(company.getHousingFundDeductionPassword());
            condition.setIsFirstHousingFund(company.getIsFirstHousingFund());
            condition.setIsPayOnWindow(company.getIsPayOnWindow());

            return success(condition);
        }
        Long id = condition.getHousingFundDeclareId();
        Long workOrderId = housingFundDeclareService.getById(id).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 ).last("limit 1"));
        BizHousingFundDeclareDetail bizHousingFundDeclareDetail = housingFundDeclareDetails.get(0);
        bizHousingFundDeclareDetail.setEntrust(one);
        return success(housingFundDeclareDetails.get(0));
    }
    /**
     * 导出列表
     */
    @PreAuthorize("@ss.hasPermi('business:housingFundDeclare:export')")
    @Log(title = "公积金申报任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizHousingFundDeclare conditions) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(conditions);
        startOrderBy();
        List<BizHousingFundDeclare> list = housingFundDeclareService.getListByBean(conditions);
        for (BizHousingFundDeclare l : list) {
            l.setCurrentPeriod(conditions.getYear() + "-" + conditions.getMonth());
            BizHousingFundDeclareDetail detail = new BizHousingFundDeclareDetail();
            detail.setHousingFundDeclareId(l.getId());
            detail.setYear(conditions.getYear());
            detail.setMonth(conditions.getMonth());
            List<BizHousingFundDeclareDetail> details = housingFundDeclareDetailService.getListByBean(detail);
            if (details.size() == 0) {
                l.setStatusText("未开始");
                l.setMakeOut("未填写");
            } else {
                detail = details.get(0);
                List<BizWorkOrderRecord> records = bizWorkOrderRecordService.query().eq("work_order_id", l.getWorkOrderId()).eq("year", conditions.getYear()).eq("month", conditions.getMonth()).eq("from_id", 0).list();
                if (records.size() > 0) {
                    SysUser sysUser = sysUserMapper.selectUserById(records.get(0).getRecorderId());
                    l.setServiceName(sysUser == null ? "" : sysUser.getNickName());
                } else {
                    l.setServiceName("");
                }
                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;
                }
            }
        }
        ExcelUtil<BizHousingFundDeclare> util = new ExcelUtil<BizHousingFundDeclare>(BizHousingFundDeclare.class);
        util.exportExcel(response, list, "公积金申报任务数据");
    }

    @ApiOperation("保存detail")
    @PostMapping("/saveDetail")
    @PreAuthorize("@ss.hasPermi('business:housingFundDeclare:edit')")
    @Log(title = "公积金申报任务", businessType = BusinessType.UPDATE)
    @ResponseBody
    public AjaxResult saveDetail(@RequestBody BizHousingFundDeclareDetail detail) {
        detail.setVerifierId(SecurityUtils.getUserId());
        detail.setVerifierTime(new Date());
        boolean bool = housingFundDeclareDetailService.saveOrUpdate(detail);
        bool = bool && checkDeduction(detail);
        List<SysFileStorage> fileStorages = detail.getEvidenceFiles();
        fileStorages.forEach(l -> {
            l.setMasterId(detail.getId());
            l.setMasterTableName("biz_housing_fund_declare_detail");
        });
        SysFileStorage delCondition = new SysFileStorage();
        delCondition.setMasterId(detail.getId());
        delCondition.setMasterTableName("biz_housing_fund_declare_detail");
        fileStorageService.physicalDelete(delCondition);
        BizHistory bizHistory = new BizHistory();
        bizHistory.setTableName("biz_housing_fund_declare");
        bizHistory.setCompanyId(detail.getCompanyId());
        bizHistory.setEvent("保存");
        bizHistory.setTenantId(getTenantId());
        bizHistory.setBelongPeriod(detail.getYear() + "-" +String.format("%02d", Integer.valueOf(detail.getMonth())));
        bizHistoryService.save(bizHistory);
        bool = bool && (fileStorages.isEmpty() || fileStorageService.saveOrUpdateBatch(fileStorages)) && addRecord(detail.getHousingFundDeclareId(), detail.getYear(), detail.getMonth(), SecurityUtils.getUserId(), detail.getAmount().compareTo(BigDecimal.ZERO) > 0 ? "公积金申报保存" : "公积金申报完成", detail.getAmount().compareTo(BigDecimal.ZERO) > 0 ? 1 : 3);
        return bool ? success(detail) : error();
    }

    @ApiOperation("审核")
    @PostMapping("/verify")
    @PreAuthorize("@ss.hasPermi('business:housingFundDeclare:verify')")
    @Transactional(rollbackFor = Exception.class)
    @Log(title = "公积金审核", businessType = BusinessType.UPDATE)
    @ResponseBody
    public AjaxResult verify(@RequestBody BizHousingFundDeclareDetail detail) {
//        if(detail.getValueAddedTax())
        BigDecimal amount = detail.getUnitAmount().add(detail.getIndividualAmount());
        BizHousingFundDeclare main = housingFundDeclareService.getById(detail.getHousingFundDeclareId());
        boolean res1 = true;
        if (amount.compareTo(BigDecimal.ZERO) > 0 && detail.getStatus().equals(3)) {
            BizDeduction deduction = new BizDeduction();
            deduction.setWorkOrderId(main.getWorkOrderId());
            deduction.setSourceName("公积金");
            deduction.setSourceTableName("biz_housing_fund_declare_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 = housingFundDeclareDetailService.updateById(detail);
        return (res1 && res2) ? success() : error();
    }

    @ApiOperation("获取公积金人员信息")
    @PostMapping("/getMembers")
    @ResponseBody
    public AjaxResult getMembers(@RequestBody BizHousingFundConfirmDetail detail) {
        BizHousingFundConfirmDetail housingFundConfirmDetail = housingFundConfirmDetailService.query().eq("company_id", detail.getCompanyId()).eq("year", detail.getYear()).eq("month", detail.getMonth()).one();
        if (housingFundConfirmDetail != null) {
            List<BizHousingFundConfirmDetailEmployee> employees = housingFundConfirmDetailEmployeeService.query()
                    .eq("housing_fund_confirm_detail_id", housingFundConfirmDetail.getId())
                    .list();
            return success(employees);
        } else {
            return success(new ArrayList<>());
        }

    }

    @ApiOperation("获取公积金人员信息")
    @PostMapping("/getMembersNoDelete")
    @ResponseBody
    public AjaxResult getMembersNoDelete(@RequestBody BizHousingFundConfirmDetail detail) {
        BizHousingFundConfirmDetail housingFundConfirmDetail = housingFundConfirmDetailService.query().eq("company_id", detail.getCompanyId()).eq("year", detail.getYear()).eq("month", detail.getMonth()).one();
        if (housingFundConfirmDetail != null) {
            List<BizHousingFundConfirmDetailEmployee> employees = housingFundConfirmDetailEmployeeService.query()
                    .eq("housing_fund_confirm_detail_id", housingFundConfirmDetail.getId())
                    .ne("change_status", 2)
                    .list();

            for (BizHousingFundConfirmDetailEmployee employee : employees) {
                employee.setCompanyAmount(employee.getRatio().divide(BigDecimal.valueOf(100)).multiply(employee.getCardinalNumber()));
                employee.setOneSelfAmount(employee.getRatio().divide(BigDecimal.valueOf(100)).multiply(employee.getCardinalNumber()));
                employee.setTotalAmount(employee.getCompanyAmount().add(employee.getOneSelfAmount()));
            }
            return success(employees);
        } else {
            return success(new ArrayList<>());
        }

    }

    private Boolean checkDeduction(BizHousingFundDeclareDetail detail) {
        BizHousingFundDeclare main = housingFundDeclareService.getById(detail.getHousingFundDeclareId());
        if (detail.getAmount() != null && detail.getAmount().compareTo(BigDecimal.ZERO) > 0 && detail.getStatus().equals(3)) {
            BizDeduction deduction = new BizDeduction();
            deduction.setWorkOrderId(main.getWorkOrderId());
            deduction.setSourceName("公积金");
            deduction.setSourceTableName("biz_housing_fund_declare_detail");
            deduction.setAmount(detail.getAmount());
            deduction.setDeductible(1);
            deduction.setYear(detail.getYear());
            deduction.setMonth(detail.getMonth());
            deduction.setSourceId(detail.getId());
            deduction.setCompanyId(detail.getCompanyId());
            BizCompany company = companyService.getById(detail.getCompanyId());
            deduction.setTenantId(company.getTenantId());
            return deductionService.save(deduction);
        }
        return true;
    }


    @ApiOperation("退回")
    @PostMapping("/turnBackDetail")
    @PreAuthorize("@ss.hasPermi('business:housingFundDeclare:return')")
    @Transactional(rollbackFor = Exception.class)
    @Log(title = "公积金申报任务-退回", businessType = BusinessType.UPDATE)
    @ResponseBody
    public AjaxResult deductionTurnBack(@RequestBody BizHousingFundDeclareDetail detail) {
        detail.setStatus(1);
        List<BizDeduction> deductions = deductionService.query().eq("source_table_name", "biz_housing_fund_declare_detail").eq("source_id", detail.getId()).list();
        if (deductions.stream().anyMatch(v -> v.getStatus().equals(2))) {
            return error("该公积金记录已扣款");
        }
        BizHistory bizHistory = new BizHistory();
        bizHistory.setTableName("biz_housing_fund_declare");
        bizHistory.setCompanyId(detail.getCompanyId());
        bizHistory.setEvent("退回");
        bizHistory.setTenantId(getTenantId());
        bizHistory.setBelongPeriod(detail.getYear() + "-" +String.format("%02d", Integer.valueOf(detail.getMonth())));
        bizHistory.setReason(detail.getRefuseReason());
        bizHistoryService.save(bizHistory);
        deductionService.removeBatchByIds(deductions.stream().map(BizDeduction::getId).collect(Collectors.toList()));
        return housingFundDeclareDetailService.updateById(detail) && addRecord(detail.getHousingFundDeclareId(), detail.getYear(), detail.getMonth(), SecurityUtils.getUserId(), "公积金申报退回", 1) ? success() : error();
    }


    private boolean addRecord(Long mainId, String year, String month, Long recorderId, String description, Integer status) {
        // 没拆分合同单价
        BizHousingFundDeclare housingFundDeclare = housingFundDeclareService.getById(mainId);
        Long workOrderId = housingFundDeclare.getWorkOrderId();
        List<BizWorkOrderRecord> records = bizWorkOrderRecordService.query().eq("work_order_id", workOrderId).eq("year", year).eq("month", month).eq("from_id", 0).list();
        if (records.isEmpty()) {
            // 新增一条记录
            BizWorkOrderRecord record = new BizWorkOrderRecord();
            record.setMonth(month);
            record.setYear(year);
            record.setTenantId(getTenantId());
            record.setCompanyId(housingFundDeclare.getCompanyId());
            record.setWorkOrderId(workOrderId);
            record.setStatus(status);
            record.setStatusDescript(description);
            record.setRecorderId(recorderId);
            return bizWorkOrderRecordService.save(record);
        } else {
            // 新增一条子记录
            Long fromId = records.get(0).getId();
            BizWorkOrderRecord fromRecord = records.get(0);
            BizWorkOrderRecord record = new BizWorkOrderRecord();
            record.setCompanyId(housingFundDeclare.getCompanyId());
            record.setFromId(fromId);
            record.setMonth(fromRecord.getMonth());
            record.setYear(fromRecord.getYear());
            record.setTenantId(fromRecord.getTenantId());
            record.setWorkOrderId(fromRecord.getWorkOrderId());
            record.setStatus(fromRecord.getStatus());
            record.setStatusDescript(fromRecord.getStatusDescript());
            record.setRecorderId(fromRecord.getRecorderId());

            fromRecord.setMonth(month);
            fromRecord.setYear(year);
            fromRecord.setTenantId(getTenantId());
            fromRecord.setWorkOrderId(workOrderId);
            fromRecord.setStatus(status);
            fromRecord.setStatusDescript(description);
            fromRecord.setCompanyId(housingFundDeclare.getCompanyId());
            fromRecord.setRecorderId(recorderId);
            return bizWorkOrderRecordService.save(record) &&
                    bizWorkOrderRecordService.updateById(fromRecord);
        }
    }
}
