package com.chinaweal.aiccs.aiccs.expelled.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.chinaweal.aiccs.aiccs.expelled.entity.EntBaseExpelledInfo;
import com.chinaweal.aiccs.aiccs.expelled.entity.ExpelledEntInfo;
import com.chinaweal.aiccs.aiccs.expelled.entity.ExpelledResultInfo;
import com.chinaweal.aiccs.aiccs.expelled.mapper.EntBaseExpelledInfoMapper;
import com.chinaweal.aiccs.aiccs.expelled.service.IEntBaseExpelledInfoService;
import com.chinaweal.aiccs.aiccs.expelled.service.IExpelledEntInfoService;
import com.chinaweal.aiccs.aiccs.expelled.service.IExpelledResultInfoService;
import com.chinaweal.aiccs.aiccs.expelled.vo.EntBaseExpelledInfoExcelVo;
import com.chinaweal.aiccs.aiccs.punishment.util.ExcelIePortUtils;
import com.chinaweal.aiccs.aiccs.punishment.util.ExcelListener;
import com.chinaweal.aiccs.utils.BeanUtil;
import com.chinaweal.youfool.framework.springboot.base.query.BaseQuery;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;

/**
 * @Description: 市场主体拟除名名单信息表实现类
 * @Author: TiAmo-cc
 * @Email: 1049976610@qq.com
 * @Date: 2026/1/3 18:10
 */
@Service
public class EntBaseExpelledInfoServiceImpl extends ServiceImpl<EntBaseExpelledInfoMapper, EntBaseExpelledInfo> implements IEntBaseExpelledInfoService {

    @Value("${excelTemplate.expelled.path}")
    private String expelledExcelTemplatePath;
    @Value("${excelTemplate.expelled.name}")
    private String expelledExcelTemplateName;

    @Resource
    private IExpelledResultInfoService expelledResultInfoService;
    @Resource
    private IExpelledEntInfoService expelledEntInfoService;

    @Override
    public IPage<EntBaseExpelledInfo> listEntBaseExpelledInfo(BaseQuery<EntBaseExpelledInfo> query) {
        EntBaseExpelledInfo entity = query.getEntity(EntBaseExpelledInfo.class);
        Page<EntBaseExpelledInfo> page = query.getPage();
        LambdaQueryWrapper<EntBaseExpelledInfo> wrapper = Wrappers.<EntBaseExpelledInfo>lambdaQuery()
                .like(StringUtils.isNotBlank(entity.getSearchEntName()), EntBaseExpelledInfo::getEntName, entity.getSearchEntName())
                .eq(StringUtils.isNotBlank(entity.getSearchUscc()), EntBaseExpelledInfo::getUscc, entity.getSearchUscc())
                .eq(EntBaseExpelledInfo::getState, "2")
                .eq(EntBaseExpelledInfo::getIsDelete, "0");
        return page(page, wrapper);
    }

    @Override
    public void saveEntBaseExpelledInfo(EntBaseExpelledInfo query) {
        EntBaseExpelledInfo expelledInfo = getEntBaseExpelledInfoByUscc(query.getUscc());
        if (expelledInfo == null) {
            expelledInfo = new EntBaseExpelledInfo();
            expelledInfo.setId(UUID.randomUUID().toString());
            expelledInfo.setState("2"); // 默认有效
            expelledInfo.setIsDelete("0");
        }
        BeanUtil.copyBean(query, expelledInfo);
        saveOrUpdate(expelledInfo);
    }

    @Override
    public EntBaseExpelledInfo getEntBaseExpelledInfoByUscc(String uscc) {
        return getOne(new LambdaQueryWrapper<EntBaseExpelledInfo>().eq(EntBaseExpelledInfo::getUscc, uscc).eq(EntBaseExpelledInfo::getIsDelete, "0"));
    }

    @Override
    public void downloadTemplate(HttpServletResponse response) {
        // 获取流
        InputStream is = null;
        OutputStream os = null;
        try {
            // 获取模板文件
            ClassPathResource resource = new ClassPathResource(expelledExcelTemplatePath + expelledExcelTemplateName);
            File file = resource.getFile();
            is = new FileInputStream(file);
            os = response.getOutputStream();
            String fileName = new String(expelledExcelTemplateName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            // 设置：当浏览器收到这份资源的时候，以下载的方式提醒用户，而不是直接显示
            response.setHeader("Content-Disposition", "attachment;  filename=\"" + fileName + "\"");
            byte[] buffer = new byte[4096];
            int len;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("下载批量导入excel模板时发生异常:{}=", e);
            return;
        } finally {
            try {
                os.close();
                is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void batchImportExpelledInfo(MultipartFile annex) throws IOException {
        ExcelListener excelListener = ExcelIePortUtils.getExcelListener(annex, new EntBaseExpelledInfoExcelVo(), 1, 1);
        Object objects = excelListener.getDatas();
        if (objects == null) {
            throw new BusinessException("读取不到数据，请检查上传的附件是否有录入数据");
        }
        List<EntBaseExpelledInfoExcelVo> datas =  (List<EntBaseExpelledInfoExcelVo>) objects;
        if (CollectionUtils.isEmpty(datas)) {
            throw new BusinessException("读取不到数据，请检查上传的附件是否有录入数据");
        }
        for (EntBaseExpelledInfoExcelVo excelVo : datas) {
            EntBaseExpelledInfo expelledInfo = new EntBaseExpelledInfo();
            BeanUtil.copyBean(excelVo, expelledInfo);
            saveEntBaseExpelledInfo(expelledInfo);
        }
    }

    @Override
    public void syncEntBaseExpelledInfo(String resultId, String state) {
        ExpelledResultInfo resultInfo = expelledResultInfoService.getById(resultId);
        if (resultInfo == null) {
            return;
        }
        ExpelledEntInfo entInfo = expelledEntInfoService.getById(resultInfo.getEntId());
        if (entInfo == null) {
            return;
        }
        EntBaseExpelledInfo expelledInfo = getById(entInfo.getExpelledId());
        if (expelledInfo == null) {
            return;
        }
        expelledInfo.setState(state);
        saveOrUpdate(expelledInfo);
    }
}
