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.entity.AdsMatHyxtStampTaxContractD;
import com.ruoyi.hywz.entity.AdsMatHyxtStampTaxInvoiceD;
import com.ruoyi.hywz.entity.AdsMatHyxtStampTaxItemD;
import com.ruoyi.hywz.entity.po.HomeStampTaxCountPO;
import com.ruoyi.hywz.entity.po.IdsPO;
import com.ruoyi.hywz.entity.po.StampTaxBatchUpdateTaxItemPO;
import com.ruoyi.hywz.listener.ImportExcelHelper;
import com.ruoyi.hywz.mapper.AdsMatHyxtStampTaxContractDMapper;
import com.ruoyi.hywz.service.IAdsMatHyxtStampTaxContractDService;
import com.ruoyi.hywz.service.IAdsMatHyxtStampTaxItemDService;
import com.ruoyi.hywz.utils.AmountUtil;
import com.ruoyi.hywz.utils.DateUtil;
import com.ruoyi.hywz.utils.IdGen;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
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.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 合同信息表 服务实现类
 * </p>
 *
 * @author mybatisplus-generator
 * @date 2024-07-14 10:07:56
 */
@Service
public class AdsMatHyxtStampTaxContractDServiceImpl extends ServiceImpl<AdsMatHyxtStampTaxContractDMapper,AdsMatHyxtStampTaxContractD> implements IAdsMatHyxtStampTaxContractDService {

    @Autowired
    private IAdsMatHyxtStampTaxItemDService adsMatHyxtStampTaxItemDService;

    @Override
    public List<AdsMatHyxtStampTaxContractD> getList(String startDate, String endDate, String orgNo) {
        LambdaQueryWrapper<AdsMatHyxtStampTaxContractD> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AdsMatHyxtStampTaxContractD::getCreateUserOrgNo, orgNo);
        queryWrapper.eq(AdsMatHyxtStampTaxContractD::getIsDeleted, 0);
//        queryWrapper.ge(AdsMatHyxtStampTaxContractD::getEffectiveDate, startDate);
//        queryWrapper.le(AdsMatHyxtStampTaxContractD::getEffectiveDate, endDate);
        queryWrapper.apply("date_format (effective_date,'%Y-%m-%d') >= date_format ({0},'%Y-%m-%d')", startDate)
                .apply("date_format (effective_date,'%Y-%m-%d') <= date_format ({0},'%Y-%m-%d')", endDate);
        return this.list(queryWrapper);
    }

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

        LambdaQueryWrapper<AdsMatHyxtStampTaxContractD> queryWrapper = Wrappers.lambdaQuery();
        // 非管理员只能查询自己单位导入的数据
        if (!loginUser.getUsername().equals("admin")) {
            queryWrapper.like(AdsMatHyxtStampTaxContractD::getCreateUserOrgNo, loginUser.getOrgNo());
        }
        queryWrapper.eq(AdsMatHyxtStampTaxContractD::getIsDeleted, 0);
        if (null != param) {
            queryWrapper.like(StringUtils.isNotBlank(param.getContractName()), AdsMatHyxtStampTaxContractD::getContractName, param.getContractName());
            queryWrapper.like(StringUtils.isNotBlank(param.getContractType()), AdsMatHyxtStampTaxContractD::getContractType, param.getContractType());
            queryWrapper.like(StringUtils.isNotBlank(param.getCounterparty()), AdsMatHyxtStampTaxContractD::getCounterparty, param.getCounterparty());
            queryWrapper.eq(StringUtils.isNotBlank(param.getStampTaxItemId()), AdsMatHyxtStampTaxContractD::getStampTaxItemId, param.getStampTaxItemId());
            queryWrapper.like(StringUtils.isNotBlank(param.getCreateUserOrgNo()), AdsMatHyxtStampTaxContractD::getCreateUserOrgNo, param.getCreateUserOrgNo());
            queryWrapper.eq(StringUtils.isNotBlank(param.getWarningType()), AdsMatHyxtStampTaxContractD::getWarningType, param.getWarningType());
            queryWrapper.eq(StringUtils.isNotBlank(param.getTaxationFlag()), AdsMatHyxtStampTaxContractD::getTaxationFlag, param.getTaxationFlag());
            if (StringUtils.isNotBlank(param.getStartDate()) && StringUtils.isNotBlank(param.getEndDate())) {
//                queryWrapper.ge(AdsMatHyxtStampTaxContractD::getEffectiveDate, param.getStartDate());
//                queryWrapper.le(AdsMatHyxtStampTaxContractD::getEffectiveDate, param.getEndDate());
                queryWrapper.apply("date_format (effective_date,'%Y-%m-%d') >= date_format ({0},'%Y-%m-%d')", param.getStartDate())
                        .apply("date_format (effective_date,'%Y-%m-%d') <= date_format ({0},'%Y-%m-%d')", param.getEndDate());
            }
            if (StringUtils.isNotBlank(param.getHomeOrgNo())) {
                queryWrapper.like(StringUtils.isNotBlank(param.getCreateUserOrgNo()), AdsMatHyxtStampTaxContractD::getCreateUserOrgNo, param.getCreateUserOrgNo());
            }
            if (StringUtils.isNotBlank(param.getHomeDate())) {
                String[] startAndEnd = DateUtil.getMonthStartAndEnd(param.getHomeDate());
                if (null != startAndEnd) {
//                    queryWrapper.ge(AdsMatHyxtStampTaxContractD::getEffectiveDate, startAndEnd[0]);
//                    queryWrapper.le(AdsMatHyxtStampTaxContractD::getEffectiveDate, startAndEnd[1]);


                    queryWrapper.apply("date_format (effective_date,'%Y-%m-%d') >= date_format ({0},'%Y-%m-%d')", startAndEnd[0])
                       .apply("date_format (effective_date,'%Y-%m-%d') <= date_format ({0},'%Y-%m-%d')", startAndEnd[1]);
                }
            }
            if (ObjectUtils.isNotEmpty(param.getIsWarningSelect())) {
                Integer isWarningSelect = param.getIsWarningSelect();
                if (isWarningSelect == 1) {
                    queryWrapper.gt(AdsMatHyxtStampTaxContractD::getIsWarning, 0);
                }
                if (isWarningSelect == 0) {
                    queryWrapper.eq(AdsMatHyxtStampTaxContractD::getIsWarning, 0);
                }
            }
        }

        queryWrapper.orderByAsc(AdsMatHyxtStampTaxContractD::getCreateUserOrgNo);
        queryWrapper.orderByDesc(AdsMatHyxtStampTaxContractD::getIsWarning);
        queryWrapper.orderByDesc(AdsMatHyxtStampTaxContractD::getCreateTime);

        return this.page(page, queryWrapper);
    }

    @Override
    public R queryList(AdsMatHyxtStampTaxContractD param) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        LambdaQueryWrapper<AdsMatHyxtStampTaxContractD> queryWrapper = Wrappers.lambdaQuery();
        // 非管理员只能查询自己单位导入的数据
