package com.qianhe.zqcz.pwxx.service.impl;

import com.qianhe.common.exception.BusinessException;
import com.qianhe.common.utils.SecurityUtils;
import com.qianhe.common.utils.StringUtils;
import com.qianhe.zqcz.jcrw.mapper.ZqczJcrwMapper;
import com.qianhe.zqcz.pwxx.domain.ZqczPwxx;
import com.qianhe.zqcz.pwxx.domain.ZqczPwxxQuery;
import com.qianhe.zqcz.pwxx.domain.ZqczPwxxVo;
import com.qianhe.zqcz.pwxx.mapper.ZqczPwxxMapper;
import com.qianhe.zqcz.pwxx.service.ZqczPwxxService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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 java.io.IOException;
import java.util.*;

@Slf4j
@Service
public class ZqczPwxxServiceImpl implements ZqczPwxxService {
    @Autowired
    private ZqczPwxxMapper zqczPwxxMapper;


    /**
     * 条件查询
     */
    @Override
    public List<ZqczPwxxVo> list(ZqczPwxxQuery zqczPwxxQuery) {
        List<ZqczPwxxVo> dataList = zqczPwxxMapper.list(zqczPwxxQuery);
        return dataList;
    }

    /**
     * 查询详情
     */
    @Override
    public ZqczPwxxVo info(Long pwid) {
        ZqczPwxxVo info = zqczPwxxMapper.info(pwid);
        return info;
    }

    /**
     * 新增
     */
    @Override
    public int add(ZqczPwxx zqczPwxx, String username) {
        zqczPwxx.setCreateBy(username);
        zqczPwxx.setUpdateBy(username);
        zqczPwxx.setCreateTime(new Date());
        return zqczPwxxMapper.add(zqczPwxx);
    }

    /**
     * 修改
     */
    @Override
    public int edit(ZqczPwxx zqczPwxx, String username) {
        zqczPwxx.setUpdateBy(username);
        return zqczPwxxMapper.edit(zqczPwxx);
    }

    /**
     * 删除
     */
    @Override
    public int delete(Long[] ids) {
        return zqczPwxxMapper.delete(ids);
    }

    /**
     * 导入
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int importExcel(Long jcrwid, MultipartFile file) {
        String username = SecurityUtils.getLoginUser().getUsername();  // 当前用户

        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(file.getInputStream());
            XSSFSheet sheet = workbook.getSheetAt(0);
            int lastRowNum = sheet.getLastRowNum();
            List<ZqczPwxx> dataList = new ArrayList<>();
            for (int i = 0; i <= lastRowNum; i++) {
                // 跳过标题行
                if (i == 0) {
                    continue;
                }
                XSSFRow row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }
                // 基层单位名称（A列）
                String pwmc = new DataFormatter().formatCellValue(row.getCell(0));
                if (StringUtils.isEmpty(pwmc)) {
                    throw new BusinessException("导入失败，第" + (i + 1) + "评委名称不能为空");
                }
                // 封装数据
                ZqczPwxx zqczPwxx = ZqczPwxx.builder()
                        .jcrwid(jcrwid)
                        .pwmc(pwmc)
                        .createBy(username)
                        .createTime(new Date())
                        .updateBy(username).build();

                dataList.add(zqczPwxx);
            }

            if (Optional.ofNullable(dataList).orElse(Collections.emptyList()).isEmpty()) {
                throw new BusinessException("读取Excel文件失败，上传数据为空");
            }

            // 先根据jcrwid删除之前的评委信息
            zqczPwxxMapper.deleteByJcrwid(jcrwid);

            // 在批量插入
            int pwSize = zqczPwxxMapper.batchAdd(dataList);
            return pwSize;
        } catch (BusinessException e) {
            throw e;
        } catch (IOException e) {
            throw new BusinessException("读取Excel文件失败，请检查文件格式");
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException ignored) {
                }
            }
        }
    }
}
