package com.engine.salary.maintainer.datacollection;

import com.engine.common.util.ServiceUtil;
import com.engine.core.impl.Service;
import com.engine.salary.entity.taxdeclaration.param.TaxDeclarationSaveParam;
import com.engine.salary.entity.taxdeclaration.po.TaxDeclarationPO;
import com.engine.salary.mapper.taxdeclaration.TaxDeclarationMapper;
import com.engine.salary.service.TaxDeclarationService;
import com.engine.salary.service.impl.TaxDeclarationServiceImpl;
import com.engine.salary.util.SalaryDateUtil;
import com.engine.salary.util.SalaryEntityUtil;
import com.engine.salary.util.db.MapperProxyFactory;
import weaver.general.BaseBean;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Harryxzy
 * @date 2023/04/23 17:23
 * @description 往期累计情况维护类
 */
public class AddUpSituationManager extends Service {

    private TaxDeclarationMapper getTaxDeclarationMapper() {
        return MapperProxyFactory.getProxy(TaxDeclarationMapper.class);
    }

    private TaxDeclarationService getTaxDeclarationService() {
        return ServiceUtil.getService(TaxDeclarationServiceImpl.class, user);
    }

    public boolean recoverAddUpHistoryData() {
        // 获取已有的个税申报表记录
        List<TaxDeclarationPO> taxDeclarationList = getTaxDeclarationMapper().listSome(new TaxDeclarationPO());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Map<Long, String> taxDeclarationMap = SalaryEntityUtil.convert2Map(taxDeclarationList, TaxDeclarationPO::getId, PO -> PO.getTaxAgentId() + "-" + sdf.format(PO.getSalaryMonth()));
        BaseBean bb = new BaseBean();
        List<Long> taxDeclarationIds = taxDeclarationList.stream().map(TaxDeclarationPO::getId).collect(Collectors.toList());
        bb.writeLog("往期累计数据恢复DataIds：" + taxDeclarationIds);
        bb.writeLog("往期累计数据恢复DataMap：" + taxDeclarationMap);
        boolean result = true;
        // 循环调用生成申报单接口
        for (int i = 0; i < taxDeclarationList.size(); i++) {
            TaxDeclarationPO po = taxDeclarationList.get(i);
            bb.writeLog("开始删除生成:" + po.getTaxAgentId() + "-" + po.getSalaryMonth());
            // 删除记录
            int delete = getTaxDeclarationMapper().deleteByIdZj(po.getId());
            LocalDate localDate = SalaryDateUtil.dateToLocalDate(po.getSalaryMonth());
            // 调用生成申报单接口
            YearMonth yearMonth = YearMonth.of(localDate.getYear(), localDate.getMonth());
            try {
                getTaxDeclarationService().save(TaxDeclarationSaveParam.builder().salaryMonth(yearMonth).taxAgentId(po.getTaxAgentId()).build());
            } catch (Exception e) {
                bb.writeLog("错误:" + e);
                result = false;
                continue;
            }
        }
        return result;
    }


}
