package com.ruoyi.hywz.service.impl;

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 com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.hywz.common.enums.StampBusinessTypeEnum;
import com.ruoyi.hywz.entity.AdsMatHyxtStampTaxContractD;
import com.ruoyi.hywz.entity.AdsMatHyxtStampTaxInvoiceD;
import com.ruoyi.hywz.entity.po.HomeStampTaxCountPO;
import com.ruoyi.hywz.entity.po.IdsPO;
import com.ruoyi.hywz.entity.po.StampTaxBatchUpdateBusinessTypePO;
import com.ruoyi.hywz.listener.ImportExcelHelper;
import com.ruoyi.hywz.mapper.AdsMatHyxtStampTaxInvoiceDMapper;
import com.ruoyi.hywz.service.IAdsMatHyxtStampTaxContractDService;
import com.ruoyi.hywz.service.IAdsMatHyxtStampTaxInvoiceDService;
import com.ruoyi.hywz.utils.DateUtil;
import com.ruoyi.hywz.utils.IdGen;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 发票信息表 服务实现类
 * </p>
 *
 * @author mybatisplus-generator
 * @date 2024-07-14 10:07:56
 */
@Service
public class AdsMatHyxtStampTaxInvoiceDServiceImpl extends ServiceImpl<AdsMatHyxtStampTaxInvoiceDMapper,AdsMatHyxtStampTaxInvoiceD> implements IAdsMatHyxtStampTaxInvoiceDService {

    @Autowired
    private IAdsMatHyxtStampTaxContractDService adsMatHyxtStampTaxContractDService;

