package com.microservices.dms.achievementLibrary.service.impl;

import java.io.*;
import java.util.*;

import com.alibaba.fastjson2.JSONObject;
import com.microservices.common.core.constant.SecurityConstants;
import com.microservices.common.core.constant.UserConstants;
import com.microservices.common.core.domain.R;
import com.microservices.common.core.exception.ServiceException;
import com.microservices.common.core.utils.DateUtils;
import com.microservices.common.core.utils.StringUtils;
import com.microservices.common.datasource.annotation.Slave;
import com.microservices.common.security.utils.SecurityUtils;
import com.microservices.dms.achievementLibrary.domain.AchievementTeam;
import com.microservices.dms.achievementLibrary.domain.Achievements;
import com.microservices.dms.achievementLibrary.mapper.AchievementTeamMapper;
import com.microservices.dms.achievementLibrary.mapper.AchievementsMapper;
import com.microservices.dms.achievementLibrary.service.IAchievementsService;
import com.microservices.system.api.RemoteFileService;
import com.microservices.system.api.model.LoginUser;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.microservices.dms.achievementLibrary.mapper.SchoolEnterpriseAchievementsMapper;
import com.microservices.dms.achievementLibrary.domain.SchoolEnterpriseAchievements;
import com.microservices.dms.achievementLibrary.service.ISchoolEnterpriseAchievementsService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

/**
 * 校企成果Service业务层处理
 * 
 * @author microservices
 * @date 2025-04-03
 */
@Service
public class SchoolEnterpriseAchievementsServiceImpl implements ISchoolEnterpriseAchievementsService 
{
    @Autowired
    private SchoolEnterpriseAchievementsMapper schoolEnterpriseAchievementsMapper;

    @Autowired
    private AchievementTeamMapper achievementTeamMapper;

    @Autowired
    private IAchievementsService achievementsService;
    @Autowired
    private AchievementsMapper achievementsMapper;

    @Autowired
    private RemoteFileService remoteFileService;

    /**
     * 查询校企成果
     *
     * @param id 校企成果主键
     * @return 校企成果
     */
    @Override
    public SchoolEnterpriseAchievements selectSchoolEnterpriseAchievementsById(Long id)
    {
        SchoolEnterpriseAchievements sAchievements =  schoolEnterpriseAchievementsMapper.selectSchoolEnterpriseAchievementsById(id);
        if(StringUtils.isNotNull(sAchievements)){
            Long achId = sAchievements.getId();
            List<AchievementTeam> teamList = achievementTeamMapper.selectAchievementTeamByAchId(achId);
            if(StringUtils.isNotNull(teamList) && teamList.size() > 0){
                sAchievements.setTeamList(teamList);
            }
        }
        return sAchievements;
    }

    /**
     * 查询校企成果列表
     *
     * @param schoolEnterpriseAchievements 校企成果
     * @return 校企成果
     */
    @Override
    public List<SchoolEnterpriseAchievements> selectSchoolEnterpriseAchievementsList(SchoolEnterpriseAchievements schoolEnterpriseAchievements)
    {
//        LoginUser loginUser = SecurityUtils.getLoginUser();
//        if (loginUser != null){
//            String username = loginUser.getUsername();
//            schoolEnterpriseAchievements.setCreateBy(username);
//        }
        List<SchoolEnterpriseAchievements> list = schoolEnterpriseAchievementsMapper.selectSchoolEnterpriseAchievementsList(schoolEnterpriseAchievements);
        for (SchoolEnterpriseAchievements a : list) {
            a.setImages(achievementsService.buildFileInfoByIdents(a.getImages(), "4"));
            a.setAttachments(achievementsService.buildFileInfoByIdents(a.getAttachments(), "4"));
        }
        return list;
    }

