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

import com.qianhe.common.constant.MtConstant;
import com.qianhe.common.enums.zqcz.ZqczCyzyGzcjEnum;
import com.qianhe.common.enums.zqcz.ZqczJszyGzcjEnum;
import com.qianhe.common.enums.zqcz.ZqczXmlbEnum;
import com.qianhe.common.enums.zqcz.ZqczXmzyEnum;
import com.qianhe.common.exception.BusinessException;
import com.qianhe.domain.ExcelCellConfig;
import com.qianhe.util.MtExcelImportUtils;
import com.qianhe.common.utils.SecurityUtils;
import com.qianhe.common.utils.StringUtils;
import com.qianhe.zqcz.xmgl.domain.ZqczXmgl;
import com.qianhe.zqcz.xmgl.domain.ZqczXmglQuery;
import com.qianhe.zqcz.xmgl.domain.ZqczXmglVo;
import com.qianhe.zqcz.xmgl.mapper.ZqczXmglMapper;
import com.qianhe.zqcz.xmgl.service.ZqczXmglService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.DataFormatter;
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.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ZqczXmglServiceImpl implements ZqczXmglService {
    @Autowired
    private ZqczXmglMapper zqczXmglMapper;


    /**
     * 条件查询
     */
    @Override
    public List<ZqczXmglVo> list(ZqczXmglQuery zqczXmglQuery) {
        List<ZqczXmglVo> dataList = zqczXmglMapper.list(zqczXmglQuery);
        return dataList;
    }

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

    /**
     * 校验参数合法性
     */
    private void checkParams(ZqczXmgl zqczXmgl) {
        if (StringUtils.isEmpty(zqczXmgl.getXmmc())) {
            throw new BusinessException("项目名称不能为空");
        }
        if (StringUtils.isEmpty(zqczXmgl.getXmzy())) {
            throw new BusinessException("项目专业不能为空");
        }
        if (!ZqczXmzyEnum.getAllCodes().contains(zqczXmgl.getXmzy())) {
            throw new BusinessException(String.format("项目专业必须为%s, 当前值 %s", ZqczXmzyEnum.getAllCodeNameStrWithSeparator(), zqczXmgl.getXmzy()));
        }
        if (StringUtils.isEmpty(zqczXmgl.getXmlb())) {
            throw new BusinessException("项目类别不能为空");
        }
        if (!ZqczXmlbEnum.getAllCodes().contains(zqczXmgl.getXmlb())) {
            throw new BusinessException(String.format("项目类别必须为%s, 当前值 %s", ZqczXmlbEnum.getAllCodeNameStrWithSeparator(), zqczXmgl.getXmlb()));
        }
        if (StringUtils.isEmpty(zqczXmgl.getGzcj())) {
            throw new BusinessException("工作场景不能为空");
        } else {
            if (MtConstant.ZQCZ_XMZY_CYZY_CODE.equals(zqczXmgl.getXmzy())) {
                ZqczCyzyGzcjEnum zqczCyzyGzcjEnum = ZqczCyzyGzcjEnum.getEnumByCode(zqczXmgl.getGzcj());
                if (zqczCyzyGzcjEnum == null) {
                    throw new BusinessException(String.format("工作场景必须为%s, 当前工作场景 %s", ZqczCyzyGzcjEnum.getAllCodeNameStrWithSeparator(), zqczXmgl.getGzcj()));
                }
            }
            if (MtConstant.ZQCZ_XMZY_JSZY_CODE.equals(zqczXmgl.getXmzy())) {
                ZqczJszyGzcjEnum jszyGzcjEnum = ZqczJszyGzcjEnum.getEnumByCode(zqczXmgl.getGzcj());
                if (jszyGzcjEnum == null) {
                    throw new BusinessException(String.format("工作场景必须为%s, 当前工作场景 %s", ZqczJszyGzcjEnum.getAllCodeNameStrWithSeparator(), zqczXmgl.getGzcj()));
                }
            }
        }
        if (zqczXmgl.getXmrs() == null || zqczXmgl.getXmrs() == 0) {
            throw new BusinessException("项目人数不能为空或0");
        }
    }

    /**
     * 新增
     */
    @Override
    public int add(ZqczXmgl zqczXmgl, String username) {
        checkParams(zqczXmgl);  // 校验入参
        zqczXmgl.setCreate_by(username);
        zqczXmgl.setUpdate_by(username);
        zqczXmgl.setCreate_time(new Date());
        return zqczXmglMapper.add(zqczXmgl);
    }

    /**
     * 修改
     */
    @Override
    public int edit(ZqczXmgl zqczXmgl, String username) {
        checkParams(zqczXmgl);  // 校验入参
        zqczXmgl.setUpdate_by(username);
        return zqczXmglMapper.edit(zqczXmgl);
    }

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

    private void importExcelCheck() {

    }

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

        // 定义通用校验规则
        List<ExcelCellConfig> cellConfigs = Arrays.asList(
                new ExcelCellConfig(0, "项目专业", true),  // 项目专业（A列）
                new ExcelCellConfig(1, "项目类别", true),  // 项目专业（B列）
                new ExcelCellConfig(2, "工作场景", true),  // 工作场景（C列）
                new ExcelCellConfig(3, "项目名称", true),  // 项目名称（D列）
                new ExcelCellConfig(4, "项目人数", true)  // 项目人数（E列）
        );

        return MtExcelImportUtils.importXlsx(file, true, (i, row) -> {
            Map<String, String> cellValueMap = MtExcelImportUtils.parseAndValidateCells(row, i, cellConfigs);

            // 项目专业处理
            String xmzyStr = cellValueMap.get("项目专业");
            if (!ZqczXmzyEnum.getAllNames().contains(xmzyStr)) {
                throw new BusinessException(String.format("第%s行，项目专业必须为%s, 当前值 %s", i + 1, ZqczXmzyEnum.getAllCodeNameStrWithSeparator(), xmzyStr));
            }
            String xmzy = ZqczXmzyEnum.getCodeByName(xmzyStr);

            // 项目类别处理
            String xmlbStr = cellValueMap.get("项目类别");
            if (!ZqczXmlbEnum.getAllNames().contains(xmlbStr)) {
                throw new BusinessException(String.format("第%s行，项目类别必须为%s, 当前值 %s", i + 1, ZqczXmlbEnum.getAllCodeNameStrWithSeparator(), xmlbStr));
            }
            String xmlb = ZqczXmlbEnum.getCodeByName(xmlbStr);

            // 工作场景处理
            String gzcjStr = cellValueMap.get("工作场景");
            String gzcj = "";
            if (MtConstant.ZQCZ_XMZY_CYZY_CODE.equals(xmzy)) {
                gzcj = ZqczCyzyGzcjEnum.getCodeByName(gzcjStr);
                if (StringUtils.isEmpty(gzcj)) {
                    throw new BusinessException(String.format("第%s行，工作场景必须为%s, 当前工作场景 %s", i + 1, ZqczCyzyGzcjEnum.getAllCodeNameStrWithSeparator(), gzcjStr));
                }
            }
            if (MtConstant.ZQCZ_XMZY_JSZY_CODE.equals(xmzy)) {
                gzcj = ZqczJszyGzcjEnum.getCodeByName(gzcjStr);
                if (gzcj == null) {
                    throw new BusinessException(String.format("第%s行，工作场景必须为%s, 当前工作场景 %s", i + 1, ZqczJszyGzcjEnum.getAllCodeNameStrWithSeparator(), gzcjStr));
                }
            }


            String xmmc = cellValueMap.get("项目名称");

            // 项目人数处理
            String xmrsStr = cellValueMap.get("项目人数");
            Integer xmrs = MtExcelImportUtils.safeParseInt(xmrsStr, "项目人数", i);

            ZqczXmgl zqczXmgl = ZqczXmgl.builder()
                    .xmzy(xmzy)
                    .xmlb(xmlb)
                    .gzcj(gzcj)
                    .xmmc(xmmc)
                    .xmrs(xmrs)
                    .create_by(username)
                    .update_by(username)
                    .build();
            return zqczXmgl;
        }, dataList -> {
            zqczXmglMapper.batchAdd(dataList);
        });
    }

    /**
     * 逻辑删除
     */
    @Override
    public int logicDelete(Long[] ids) {
        return zqczXmglMapper.logicDelete(ids);
    }
}