    @Override
    public List<AdsMatHyxtStampTaxInvoiceD> getList(String startDate, String endDate, String orgNo) {
        LambdaQueryWrapper<AdsMatHyxtStampTaxInvoiceD> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AdsMatHyxtStampTaxInvoiceD::getCreateUserOrgNo, orgNo);
        queryWrapper.eq(AdsMatHyxtStampTaxInvoiceD::getIsDeleted, 0);
        queryWrapper.ge(AdsMatHyxtStampTaxInvoiceD::getMakeDate, startDate);
        queryWrapper.le(AdsMatHyxtStampTaxInvoiceD::getMakeDate, endDate);
        return this.list(queryWrapper);
    }

    /**
     * 分页查询
     */
    @Override
    public Page<AdsMatHyxtStampTaxInvoiceD> queryPage(Long pageSize, Long pageNo, AdsMatHyxtStampTaxInvoiceD param) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Page<AdsMatHyxtStampTaxInvoiceD> page = new Page<>();
        page.setSize(pageSize);
        page.setCurrent(pageNo);

        LambdaQueryWrapper<AdsMatHyxtStampTaxInvoiceD> queryWrapper = Wrappers.lambdaQuery();
        // 非管理员只能查询自己单位导入的数据
        if (!loginUser.getUsername().equals("admin")) {
            queryWrapper.like(AdsMatHyxtStampTaxInvoiceD::getCreateUserOrgNo, loginUser.getOrgNo());
        }
        queryWrapper.eq(AdsMatHyxtStampTaxInvoiceD::getIsDeleted, 0);
        if (null != param) {
            queryWrapper.like(StringUtils.isNotBlank(param.getInvoiceCode()), AdsMatHyxtStampTaxInvoiceD::getInvoiceCode, param.getInvoiceCode());
            queryWrapper.like(StringUtils.isNotBlank(param.getInvoiceNumber()), AdsMatHyxtStampTaxInvoiceD::getInvoiceNumber, param.getInvoiceNumber());
            queryWrapper.like(StringUtils.isNotBlank(param.getSellerName()), AdsMatHyxtStampTaxInvoiceD::getSellerName, param.getSellerName());
            queryWrapper.like(StringUtils.isNotBlank(param.getInvoiceTelexNumber()), AdsMatHyxtStampTaxInvoiceD::getInvoiceTelexNumber, param.getInvoiceTelexNumber());
            queryWrapper.eq(StringUtils.isNotBlank(param.getCreateUserOrgNo()), AdsMatHyxtStampTaxInvoiceD::getCreateUserOrgNo, param.getCreateUserOrgNo());
//            queryWrapper.eq(StringUtils.isNotBlank(param.getBusinessTypeCode()), AdsMatHyxtStampTaxInvoiceD::getBusinessTypeCode, param.getBusinessTypeCode());
            queryWrapper.eq(StringUtils.isNotBlank(param.getWarningType()), AdsMatHyxtStampTaxInvoiceD::getWarningType, param.getWarningType());
            if (StringUtils.isNotBlank(param.getBusinessTypeCode())) {
                String businessTypeCode = param.getBusinessTypeCode();
                if (businessTypeCode.equals(StampBusinessTypeEnum.TYPE_0.getCode())) {
                    queryWrapper.isNull(AdsMatHyxtStampTaxInvoiceD::getBusinessTypeCode);
                } else {
                    queryWrapper.eq(AdsMatHyxtStampTaxInvoiceD::getBusinessTypeCode, param.getBusinessTypeCode());
                }
            }
            if (StringUtils.isNotBlank(param.getStartDate()) && StringUtils.isNotBlank(param.getEndDate())) {
                queryWrapper.ge(AdsMatHyxtStampTaxInvoiceD::getMakeDate, param.getStartDate());
                queryWrapper.le(AdsMatHyxtStampTaxInvoiceD::getMakeDate, param.getEndDate());
            }
            if (StringUtils.isNotBlank(param.getHomeOrgNo())) {
                queryWrapper.like(StringUtils.isNotBlank(param.getCreateUserOrgNo()), AdsMatHyxtStampTaxInvoiceD::getCreateUserOrgNo, param.getCreateUserOrgNo());
            }
            if (StringUtils.isNotBlank(param.getHomeDate())) {
                String[] startAndEnd = DateUtil.getMonthStartAndEnd(param.getHomeDate());
                if (null != startAndEnd) {
                    queryWrapper.ge(AdsMatHyxtStampTaxInvoiceD::getMakeDate, startAndEnd[0]);
                    queryWrapper.le(AdsMatHyxtStampTaxInvoiceD::getMakeDate, startAndEnd[1]);
                }
            }
            if (ObjectUtils.isNotEmpty(param.getIsWarningSelect())) {
                Integer isWarningSelect = param.getIsWarningSelect();
                if (isWarningSelect == 1) {
                    queryWrapper.gt(AdsMatHyxtStampTaxInvoiceD::getIsWarning, 0);
                }
                if (isWarningSelect == 0) {
                    queryWrapper.eq(AdsMatHyxtStampTaxInvoiceD::getIsWarning, 0);
                }
            }
        }

        queryWrapper.orderByAsc(AdsMatHyxtStampTaxInvoiceD::getCreateUserOrgNo);
        queryWrapper.orderByDesc(AdsMatHyxtStampTaxInvoiceD::getIsWarning);
        queryWrapper.orderByDesc(AdsMatHyxtStampTaxInvoiceD::getCreateTime);
        return this.page(page, queryWrapper);
    }

    @Override
    public R queryList(AdsMatHyxtStampTaxInvoiceD param) {
        // TODO 先查ads_mat_hyxt_stamp_tax_contract_invoice_d表，然后根据businessId反查发票表
        LoginUser loginUser = SecurityUtils.getLoginUser();
        LambdaQueryWrapper<AdsMatHyxtStampTaxInvoiceD> queryWrapper = Wrappers.lambdaQuery();
        // 非管理员只能查询自己单位导入的数据
//        if (!loginUser.getUsername().equals("admin")) {
//            queryWrapper.like(AdsMatHyxtStampTaxInvoiceD::getCreateUserOrgNo, loginUser.getOrgNo());
//        }
        queryWrapper.eq(AdsMatHyxtStampTaxInvoiceD::getIsDeleted, 0);

        if (null != param) {
            queryWrapper.eq(StringUtils.isNotBlank(param.getId()), AdsMatHyxtStampTaxInvoiceD::getId, param.getId());
            queryWrapper.eq(StringUtils.isNotBlank(param.getWarningType()), AdsMatHyxtStampTaxInvoiceD::getWarningType, param.getWarningType());
        }
        return R.ok(this.list(queryWrapper));
    }

    /**
     * 下载模板
     */
    @Override
    public void downloadTemplate(HttpServletResponse response) {
        String filePath = "excelTemplate/stampTax/stampTaxInvoiceImport.xlsx";
        byte[] buffer = new byte[1024];
        InputStream fis = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
        BufferedInputStream bis = null;
        try {
            response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + URLEncoder.encode(UUID.fastUUID().toString(), "UTF-8"));
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
                fis.close();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }

    @Override
    public void exportData(String warningType, HttpServletResponse response) throws IOException {
        InputStream fis = null;
        OutputStream ops = null;

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = java.util.UUID.randomUUID() + ".xlsx";
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        String templateFileName = "excelTemplate/stampTax/stampTaxInvoiceExport.xlsx";
        fis = Thread.currentThread().getContextClassLoader().getResourceAsStream(templateFileName);
        ops = response.getOutputStream();
        List<AdsMatHyxtStampTaxInvoiceD> list = this.getList(warningType);
        int i = 0;
        for (AdsMatHyxtStampTaxInvoiceD itemD : list) {
            i++;
            itemD.setNo(i);
        }

        //填充导出信息
        ExcelWriter excelWriter = EasyExcel.write(ops, AdsMatHyxtStampTaxInvoiceD.class).withTemplate(fis).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        excelWriter.fill(list, fillConfig, writeSheet);
        excelWriter.finish();
    }

    private List<AdsMatHyxtStampTaxInvoiceD> getList(String warningType) {
        LambdaQueryWrapper<AdsMatHyxtStampTaxInvoiceD> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AdsMatHyxtStampTaxInvoiceD::getWarningType, warningType);
        queryWrapper.eq(AdsMatHyxtStampTaxInvoiceD::getIsDeleted, 0);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 逻辑删除
     */
    @Override
    public R delete(IdsPO param) {
        LambdaUpdateWrapper<AdsMatHyxtStampTaxInvoiceD> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.in(AdsMatHyxtStampTaxInvoiceD::getId, param.getIds());
        updateWrapper.set(AdsMatHyxtStampTaxInvoiceD::getIsDeleted, 1);
        this.update(updateWrapper);
        return R.ok();
    }

    @Override
    public R deleteOne(IdsPO param) {
        LambdaUpdateWrapper<AdsMatHyxtStampTaxInvoiceD> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(AdsMatHyxtStampTaxInvoiceD::getId, param.getId());
        updateWrapper.set(AdsMatHyxtStampTaxInvoiceD::getIsDeleted, 1);
        this.update(updateWrapper);
        return R.ok();
    }

    @Override
    public R batchDelete(IdsPO param) {
        LambdaQueryWrapper<AdsMatHyxtStampTaxInvoiceD> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.in(AdsMatHyxtStampTaxInvoiceD::getId, param.getIds());
        baseMapper.delete(queryWrapper);
        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R invoiceImport(MultipartFile file, HomeStampTaxCountPO param) throws IOException {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        ImportExcelHelper<AdsMatHyxtStampTaxInvoiceD> helper = new ImportExcelHelper<>();
        List<AdsMatHyxtStampTaxInvoiceD> list = helper.getList(file.getInputStream(), AdsMatHyxtStampTaxInvoiceD.class, 0, 1);
        if (list.size() == 0) {
            return R.fail("导入失败，未解析到正确数据!");
        }
        // 先删除日期区间的数据
        String[] startAndEnd = DateUtil.getMonthStartAndEnd(param.getHomeDate());
        this.deleteData(param.getHomeOrgNo(), startAndEnd[0], startAndEnd[1]);

        // 1.查合同数据
        AdsMatHyxtStampTaxContractD adsMatHyxtStampTaxContractD = new AdsMatHyxtStampTaxContractD();
//        adsMatHyxtStampTaxContractD.setContractType("技术服务类合同");
        R r = adsMatHyxtStampTaxContractDService.queryList(adsMatHyxtStampTaxContractD);
        List<AdsMatHyxtStampTaxContractD> list1 = (List<AdsMatHyxtStampTaxContractD>) r.getData();

        Date date = new Date();
        for (AdsMatHyxtStampTaxInvoiceD invoiceD : list) {
            invoiceD.setId(IdGen.get32UUID());
            invoiceD.setIsWarning(0);
            invoiceD.setIsDeleted(0);
            invoiceD.setCreateUser(loginUser.getUsername());
            invoiceD.setCreateUserId(String.valueOf(loginUser.getUserId()));
            invoiceD.setCreateUserName(loginUser.getUsername());
            invoiceD.setCreateTime(date);
//            invoiceD.setCreateUserOrgNo(loginUser.getOrgNo());
//            invoiceD.setCreateUserOrgName(loginUser.getOrgName());
            invoiceD.setCreateUserOrgNo(param.getHomeOrgNo());
            invoiceD.setCreateUserOrgName(param.getSelectName());

            // 匹配业务分类
            String remark = invoiceD.getRemark();   // 备注
            String spBusinessType = invoiceD.getSpBusinessType();   // 特定业务类型
            String itemDesc = invoiceD.getItemDesc();   // 货物或应税劳务名称
            String taxRate = invoiceD.getTaxRate(); // 税率

            invoiceD.setBusinessType(StampBusinessTypeEnum.TYPE_0.getDesc());
            invoiceD.setBusinessTypeCode(StampBusinessTypeEnum.TYPE_0.getCode());

            if (StringUtils.isNotBlank(taxRate)) {
                if (taxRate.contains("免税") || taxRate.contains("0%")) {
                    continue;
                }
            }

            // 发票信息表“备注”包含（电商采购） ===> 电商采购
            if (StringUtils.isNotBlank(remark) && (remark.contains("电商采购") || remark.contains("采购订单")) ) {
                invoiceD.setBusinessType(StampBusinessTypeEnum.TYPE_1.getDesc());
                invoiceD.setBusinessTypeCode(StampBusinessTypeEnum.TYPE_1.getCode());
            }

            // 发票信息表“特定业务类型”为（成品油发票）（汽油）===> 汽油
            if (StringUtils.isNotBlank(spBusinessType) && spBusinessType.contains("成品油发票")) {
                invoiceD.setBusinessType(StampBusinessTypeEnum.TYPE_3.getDesc());
                invoiceD.setBusinessTypeCode(StampBusinessTypeEnum.TYPE_3.getCode());
            }
            if (StringUtils.isNotBlank(spBusinessType) && spBusinessType.contains("汽油")) {
                invoiceD.setBusinessType(StampBusinessTypeEnum.TYPE_3.getDesc());
                invoiceD.setBusinessTypeCode(StampBusinessTypeEnum.TYPE_3.getCode());
            }

            // 发票信息表“货物或应税劳务名称”含有（发电）或（购电）字段 ===> 购电
            if (StringUtils.isNotBlank(itemDesc) && (itemDesc.contains("发电") || itemDesc.contains("购电") || itemDesc.contains("*供电*"))) {
                invoiceD.setBusinessType(StampBusinessTypeEnum.TYPE_4.getDesc());
                invoiceD.setBusinessTypeCode(StampBusinessTypeEnum.TYPE_4.getCode());
            }

            // 发票信息表“货物或应税劳务名称”为（设计服务）（设计费） ===> 勘察设计
            if (StringUtils.isNotBlank(itemDesc) && (itemDesc.contains("设计服务") || itemDesc.contains("设计费"))) {
                invoiceD.setBusinessType(StampBusinessTypeEnum.TYPE_5.getDesc());
                invoiceD.setBusinessTypeCode(StampBusinessTypeEnum.TYPE_5.getCode());
            }

            // 合同信息表“合同名称”包含（宣传）字段，以“合同对方”字段为条件搜索全量发票信息表“销方名称”为相同的，匹配的上的标记为广告宣传
            list1.stream().forEach(e->{
                String contractName = e.getContractName(); // 合同名称
                String counterparty = e.getCounterparty(); // 合同对方
                if (StringUtils.isNotBlank(contractName) && contractName.contains("宣传")) {
                    if (StringUtils.isNotBlank(counterparty) && counterparty.equals(invoiceD.getSellerName())) {
                        invoiceD.setBusinessType(StampBusinessTypeEnum.TYPE_6.getDesc());
                        invoiceD.setBusinessTypeCode(StampBusinessTypeEnum.TYPE_6.getCode());
                    }
                }
            });

            // 发票信息表“货物或应税劳务名称”为（印刷品） ===> 印刷品
            if (StringUtils.isNotBlank(itemDesc) && itemDesc.contains("印刷品")) {
//                invoiceD.setBusinessType("印刷品");
                invoiceD.setBusinessType(StampBusinessTypeEnum.TYPE_7.getDesc());
                invoiceD.setBusinessTypeCode(StampBusinessTypeEnum.TYPE_7.getCode());
            }

            // 合同信息表“合同类型”为（技术服务类合同），以“合同对方”字段为条件搜索全量发票信息表“销方名称”为相同的，匹配的上的标记为技术服务
            list1.stream().forEach(e->{
                String contractType = e.getContractType(); // 合同类型
                String counterparty = e.getCounterparty(); // 合同对方
                if (StringUtils.isNotBlank(contractType) && contractType.contains("技术服务类合同")) {
                    if (StringUtils.isNotBlank(counterparty) && counterparty.equals(invoiceD.getSellerName())) {
                        invoiceD.setBusinessType(StampBusinessTypeEnum.TYPE_8.getDesc());
                        invoiceD.setBusinessTypeCode(StampBusinessTypeEnum.TYPE_8.getCode());
                    }
                }
            });

        }
        this.saveOrUpdateBatch(list);
        return R.ok();
    }

    private void deleteData(String orgNo, String startDate, String endDate) {
        LambdaQueryWrapper<AdsMatHyxtStampTaxInvoiceD> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AdsMatHyxtStampTaxInvoiceD::getCreateUserOrgNo, orgNo);
        queryWrapper.ge(AdsMatHyxtStampTaxInvoiceD::getMakeDate, startDate);
        queryWrapper.le(AdsMatHyxtStampTaxInvoiceD::getMakeDate, endDate);
        baseMapper.delete(queryWrapper);
    }

    private String checkIsExist(String invoiceCode, String invoiceNumber, String invoiceTelexNumber) {
        if (StringUtils.isNotBlank(invoiceCode) && StringUtils.isNotBlank(invoiceNumber)) {
            return check1(invoiceCode, invoiceNumber);
        } else if (StringUtils.isNotBlank(invoiceTelexNumber)) {
            return check2(invoiceTelexNumber);
        }
        return null;
    }

    private String check1(String invoiceCode, String invoiceNumber) {
        LambdaQueryWrapper<AdsMatHyxtStampTaxInvoiceD> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AdsMatHyxtStampTaxInvoiceD::getInvoiceCode, invoiceCode);
        queryWrapper.eq(AdsMatHyxtStampTaxInvoiceD::getInvoiceNumber, invoiceNumber);
        queryWrapper.eq(AdsMatHyxtStampTaxInvoiceD::getIsDeleted, 0);
        List<AdsMatHyxtStampTaxInvoiceD> list = baseMapper.selectList(queryWrapper);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0).getId();
    }

    private String check2(String invoiceTelexNumber) {
        LambdaQueryWrapper<AdsMatHyxtStampTaxInvoiceD> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AdsMatHyxtStampTaxInvoiceD::getInvoiceTelexNumber, invoiceTelexNumber);
        queryWrapper.eq(AdsMatHyxtStampTaxInvoiceD::getIsDeleted, 0);
        List<AdsMatHyxtStampTaxInvoiceD> list = baseMapper.selectList(queryWrapper);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0).getId();
    }

    @Override
    public void updateIsWarning(String id, Integer isWarning, String warningRemark) {
        LambdaUpdateWrapper<AdsMatHyxtStampTaxInvoiceD> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(AdsMatHyxtStampTaxInvoiceD::getId, id);
        updateWrapper.set(AdsMatHyxtStampTaxInvoiceD::getIsWarning, isWarning);
        updateWrapper.set(AdsMatHyxtStampTaxInvoiceD::getWarningStatusDesc, "已处理");
        updateWrapper.set(AdsMatHyxtStampTaxInvoiceD::getUpdateTime, new Date());
        updateWrapper.set(AdsMatHyxtStampTaxInvoiceD::getWarningRemark, warningRemark);
        this.update(updateWrapper);
    }

    @Override
    public void batchUpdateIsWarning(Integer isWarning) {
        LambdaUpdateWrapper<AdsMatHyxtStampTaxInvoiceD> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.set(AdsMatHyxtStampTaxInvoiceD::getIsWarning, isWarning);
        updateWrapper.set(AdsMatHyxtStampTaxInvoiceD::getWarningType, "");
        this.update(updateWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R updateBusinessType(AdsMatHyxtStampTaxInvoiceD invoiceD) {
        if (StringUtils.isNotBlank(invoiceD.getId())) {
            LambdaUpdateWrapper<AdsMatHyxtStampTaxInvoiceD> updateWrapper = Wrappers.lambdaUpdate();
            if (StringUtils.isNotBlank(invoiceD.getBusinessTypeCode())) {
                updateWrapper.eq(AdsMatHyxtStampTaxInvoiceD::getId, invoiceD.getId());
                updateWrapper.set(AdsMatHyxtStampTaxInvoiceD::getBusinessType, invoiceD.getBusinessType());
                updateWrapper.set(AdsMatHyxtStampTaxInvoiceD::getBusinessTypeCode, invoiceD.getBusinessTypeCode());
            } else {
                updateWrapper.eq(AdsMatHyxtStampTaxInvoiceD::getId, invoiceD.getId());
                updateWrapper.set(AdsMatHyxtStampTaxInvoiceD::getBusinessType, "");
                updateWrapper.set(AdsMatHyxtStampTaxInvoiceD::getBusinessTypeCode, "");
            }
            updateWrapper.set(AdsMatHyxtStampTaxInvoiceD::getUpdateTime, new Date());
            this.update(updateWrapper);
        }
        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R batchUpdateBusinessType(StampTaxBatchUpdateBusinessTypePO param) {
        List<String> ids = param.getIds();
        if (ObjectUtils.isNotEmpty(ids) && !ids.isEmpty()) {
            List<AdsMatHyxtStampTaxInvoiceD> list = this.selectByIds(param.getIds());
            for (AdsMatHyxtStampTaxInvoiceD invoiceD : list) {
                invoiceD.setBusinessTypeCode(param.getBusinessTypeCode());
                invoiceD.setBusinessType(param.getBusinessType());
            }

            if (!list.isEmpty()) {
                this.saveOrUpdateBatch(list);
            }
        }
        return R.ok();
    }

    @Override
    public List<AdsMatHyxtStampTaxInvoiceD> getByBusinessCode(String businessTypeCode, List<AdsMatHyxtStampTaxInvoiceD> list) {
        List<AdsMatHyxtStampTaxInvoiceD> result = new ArrayList<>();
        for (AdsMatHyxtStampTaxInvoiceD invoiceD : list) {
            String bc = invoiceD.getBusinessTypeCode();
            if (StringUtils.isNotBlank(bc) && businessTypeCode.equals(bc)) {
                result.add(invoiceD);
            }
        }
        return result;
    }

    @Override
    public int countNum(String orgNo, String date) {
        String[] startAndEnd = DateUtil.getMonthStartAndEnd(date);
        LambdaQueryWrapper<AdsMatHyxtStampTaxInvoiceD> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.like(AdsMatHyxtStampTaxInvoiceD::getCreateUserOrgNo, orgNo);
        if (null != startAndEnd) {
            queryWrapper.ge(AdsMatHyxtStampTaxInvoiceD::getMakeDate, startAndEnd[0]);
            queryWrapper.le(AdsMatHyxtStampTaxInvoiceD::getMakeDate, startAndEnd[1]);
        }
        queryWrapper.eq(AdsMatHyxtStampTaxInvoiceD::getIsDeleted, 0);
        return Math.toIntExact(baseMapper.selectCount(queryWrapper));
    }

    @Override
    public int countWarningNum(String orgNo, String date) {
        String[] startAndEnd = DateUtil.getMonthStartAndEnd(date);
        LambdaQueryWrapper<AdsMatHyxtStampTaxInvoiceD> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.ge(AdsMatHyxtStampTaxInvoiceD::getIsWarning, 1);
        queryWrapper.like(AdsMatHyxtStampTaxInvoiceD::getCreateUserOrgNo, orgNo);
        if (null != startAndEnd) {
            queryWrapper.ge(AdsMatHyxtStampTaxInvoiceD::getMakeDate, startAndEnd[0]);
            queryWrapper.le(AdsMatHyxtStampTaxInvoiceD::getMakeDate, startAndEnd[1]);
        }
        queryWrapper.eq(AdsMatHyxtStampTaxInvoiceD::getIsDeleted, 0);
        return Math.toIntExact(baseMapper.selectCount(queryWrapper));
    }

    private List<AdsMatHyxtStampTaxInvoiceD> selectByIds(List<String> ids) {
        LambdaQueryWrapper<AdsMatHyxtStampTaxInvoiceD> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.in(AdsMatHyxtStampTaxInvoiceD::getId, ids);
        return this.baseMapper.selectList(queryWrapper);
    }

}
