package com.ruoyi.hywz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.AdsMatHyxtStampTaxZhptInvoiceD;
import com.ruoyi.hywz.entity.po.IdsPO;
import com.ruoyi.hywz.listener.ImportExcelHelper;
import com.ruoyi.hywz.mapper.AdsMatHyxtStampTaxZhptInvoiceDMapper;
import com.ruoyi.hywz.service.IAdsMatHyxtStampTaxZhptInvoiceDService;
import com.ruoyi.hywz.utils.DateUtil;
import com.ruoyi.hywz.utils.IdGen;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
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.Date;
import java.util.List;

/**
 * <p>
 * 【印花税】【智慧平台】发票信息表 服务实现类
 * </p>
 *
 * @author mybatisplus-generator
 * @date 2024-08-23 11:15:50
 */
@Service
public class AdsMatHyxtStampTaxZhptInvoiceDServiceImpl extends ServiceImpl<AdsMatHyxtStampTaxZhptInvoiceDMapper, AdsMatHyxtStampTaxZhptInvoiceD> implements IAdsMatHyxtStampTaxZhptInvoiceDService {

    @Override
    public Page<AdsMatHyxtStampTaxZhptInvoiceD> queryPage(Long pageSize, Long pageNo, AdsMatHyxtStampTaxZhptInvoiceD param) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Page<AdsMatHyxtStampTaxZhptInvoiceD> page = new Page<>();
        page.setSize(pageSize);
        page.setCurrent(pageNo);

        LambdaQueryWrapper<AdsMatHyxtStampTaxZhptInvoiceD> queryWrapper = Wrappers.lambdaQuery();
        // 非管理员只能查询自己单位导入的数据
        if (!loginUser.getUsername().equals("admin")) {
            queryWrapper.like(AdsMatHyxtStampTaxZhptInvoiceD::getCreateUserOrgNo, loginUser.getOrgNo());
        }
        queryWrapper.eq(AdsMatHyxtStampTaxZhptInvoiceD::getIsDeleted, 0);

        if (null != param) {
            queryWrapper.like(StringUtils.isNotBlank(param.getInvoiceType()), AdsMatHyxtStampTaxZhptInvoiceD::getInvoiceType, param.getInvoiceType());
            queryWrapper.like(StringUtils.isNotBlank(param.getInvoiceStatus()), AdsMatHyxtStampTaxZhptInvoiceD::getInvoiceStatus, param.getInvoiceStatus());
            queryWrapper.like(StringUtils.isNotBlank(param.getInvoiceCode()), AdsMatHyxtStampTaxZhptInvoiceD::getInvoiceCode, param.getInvoiceCode());
            queryWrapper.like(StringUtils.isNotBlank(param.getInvoiceNumber()), AdsMatHyxtStampTaxZhptInvoiceD::getInvoiceNumber, param.getInvoiceNumber());
            queryWrapper.like(StringUtils.isNotBlank(param.getSellerName()), AdsMatHyxtStampTaxZhptInvoiceD::getSellerName, param.getSellerName());
            queryWrapper.like(StringUtils.isNotBlank(param.getVoucherNo()), AdsMatHyxtStampTaxZhptInvoiceD::getVoucherNo, param.getVoucherNo());
        }

        queryWrapper.orderByDesc(AdsMatHyxtStampTaxZhptInvoiceD::getCreateTime);
        return this.page(page, queryWrapper);
    }

    @Override
    public void downloadTemplate(HttpServletResponse response) {
        String filePath = "excelTemplate/stampTax/stampTaxZhptInvoiceImport.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 deleteOne(IdsPO param) {
        LambdaQueryWrapper<AdsMatHyxtStampTaxZhptInvoiceD> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AdsMatHyxtStampTaxZhptInvoiceD::getId, param.getId());
        baseMapper.delete(queryWrapper);
    }

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

    @Override
    public R importData(MultipartFile file) throws IOException {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        ImportExcelHelper<AdsMatHyxtStampTaxZhptInvoiceD> helper = new ImportExcelHelper<>();
        List<AdsMatHyxtStampTaxZhptInvoiceD> list = helper.getList(file.getInputStream(), AdsMatHyxtStampTaxZhptInvoiceD.class, 0, 1);
        if (list.size() == 0) {
            return R.fail("导入失败，未解析到正确数据!");
        }
        Date date = new Date();
        for (AdsMatHyxtStampTaxZhptInvoiceD invoiceD : list) {
            invoiceD.setId(IdGen.get32UUID());
            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());
        }
        this.saveBatch(list);
        return R.ok();
    }

    @Override
    public boolean checkIsWarning1(String invoiceNumber) {
        LambdaQueryWrapper<AdsMatHyxtStampTaxZhptInvoiceD> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AdsMatHyxtStampTaxZhptInvoiceD::getInvoiceNumber, invoiceNumber);
        queryWrapper.isNotNull(AdsMatHyxtStampTaxZhptInvoiceD::getVoucherNo);
        List<AdsMatHyxtStampTaxZhptInvoiceD> list = baseMapper.selectList(queryWrapper);
        if (list.isEmpty()) {
            return false;
        }
        return true;
    }

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