//        if (!loginUser.getUsername().equals("admin")) {
//            queryWrapper.like(AdsMatHyxtStampTaxContractD::getCreateUserOrgNo, loginUser.getOrgNo());
//        }
        queryWrapper.eq(AdsMatHyxtStampTaxContractD::getIsDeleted, 0);
        if (null != param) {
            queryWrapper.eq(StringUtils.isNotBlank(param.getId()), AdsMatHyxtStampTaxContractD::getId, param.getId());
            queryWrapper.eq(StringUtils.isNotBlank(param.getWarningType()), AdsMatHyxtStampTaxContractD::getWarningType, param.getWarningType());

            queryWrapper.like(StringUtils.isNotBlank(param.getContractType()), AdsMatHyxtStampTaxContractD::getContractType, param.getContractType());
        }
        return R.ok(this.list(queryWrapper));
    }

    /**
     * 下载模板
     */
    @Override
    public void downloadTemplate(HttpServletResponse response) {
        String filePath = "excelTemplate/stampTax/contractImport.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/stampTaxContractExport.xlsx";
        fis = Thread.currentThread().getContextClassLoader().getResourceAsStream(templateFileName);
        ops = response.getOutputStream();
        List<AdsMatHyxtStampTaxContractD> list = this.getList(warningType);
        int i = 0;
        for (AdsMatHyxtStampTaxContractD itemD : list) {
            i++;
            itemD.setNo(i);
        }

        //填充导出信息
        ExcelWriter excelWriter = EasyExcel.write(ops, AdsMatHyxtStampTaxContractD.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<AdsMatHyxtStampTaxContractD> getList(String warningType) {
        LambdaQueryWrapper<AdsMatHyxtStampTaxContractD> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AdsMatHyxtStampTaxContractD::getWarningType, warningType);
        queryWrapper.eq(AdsMatHyxtStampTaxContractD::getIsDeleted, 0);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     *
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R contractImport(MultipartFile file, HomeStampTaxCountPO param) throws IOException {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        ImportExcelHelper<AdsMatHyxtStampTaxContractD> helper = new ImportExcelHelper<>();
        List<AdsMatHyxtStampTaxContractD> list = helper.getList(file.getInputStream(), AdsMatHyxtStampTaxContractD.class, 0, 1);
        if (list.size() == 0) {
            return R.fail("导入失败，未解析到正确数据!");
        }
        Map<String, AdsMatHyxtStampTaxItemD> taxMap = adsMatHyxtStampTaxItemDService.getMap();

        // TODO 先删除日期区间的数据
        String[] startAndEnd = DateUtil.getMonthStartAndEnd(param.getHomeDate());
        this.deleteData(param.getHomeOrgNo(), startAndEnd[0], startAndEnd[1]);

        Date date = new Date();
        for (AdsMatHyxtStampTaxContractD contractD : list) {
            // 判断合同是否存在(根据合同名称)
            String dbId = this.checkIsExist(contractD.getContractCode());
            if (StringUtils.isNotBlank(dbId)) {
                contractD.setId(dbId);
            } else {
                contractD.setId(IdGen.get32UUID());
            }
            contractD.setCreateUser(loginUser.getUsername());
            contractD.setCreateUserId(String.valueOf(loginUser.getUserId()));
            contractD.setCreateUserName(loginUser.getUsername());
            contractD.setCreateTime(date);
//            contractD.setCreateUserOrgNo(loginUser.getOrgNo());
//            contractD.setCreateUserOrgName(loginUser.getOrgName());
            contractD.setCreateUserOrgNo(param.getHomeOrgNo());
            contractD.setCreateUserOrgName(param.getSelectName());

            // 匹配税目
            String contractType = contractD.getContractType();  // 合同类型
            String contractName = contractD.getContractName();  // 合同名称
            String taxRate = contractD.getTaxRate();
            BigDecimal preTaxAmount = AmountUtil.convert(contractD.getPreTaxAmount());  // 不含税金额
            if (StringUtils.isNotBlank(contractType)) {
                // 【顺序】优先租赁合同、承揽合同、建设工程合同（租赁合同匹配完，再匹配承揽合同、最后匹配建设工程合同）
                // ================================ 建设工程合同 ================================
                // 合同信息表“税率”为（0.09）且合同“不含税金额”不等于0
                if (StringUtils.isNotBlank(taxRate) && taxRate.contains("0.09") && preTaxAmount.compareTo(BigDecimal.ZERO) > 0) {// 建设工程合同
                    this.setStampTaxItem("c5", taxMap, contractD);
                }

                // ================================ 承揽合同 ================================
                // 合同信息表“合同名称”包含（检测）、(测试）、（检验）
                // 合同信息表“合同名称”包含（修理）、（维修）字段且“税率”为（0.13）、（0.03）或（0.01）
                else if (StringUtils.isNotBlank(contractName)) {//  承揽合同
                    if (contractName.contains("检测") || contractName.contains("测试") || contractName.contains("检验")) {
                        this.setStampTaxItem("c4", taxMap, contractD);
                    }
                    else if (contractName.contains("修理") || contractName.contains("维修")) {
                        if (StringUtils.isNotBlank(taxRate)) {
                            if (taxRate.contains("0.13") || taxRate.contains("0.03") || taxRate.contains("0.01")) {
                                this.setStampTaxItem("c4", taxMap, contractD);
                            }
                        }
                    }else { //非应税合同
                        this.setStampTaxItem("c20", taxMap, contractD);
                    }

                }

                // ================================ 租赁合同 ================================
                else if (contractType.contains("租赁服务")) {// 租赁合同
                    this.setStampTaxItem("c8", taxMap, contractD);
                }

                // ================================ 运输合同 ================================
                else if (contractType.contains("仓储运输")) {// 运输合同
                    this.setStampTaxItem("c6", taxMap, contractD);
                }

                // ================================ 买卖合同 ================================
                // 合同信息表“合同类型”为（物资买卖类合同）类型下“不含税金额”不等于0
                else if (contractType.contains("物资买卖类") && preTaxAmount.compareTo(BigDecimal.ZERO) > 0) {// 买卖合同
                    this.setStampTaxItem("c3", taxMap, contractD);
                }

                // ================================ 技术合同 ================================
//                else if (contractType.contains("技术服务类合同_研发") || contractType.contains("技术服务类合同_实施服务") && preTaxAmount.compareTo(BigDecimal.ZERO) > 0) {// 技术合同
                else if (contractType.contains("技术服务类合同") && preTaxAmount.compareTo(BigDecimal.ZERO) > 0) {// 技术合同
                    this.setStampTaxItem("c7", taxMap, contractD);
                }

                else if (contractType.contains("保管合同")) {// 保管合同
                    this.setStampTaxItem("c9", taxMap, contractD);
                }
                else if (contractType.contains("仓储合同")) {// 仓储合同
                    this.setStampTaxItem("c10", taxMap, contractD);
                }
                else if (contractType.contains("保险合同")) {// 财产保险合同
                    this.setStampTaxItem("c11", taxMap, contractD);
                }else { //非应税合同
                    this.setStampTaxItem("c20", taxMap, contractD);
                    contractD.setTaxationFlag("N");

                }
            }

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

    private void deleteData(String orgNo, String startDate, String endDate) {
        LambdaQueryWrapper<AdsMatHyxtStampTaxContractD> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AdsMatHyxtStampTaxContractD::getCreateUserOrgNo, orgNo);
//        queryWrapper.ge(AdsMatHyxtStampTaxContractD::getEffectiveDate, startDate);
//        queryWrapper.le(AdsMatHyxtStampTaxContractD::getEffectiveDate, endDate);
        queryWrapper.apply("date_format (effective_date,'%Y-%m-%d') >= date_format ({0},'%Y-%m-%d')", startDate)
                .apply("date_format (effective_date,'%Y-%m-%d') <= date_format ({0},'%Y-%m-%d')", endDate);
        baseMapper.delete(queryWrapper);
    }

    private String checkIsExist(String contractCode) {
        LambdaQueryWrapper<AdsMatHyxtStampTaxContractD> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AdsMatHyxtStampTaxContractD::getContractCode, contractCode);
        queryWrapper.eq(AdsMatHyxtStampTaxContractD::getIsDeleted, 0);
        List<AdsMatHyxtStampTaxContractD> list = baseMapper.selectList(queryWrapper);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0).getId();
    }

    private void setStampTaxItem(String key, Map<String, AdsMatHyxtStampTaxItemD> taxMap, AdsMatHyxtStampTaxContractD contractD) {
        AdsMatHyxtStampTaxItemD taxItemD = taxMap.get(key);
        contractD.setStampTaxItem(taxItemD.getItemName());
        contractD.setStampTaxItemId(taxItemD.getId());
        contractD.setStampTaxRate(taxItemD.getTaxRate());
        contractD.setTaxationFlag("Y");

        BigDecimal contractAmount = AmountUtil.convert(contractD.getContractAmount());
        BigDecimal preTaxAmount = AmountUtil.convert(contractD.getPreTaxAmount());
        BigDecimal taxRate = AmountUtil.convert(taxItemD.getTaxRate()).divide(new BigDecimal(1000));
        if (preTaxAmount.compareTo(BigDecimal.ZERO) > 0) {
            contractD.setTaxableAmount(preTaxAmount.multiply(taxRate).setScale(2, RoundingMode.HALF_UP).toString());
        } else {
            contractD.setTaxableAmount(contractAmount.multiply(taxRate).setScale(2, RoundingMode.HALF_UP).toString());
        }

    }

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

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

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

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

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R updateTax(AdsMatHyxtStampTaxContractD contractD) {
        if (StringUtils.isNotEmpty(contractD.getStampTaxItemId())) {
            AdsMatHyxtStampTaxItemD taxItemD = adsMatHyxtStampTaxItemDService.getById(contractD.getStampTaxItemId());
            if (ObjectUtils.isNotEmpty(taxItemD)) {
                this.setTax(contractD, taxItemD, new Date());
            }
        } else {
            contractD.setStampTaxItemId("");
            contractD.setStampTaxRate("");
            contractD.setStampTaxItem("");
            contractD.setTaxableAmount("");
            contractD.setTaxationFlag("N");
        }
        this.updateById(contractD);
        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R batchUpdateTax(StampTaxBatchUpdateTaxItemPO param) {
        String stampTaxItemId = param.getStampTaxItemId();
        if (StringUtils.isNotBlank(stampTaxItemId)) {
            AdsMatHyxtStampTaxItemD taxItemD = adsMatHyxtStampTaxItemDService.getById(stampTaxItemId);
            Date date = new Date();
            if (ObjectUtils.isNotEmpty(taxItemD)) {
                List<AdsMatHyxtStampTaxContractD> cList = this.selectByIds(param.getIds());
                for (AdsMatHyxtStampTaxContractD contractD : cList) {
                    this.setTax(contractD, taxItemD, date);
                }

                if (!cList.isEmpty()) {
                    this.saveOrUpdateBatch(cList);
                }
            }
        } else {
            LambdaUpdateWrapper<AdsMatHyxtStampTaxContractD> updateWrapper = Wrappers.lambdaUpdate();
            updateWrapper.in(AdsMatHyxtStampTaxContractD::getId, param.getIds());
            updateWrapper.set(AdsMatHyxtStampTaxContractD::getStampTaxItemId, "");
            updateWrapper.set(AdsMatHyxtStampTaxContractD::getStampTaxRate, "");
            updateWrapper.set(AdsMatHyxtStampTaxContractD::getStampTaxItem, "");
            updateWrapper.set(AdsMatHyxtStampTaxContractD::getTaxableAmount, "");
            updateWrapper.set(AdsMatHyxtStampTaxContractD::getTaxationFlag, "N");
            this.update(updateWrapper);
        }
        return R.ok();
    }

    @Override
    public int countNum(String orgNo, String date) {
        String[] startAndEnd = DateUtil.getMonthStartAndEnd(date);
        LambdaQueryWrapper<AdsMatHyxtStampTaxContractD> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.like(AdsMatHyxtStampTaxContractD::getCreateUserOrgNo, orgNo);
        if (null != startAndEnd) {
//            queryWrapper.ge(AdsMatHyxtStampTaxContractD::getEffectiveDate, startAndEnd[0]);
//            queryWrapper.le(AdsMatHyxtStampTaxContractD::getEffectiveDate, startAndEnd[1]);

            queryWrapper.apply("date_format (effective_date,'%Y-%m-%d') >= date_format ({0},'%Y-%m-%d')", startAndEnd[0])
                    .apply("date_format (effective_date,'%Y-%m-%d') <= date_format ({0},'%Y-%m-%d')", startAndEnd[1]);
        }
        queryWrapper.eq(AdsMatHyxtStampTaxContractD::getIsDeleted, 0);
        return Math.toIntExact(baseMapper.selectCount(queryWrapper));
    }

    @Override
    public int countWarningNum(String orgNo, String date) {
        String[] startAndEnd = DateUtil.getMonthStartAndEnd(date);
        LambdaQueryWrapper<AdsMatHyxtStampTaxContractD> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.ge(AdsMatHyxtStampTaxContractD::getIsWarning, 1);
        queryWrapper.like(AdsMatHyxtStampTaxContractD::getCreateUserOrgNo, orgNo);
        if (null != startAndEnd) {
//            queryWrapper.ge(AdsMatHyxtStampTaxContractD::getEffectiveDate, startAndEnd[0]);
//            queryWrapper.le(AdsMatHyxtStampTaxContractD::getEffectiveDate, startAndEnd[1]);
            queryWrapper.apply("date_format (effective_date,'%Y-%m-%d') >= date_format ({0},'%Y-%m-%d')", startAndEnd[0])
                    .apply("date_format (effective_date,'%Y-%m-%d') <= date_format ({0},'%Y-%m-%d')", startAndEnd[1]);
        }
        queryWrapper.eq(AdsMatHyxtStampTaxContractD::getIsDeleted, 0);
        return Math.toIntExact(baseMapper.selectCount(queryWrapper));
    }

    @Override
    public List<AdsMatHyxtStampTaxContractD> getWarnigList(String orgNo) {
        LambdaQueryWrapper<AdsMatHyxtStampTaxContractD> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.ge(AdsMatHyxtStampTaxContractD::getIsWarning, 1);
        queryWrapper.eq(AdsMatHyxtStampTaxContractD::getCreateUserOrgNo, orgNo);
        queryWrapper.eq(AdsMatHyxtStampTaxContractD::getIsDeleted, 0);
        return baseMapper.selectList(queryWrapper);
    }

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

    private void setTax(AdsMatHyxtStampTaxContractD contractD, AdsMatHyxtStampTaxItemD taxItemD, Date date) {
        contractD.setStampTaxItemId(taxItemD.getId());
        contractD.setStampTaxItem(taxItemD.getItemName());
        contractD.setStampTaxRate(taxItemD.getTaxRate());
        contractD.setTaxationFlag("Y");

        BigDecimal contractAmount = AmountUtil.convert(contractD.getContractAmount());
        BigDecimal preTaxAmount = AmountUtil.convert(contractD.getPreTaxAmount());
        BigDecimal taxRate = AmountUtil.convert(taxItemD.getTaxRate()).divide(new BigDecimal(1000));
        if (preTaxAmount.compareTo(BigDecimal.ZERO) > 0) {
            contractD.setTaxableAmount(preTaxAmount.multiply(taxRate).setScale(2, RoundingMode.HALF_UP).toString());
        } else {
            contractD.setTaxableAmount(contractAmount.multiply(taxRate).setScale(2, RoundingMode.HALF_UP).toString());
        }

        contractD.setUpdateTime(date);
    }

}
