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

import com.qianhe.common.constant.MtConstant;
import com.qianhe.common.exception.BusinessException;
import com.qianhe.common.utils.StringUtils;
import com.qianhe.zqcz.jcdw.domain.ZqczJcdw;
import com.qianhe.zqcz.jcdw.domain.ZqczJcdwQuery;
import com.qianhe.zqcz.jcdw.domain.ZqczJcdwVo;
import com.qianhe.zqcz.jcdw.mapper.ZqczJcdwMapper;
import com.qianhe.zqcz.jcdw.service.ZqczJcdwService;
import com.qianhe.zqcz.zsrw.domain.ZqczZsrw;
import com.qianhe.zqcz.zsrw.mapper.ZqczZsrwMapper;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFRow;
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.ArrayList;
import java.util.List;

@Service
public class ZqczJcdwServiceImpl implements ZqczJcdwService {
    @Autowired
    private ZqczJcdwMapper zqczJcdwMapper;
    @Autowired
    private ZqczZsrwMapper zqczZsrwMapper;

    /**
     * 分页查询
     */
    @Override
    public List<ZqczJcdwVo> list(ZqczJcdwQuery zqczJcdwQuery) {
        List<ZqczJcdwVo> dataList = zqczJcdwMapper.list(zqczJcdwQuery);
        return dataList;
    }

    /**
     * 查询详情
     */
    @Override
    public ZqczJcdwVo info(Long jcdwid) {
        ZqczJcdwVo info = zqczJcdwMapper.info(jcdwid);
        return info;
    }

    /**
     * 新增
     */
    @Override
    public int add(ZqczJcdw zqczJcdw) {
        return zqczJcdwMapper.add(zqczJcdw);
    }

    /**
     * 修改
     */
    @Override
    public int edit(ZqczJcdw zqczJcdw) {
        return zqczJcdwMapper.edit(zqczJcdw);
    }

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

    /**
     * 上传文件 批量新增
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int batchAdd(Long zsrwid, MultipartFile file) {
        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(file.getInputStream());
            XSSFSheet sheet = workbook.getSheetAt(0);
            int lastRowNum = sheet.getLastRowNum();
            List<ZqczJcdw> list = new ArrayList<>();
            for (int i = 0; i <= lastRowNum; i++) {
                // 跳过标题行
                if (i == 0) {
                    continue;
                }
                XSSFRow row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }
                // 基层单位名称（A列）
                String jcdwmc = new DataFormatter().formatCellValue(row.getCell(0));
                if (StringUtils.isEmpty(jcdwmc)) {
                    throw new BusinessException("导入失败，第" + (i + 1) + "行基层单位名称不能为空");
                }
                // 基层单位类型（B列），Excel填中文名称，通过字典转为数据库编码
                String jczzlxName = new DataFormatter().formatCellValue(row.getCell(1)).trim();
                String jczzlx = MtConstant.ZQCZ_JCDWLX_MAP.get(jczzlxName);
                if (jczzlx == null) {
                    throw new BusinessException("导入失败，第" + (i + 1) + "行基层单位类型必须为'采油'或'集输'");
                }
                ZqczJcdw jcdw = new ZqczJcdw();
                jcdw.setZsrwid(zsrwid);
                jcdw.setJcdwmc(jcdwmc.trim());
                jcdw.setJczzlx(jczzlx);
                list.add(jcdw);
            }
            if (list.isEmpty()) {
                throw new BusinessException("导入失败，文件中没有有效数据");
            }
            zqczJcdwMapper.deleteByZsrwid(zsrwid);  // 先通过 直属任务ID 删除所在基层组织
            int glqsl = zqczJcdwMapper.batchAdd(list);// 在新增
            zqczZsrwMapper.edit(ZqczZsrw.builder().zsrwid(zsrwid).glqsl(glqsl).build());  // 同步基层单位总数量
            return glqsl;  // 在新增
        } catch (BusinessException e) {
            throw e;
        } catch (IOException e) {
            throw new BusinessException("读取Excel文件失败，请检查文件格式");
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException ignored) {
                }
            }
        }
    }

    /**
     * 通过直属任务ID 删除
     */
    @Override
    public int deleteZsrwid(Long zsrwid) {
        return zqczJcdwMapper.deleteByZsrwid(zsrwid);
    }
}