    @Override
    public List<SchoolEnterpriseAchievements> listFront(SchoolEnterpriseAchievements schoolEnterpriseAchievements) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser != null) {
            String username = loginUser.getUsername();
            schoolEnterpriseAchievements.setCreateBy(username);
        }
        return selectSchoolEnterpriseAchievementsList(schoolEnterpriseAchievements);
    }

    /**
     * 新增校企成果
     *
     * @param schoolEnterpriseAchievements 校企成果
     * @return 结果
     */
    @Override
    public Long insertSchoolEnterpriseAchievements(SchoolEnterpriseAchievements schoolEnterpriseAchievements)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser != null){
            String username = loginUser.getUsername();
            schoolEnterpriseAchievements.setCreateBy(username);
        }
        schoolEnterpriseAchievements.setCreateTime(DateUtils.getNowDate());
        schoolEnterpriseAchievementsMapper.insertSchoolEnterpriseAchievements(schoolEnterpriseAchievements);
        return schoolEnterpriseAchievements.getId();
    }

    //先判断是否存在名称一致的成果，存在则抛异常，已存在名称一样的成果
    @Override
    public boolean getCheckSchoolAchName(SchoolEnterpriseAchievements schoolEnterpriseAchievements) {
        Long achId = StringUtils.isNull(schoolEnterpriseAchievements.getId()) ? -1L : schoolEnterpriseAchievements.getId();
        SchoolEnterpriseAchievements  info =schoolEnterpriseAchievementsMapper.selectSchoolEnterpriseAchievementsByName(schoolEnterpriseAchievements.getAchievementName());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != achId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 导入成果数据（包含图片处理）
     */
    @Override
    @Transactional
    @Slave
    public String batchInsertSchoolEnterpriseAchievements(List<SchoolEnterpriseAchievements> list,
                                    Map<String, MultipartFile> imageMap,
                                    boolean updateSupport,
                                    String operName) {
        if (list == null || list.isEmpty()) {
            throw new RuntimeException("导入成果数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int imageErrorNum = 0; // 新增：图片处理失败数
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        StringBuilder imageErrorMsg = new StringBuilder(); // 新增：图片错误信息

        for (SchoolEnterpriseAchievements schoolEnterpriseAchievement : list) {
            try {
                // 处理图片字段（优化后：返回处理结果，不抛出异常）
                String imageHandleResult = handleAchievementImage(schoolEnterpriseAchievement, imageMap);
                if (imageHandleResult.contains("失败") || imageHandleResult.contains("异常")) {
                    imageErrorNum++;
                    imageErrorMsg.append("<br/>").append(imageErrorNum).append("、成果 ").append(schoolEnterpriseAchievement.getAchievementName()).append(" 图片处理失败：").append(imageHandleResult);
                }

                // 原有查重和入库逻辑（不受图片处理影响）
                SchoolEnterpriseAchievements exist = schoolEnterpriseAchievementsMapper.selectSchoolEnterpriseAchievementsByName(schoolEnterpriseAchievement.getAchievementName());
                if (exist == null) {
                    schoolEnterpriseAchievement.setCreateBy(operName);
                    schoolEnterpriseAchievement.setCreateTime(new Date());
                    schoolEnterpriseAchievement.setUpdateBy(operName);
                    schoolEnterpriseAchievement.setUpdateTime(new Date());
                    schoolEnterpriseAchievement.setStatus("2");
                    schoolEnterpriseAchievementsMapper.insertSchoolEnterpriseAchievements(schoolEnterpriseAchievement);
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、成果 ").append(schoolEnterpriseAchievement.getAchievementName()).append(" 导入成功");
                } else {
                    if (updateSupport) {
                        schoolEnterpriseAchievement.setId(exist.getId());
                        schoolEnterpriseAchievement.setCreateBy(exist.getCreateBy());
                        schoolEnterpriseAchievement.setCreateTime(exist.getCreateTime());
                        schoolEnterpriseAchievement.setUpdateBy(operName);
                        schoolEnterpriseAchievement.setUpdateTime(new Date());
                        schoolEnterpriseAchievementsMapper.updateSchoolEnterpriseAchievements(schoolEnterpriseAchievement);
                        successNum++;
                        successMsg.append("<br/>").append(successNum).append("、成果 ").append(schoolEnterpriseAchievement.getAchievementName()).append(" 更新成功");
                    } else {
                        failureNum++;
                        failureMsg.append("<br/>").append(failureNum).append("、成果 ").append(schoolEnterpriseAchievement.getAchievementName()).append(" 已存在（未开启更新）");
                    }
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、成果 " + schoolEnterpriseAchievement.getAchievementName() + " 导入失败：";
                failureMsg.append(msg).append(e.getMessage());
            }
        }

        // 组装最终提示信息（包含图片处理错误）
        StringBuilder finalMsg = new StringBuilder();
        if (successNum > 0) {
            finalMsg.append("共 ").append(successNum).append(" 条数据导入/更新成功：").append(successMsg);
        }
        if (failureNum > 0) {
            finalMsg.append("<br/>共 ").append(failureNum).append(" 条数据导入失败：").append(failureMsg);
        }
        if (imageErrorNum > 0) {
            finalMsg.append("<br/>共 ").append(imageErrorNum).append(" 条数据图片处理失败：").append(imageErrorMsg);
        }

        return finalMsg.toString();
    }

    /**
     * 处理成果图片：上传并格式化存储（FastJSON解析版）
     * @param achievement 成果实体
     * @param imageMap Excel解析出的图片映射表
     * @return 图片处理结果提示（成功/失败信息）
     */
    private String handleAchievementImage(SchoolEnterpriseAchievements achievement, Map<String, MultipartFile> imageMap) {
        String imageCellKey = achievement.getImages();
        if (StringUtils.isEmpty(imageCellKey) || !imageMap.containsKey(imageCellKey)) {
            achievement.setImages("[]");
            return "无图片，跳过处理";
        }

        try {
            MultipartFile file = imageMap.get(imageCellKey);
            byte[] fileBytes = file.getBytes();

            if (fileBytes == null || fileBytes.length == 0) {
                return "图片文件为空，跳过处理";
            }

            // 构建 HashMap 参数
            String originalFilename = StringUtils.isEmpty(file.getOriginalFilename())
                    ? "excel_import_image_" + System.currentTimeMillis() + ".png"
                    : file.getOriginalFilename();

            Map<String, Object> params = new HashMap<>();
            params.put("base64Data", Base64.getEncoder().encodeToString(fileBytes));
            params.put("fileName", originalFilename);
            params.put("contentType", file.getContentType());
            params.put("size", fileBytes.length);

            // 调用 Base64 上传接口
            R<?> fileResult = remoteFileService.uploadBase64(params, "dms", "import", SecurityConstants.INNER);

            // 解析结果（与原逻辑相同）
            if (StringUtils.isNull(fileResult) || StringUtils.isNull(fileResult.getData())) {
                String errorMsg = !StringUtils.isNull(fileResult) ? fileResult.getMsg() : "接口返回异常";
                return "图片上传失败：" + errorMsg;
            }

            JSONObject resultJson = JSONObject.parseObject(JSONObject.toJSONString(fileResult.getData()));
            String fileOriginName = resultJson.getString("fileOriginName");
            String url = resultJson.getString("downloadUrl");
            Integer fileId = resultJson.getInteger("fileId");

            if (StringUtils.isEmpty(fileOriginName) || StringUtils.isEmpty(url) || fileId == null) {
                return "图片上传成功，但返回数据不完整";
            }

            String imageJson = String.format("[{\"k\":\"%s\",\"v\":\"%s\",\"id\":%d}]",
                    fileOriginName, url, fileId);
            achievement.setImages(imageJson);

            return "图片处理成功";

        } catch (Exception e) {
            return "图片处理异常：" + e.getMessage();
        }
    }


    /**
     * 修改校企成果
     *
     * @param schoolEnterpriseAchievements 校企成果
     * @return 结果
     */
    @Override
    public int updateSchoolEnterpriseAchievements(SchoolEnterpriseAchievements schoolEnterpriseAchievements)
    {
        schoolEnterpriseAchievements.setUpdateTime(DateUtils.getNowDate());
        String status = schoolEnterpriseAchievements.getStatus();
        if(StringUtils.isNotEmpty(status)){
            schoolEnterpriseAchievements.setReviewDate(DateUtils.getNowDate());
            if (SecurityUtils.getLoginUser() != null) {
                schoolEnterpriseAchievements.setReviewer(SecurityUtils.getLoginUser().getUsername());
            }
        }
        return schoolEnterpriseAchievementsMapper.updateSchoolEnterpriseAchievements(schoolEnterpriseAchievements);
    }

    /**
     * 批量删除校企成果
     *
     * @param ids 需要删除的校企成果主键
     * @return 结果
     */
    @Override
    public int deleteSchoolEnterpriseAchievementsByIds(Long[] ids)
    {
        return schoolEnterpriseAchievementsMapper.deleteSchoolEnterpriseAchievementsByIds(ids);
    }

    /**
     * 删除校企成果信息
     *
     * @param id 校企成果主键
     * @return 结果
     */
    @Override
    public int deleteSchoolEnterpriseAchievementsById(Long id)
    {
        // 校企成果删除前判断数据仓库是否存在数据，存在则不允许删除该数据
        Achievements achievements = new Achievements();
        achievements.setSource("4");
        achievements.setSourceId(id);
        List<Achievements> ss = achievementsMapper.selectAchievementsList(achievements);
        if (ss != null && !ss.isEmpty()) {
            throw new ServiceException("数据仓库是否存在数据，不允许删除");
        }

        // 校企成果被删除，对应的成员也应该一并删除
        achievementTeamMapper.deleteAchievementTeamByAId(id);
        return schoolEnterpriseAchievementsMapper.deleteSchoolEnterpriseAchievementsById(id);
    }

    @Override
    public Long topStatistic(SchoolEnterpriseAchievements schoolEnterpriseAchievements) {
        return schoolEnterpriseAchievementsMapper.topStatistic(schoolEnterpriseAchievements);
    }
}
