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

import com.qianhe.common.constant.MtConstant;
import com.qianhe.common.exception.BusinessException;
import com.qianhe.common.utils.SecurityUtils;
import com.qianhe.common.utils.StringUtils;
import com.qianhe.zqcz.pwxx.domain.ZqczPwxx;
import com.qianhe.zqcz.ryxx.domain.ZqczRyxx;
import com.qianhe.zqcz.ryxx.domain.ZqczRyxxQuery;
import com.qianhe.zqcz.ryxx.domain.ZqczRyxxVo;
import com.qianhe.zqcz.ryxx.mapper.ZqczRyxxMapper;
import com.qianhe.zqcz.ryxx.service.ZqczRyxxService;
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 ZqczRyxxServiceImpl implements ZqczRyxxService {
    @Autowired
    private ZqczRyxxMapper zqczRyxxMapper;

    /**
     * 条件查询
     */
    @Override
    public List<ZqczRyxxVo> list(ZqczRyxxQuery zqczRyxxQuery) {
        List<ZqczRyxxVo> dataList = zqczRyxxMapper.list(zqczRyxxQuery);
        return dataList;
    }

    /**
     * 查询详情
     */
    @Override
    public ZqczRyxxVo info(Long id) {
        ZqczRyxxVo info = zqczRyxxMapper.info(id);
        return info;
    }

    /**
     * 新增
     */
    @Override
    public int add(ZqczRyxx zqczRyxx, String username) {
        zqczRyxx.setCreate_by(username);
        zqczRyxx.setUpdate_by(username);
        zqczRyxx.setCreate_time(new Date());
        return zqczRyxxMapper.add(zqczRyxx);
    }

    /**
     * 修改
     */
    @Override
    public int edit(ZqczRyxx zqczRyxx, String username) {
        zqczRyxx.setUpdate_by(username);
        return zqczRyxxMapper.edit(zqczRyxx);
    }

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

    /**
     * 根据基础任务ID删除
     */
    @Override
    public int deleteByJcrwid(Long jcrwid) {
        return zqczRyxxMapper.deleteByJcrwid(jcrwid);
    }

    /**
     * 导入
     */
    @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<ZqczRyxx> 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 rymc = new DataFormatter().formatCellValue(row.getCell(0)).trim();
                if (StringUtils.isEmpty(rymc)) {
                    throw new BusinessException("导入失败，第" + (i + 1) + "行，人员名称不能为空");
                }
                // 单位（B列）
                String dwmc = new DataFormatter().formatCellValue(row.getCell(1)).trim();
                if (StringUtils.isEmpty(dwmc)) {
                    throw new BusinessException("导入失败，第" + (i + 1) + "行，单位不能为空");
                }
                // 分类（C列）
                String ryflName = new DataFormatter().formatCellValue(row.getCell(2)).trim();
                String ryfl = MtConstant.ZQCZ_RYLX_MAP.get(ryflName);
                if (StringUtils.isEmpty(ryfl)) {
                    throw new BusinessException("导入失败，第" + (i + 1) + "行，分类必须为'领导班子'、'三室一中心'、'班站'");
                }
                // 封装数据
                ZqczRyxx ryxxInfo = ZqczRyxx.builder()
                        .jcrwid(jcrwid)
                        .rymc(rymc)
                        .dwmc(dwmc)
                        .ryfl(ryfl)
                        .build();
                dataList.add(ryxxInfo);
            }

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

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

            // 在批量插入
            int pwSize = zqczRyxxMapper.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) {
                }
            }
        }
    }
}
