package com.fs.qw.service.impl;

import com.alibaba.fastjson.JSON;
import com.fs.common.constant.FsConstants;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCacheT;
import com.fs.common.exception.base.BaseException;
import com.fs.common.utils.StringUtils;
import com.fs.company.domain.Company;
import com.fs.company.mapper.CompanyMapper;
import com.fs.qw.domain.QwCompany;
import com.fs.qw.domain.QwFriendWelcome;
import com.fs.qw.mapper.QwCompanyMapper;
import com.fs.qw.mapper.QwFriendWelcomeItemMapper;
import com.fs.qw.mapper.QwFriendWelcomeMapper;
import com.fs.qw.mapper.QwUserMapper;
import com.fs.qw.param.QwFriendWelcomeParam;
import com.fs.qw.service.IQwFriendWelcomeService;
import com.fs.qw.vo.QwFriendWelcomeDayPart;
import com.fs.qw.vo.QwFriendWelcomeVO;
import com.fs.qw.vo.QwUserVO;
import com.fs.qwApi.Result.QwUploadImgResult;
import com.fs.qwApi.Result.QwUploadResult;
import com.fs.qwApi.param.SendWelcomeMsgParam;
import com.fs.qwApi.service.QwApiService;
import com.fs.voice.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 好友欢迎语Service业务层处理
 *
 * @author fs
 * @date 2024-07-20
 */
@Service
public class QwFriendWelcomeServiceImpl implements IQwFriendWelcomeService {
    @Autowired
    private QwFriendWelcomeMapper qwFriendWelcomeMapper;

    @Autowired
    private QwFriendWelcomeItemMapper qwFriendWelcomeItemMapper;

    @Autowired
    private QwUserMapper qwUserMapper;

    @Autowired
    private QwApiService qwApiService;

    @Autowired
    private RedisCacheT<Long> redisCache;
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private QwCompanyMapper qwCompanyMapper;

    /**
     * 查询好友欢迎语
     *
     * @param id 好友欢迎语主键
     * @return 好友欢迎语
     */
    @Override
    public QwFriendWelcomeVO selectQwFriendWelcomeById(Long id) {
        QwFriendWelcomeVO qwFriendWelcomeVO = qwFriendWelcomeMapper.selectQwFriendWelcomeByIdVO(id);

        // 假设 qwFriendWelcomeVO 是已经初始化的对象
        String qwUserIds = qwFriendWelcomeVO.getQwUserIds();

        // 去除方括号
        String sanitizedQwUserIds = qwUserIds.replace("[", "").replace("]", "");

        // 将字符串转换为列表
        List<String> qwUserIdsList = Arrays.asList(sanitizedQwUserIds.split(","));

        List<QwUserVO> qwUserByIds = qwUserMapper.getQwUserByIds(qwUserIdsList, qwFriendWelcomeVO.getCorpId());
        qwFriendWelcomeVO.setUserSelectList(qwUserByIds);

        return qwFriendWelcomeVO;
    }

    /**
     * 查询好友欢迎语列表
     *
     * @param qwFriendWelcomeParam 好友欢迎语
     * @return 好友欢迎语
     */
    @Override
    public List<QwFriendWelcome> selectQwFriendWelcomeListVO(QwFriendWelcomeParam qwFriendWelcomeParam) {
        return qwFriendWelcomeMapper.selectQwFriendWelcomeListVO(qwFriendWelcomeParam);
    }

    @Override
    public List<QwFriendWelcome> selectQwFriendWelcomeListMyVO(QwFriendWelcomeParam qwFriendWelcomeParam) {
        return qwFriendWelcomeMapper.selectQwFriendWelcomeListMyVO(qwFriendWelcomeParam);
    }

    /**
     * 新增好友欢迎语
     *
     * @param qwFriendWelcomeParam 好友欢迎语
     * @return 结果
     */
    @Override
    public R insertQwFriendWelcomeVO(QwFriendWelcomeParam qwFriendWelcomeParam) {
        List<SendWelcomeMsgParam.Attachment> attachmentsAll = JSON.parseArray(qwFriendWelcomeParam.getAttachments(), SendWelcomeMsgParam.Attachment.class);
        boolean video = false;
        if (attachmentsAll != null && !attachmentsAll.isEmpty()) {
            String corpId = qwFriendWelcomeParam.getCorpId();
            for (SendWelcomeMsgParam.Attachment attachment : attachmentsAll) {

                if (attachment.getMsgtype().equals("image")) {

                    try {
                        QwUploadImgResult uploadimg = qwApiService.uploadimgs(attachment.getImage().getPic_url(), qwFriendWelcomeParam.getCorpId());
                        if (uploadimg.getErrcode() == 0) {
                            attachment.getImage().setPic_url(uploadimg.getUrl());
                        } else {
                            return R.error("图片image上传失败:" + uploadimg.getErrMsg());
                        }
                    } catch (Exception e) {
                        return R.error("图片image上传出错:" + e);
//                        throw new RuntimeException("insertQwFriendWelcomeVO-attachment/image:"+e);
                    }
                }
                if (attachment.getMsgtype().equals("video")) {
                    if(!video){
                        video = true;
                    }
                    try {
                        uploadVideo(qwApiService, attachment, corpId);
                    } catch (BaseException e) {
                        return R.error(e.getMessage());
                    } catch (Exception e) {
                        return R.error("视频上传出错:" + e);
                    }
                }
                if (attachment.getMsgtype().equals("link")) {
                    String LinkPicUrl = attachment.getLink().getPicurl();
                    if (LinkPicUrl != null && !LinkPicUrl.isEmpty()) {
                        try {
                            QwUploadImgResult uploadimg = qwApiService.uploadimgs(LinkPicUrl, qwFriendWelcomeParam.getCorpId());
                            if (uploadimg.getErrcode() == 0) {
                                attachment.getLink().setPicurl(uploadimg.getUrl());
                            } else {
                                return R.error("图片link上传失败:" + uploadimg.getErrMsg());
                            }


                        } catch (Exception e) {
                            return R.error("图片link上传出错:" + e);
//                            throw new RuntimeException("insertQwFriendWelcomeVO-attachment/link:"+e);
                        }
                    }

                }
            }

            qwFriendWelcomeParam.setAttachments(JSON.toJSONString(attachmentsAll));
        }

        if (qwFriendWelcomeParam.getIsDayparting() == 1) {
            List<QwFriendWelcomeDayPart.Schedule> schedules = JSON.parseArray(qwFriendWelcomeParam.getDaypartingItemlist(), QwFriendWelcomeDayPart.Schedule.class);
            if (schedules != null && !schedules.isEmpty()) {

                for (QwFriendWelcomeDayPart.Schedule schedule : schedules) {
                    String corpId = qwFriendWelcomeParam.getCorpId();
                    for (SendWelcomeMsgParam.Attachment attachment : schedule.getAttachments()) {
                        if (attachment.getMsgtype().equals("image")) {
                            try {
                                QwUploadImgResult uploadimg = qwApiService.uploadimgs(attachment.getImage().getPic_url(), corpId);
                                if (uploadimg.getErrcode() == 0) {
                                    attachment.getImage().setPic_url(uploadimg.getUrl());
                                } else {
                                    return R.error("分时段图片image上传失败:" + uploadimg.getErrMsg());
                                }
                            } catch (Exception e) {
                                return R.error("分时段图片image上传出错:" + e);
                            }
                        }
                        if (attachment.getMsgtype().equals("video")) {
                            if(!video){
                                video = true;
                            }
                            try {
                                uploadVideo(qwApiService, attachment, corpId);
                            } catch (BaseException e) {
                                return R.error(e.getMessage());
                            } catch (Exception e) {
                                return R.error("视频上传出错:" + e);
                            }
                        }
                        if (attachment.getMsgtype().equals("link")) {
                            String linkPicurl = attachment.getLink().getPicurl();
                            if (linkPicurl != null && !linkPicurl.isEmpty()) {
                                try {
                                    QwUploadImgResult uploadimg = qwApiService.uploadimgs(linkPicurl, corpId);
                                    if (uploadimg.getErrcode() == 0) {
                                        attachment.getLink().setPicurl(uploadimg.getUrl());
                                    } else {
                                        return R.error("分时段图片link上传失败:" + uploadimg.getErrMsg());
                                    }

                                } catch (Exception e) {
                                    return R.error("分时段图片link上传出错:" + e);
                                }
                            }
                        }
                    }

                }
            }
            qwFriendWelcomeParam.setDaypartingItemlist(JSON.toJSONString(schedules));
        }
        int i = qwFriendWelcomeMapper.insertQwFriendWelcomeVO(qwFriendWelcomeParam);
        if(video){
            redisCache.setCacheObject(FsConstants.FRIEND_WELCOME_VIDEO_KEY + qwFriendWelcomeParam.getId(), qwFriendWelcomeParam.getId(), 60, TimeUnit.HOURS);
        }
        if (i > 0) {
            return R.ok("新增成功");
        } else {
            return R.error("新增失败");
        }

    }

    public static void uploadVideo(QwApiService qwApiService, SendWelcomeMsgParam.Attachment attachment, String corpId) throws Exception {
        QwUploadResult result = qwApiService.upload(urlToFile(attachment.getVideo().getUrl()), "video", corpId);
        if (result.getErrCode() == 0) {
            attachment.getVideo().setMedia_id(result.getMediaId());
        } else {
            throw new BaseException("视频上传失败:" + result.getErrMsg());
        }
    }

    /**
     * 修改好友欢迎语
     *
     * @param qwFriendWelcome 好友欢迎语
     * @return 结果
     */
    @Override
    public R updateQwFriendWelcome(QwFriendWelcome qwFriendWelcome) {
        List<SendWelcomeMsgParam.Attachment> attachmentsAll = JSON.parseArray(qwFriendWelcome.getAttachments(), SendWelcomeMsgParam.Attachment.class);
        boolean video = false;
        if (attachmentsAll != null && !attachmentsAll.isEmpty()) {

            for (SendWelcomeMsgParam.Attachment attachment : attachmentsAll) {
                String corpId = qwFriendWelcome.getCorpId();
                if (attachment.getMsgtype().equals("image") && !attachment.getImage().getPic_url().contains("https://wework.qpic.cn")) {

                    try {
                        QwUploadImgResult uploadimg = qwApiService.uploadimgs(attachment.getImage().getPic_url(), corpId);
                        if (uploadimg.getErrcode() == 0) {
                            attachment.getImage().setPic_url(uploadimg.getUrl());
                        } else {
                            return R.error("上传好友欢迎语图片image失败:" + uploadimg.getErrMsg());
                        }

                    } catch (Exception e) {
                        return R.error("上传好友欢迎语图片出错:" + e);
                    }


                }
                if (attachment.getMsgtype().equals("video")) {
                    if(!video){
                        video = true;
                    }
                    try {
                        uploadVideo(qwApiService, attachment, corpId);
                    } catch (BaseException e) {
                        return R.error(e.getMessage());
                    } catch (Exception e) {
                        return R.error("视频上传出错:" + e);
                    }
                }

                if (attachment.getMsgtype().equals("link")) {
                    String LinkPicUrl = attachment.getLink().getPicurl();
                    if (LinkPicUrl != null && !LinkPicUrl.isEmpty() && !LinkPicUrl.contains("https://wework.qpic.cn")) {
                        try {
                            QwUploadImgResult uploadimg = qwApiService.uploadimgs(LinkPicUrl, corpId);
                            if (uploadimg.getErrcode() == 0) {
                                attachment.getLink().setPicurl(uploadimg.getUrl());
                            } else {
                                return R.error("上传好友欢迎语图片link失败:" + uploadimg.getErrMsg());
                            }

                        } catch (Exception e) {
                            return R.error("上传好友欢迎语图片link出错:" + e);
                        }
                    }

                }
            }

            qwFriendWelcome.setAttachments(JSON.toJSONString(attachmentsAll));
        }

        if (qwFriendWelcome.getIsDayparting().equals("1")) {
            List<QwFriendWelcomeDayPart.Schedule> schedules = JSON.parseArray(qwFriendWelcome.getDaypartingItemlist(), QwFriendWelcomeDayPart.Schedule.class);
            if (schedules != null && !schedules.isEmpty()) {

                for (QwFriendWelcomeDayPart.Schedule schedule : schedules) {
                    String corpId = qwFriendWelcome.getCorpId();
                    for (SendWelcomeMsgParam.Attachment attachment : schedule.getAttachments()) {
                        if (attachment.getMsgtype().equals("image") && !attachment.getImage().getPic_url().contains("https://wework.qpic.cn")) {
                            try {
                                QwUploadImgResult uploadimg = qwApiService.uploadimgs(attachment.getImage().getPic_url(), corpId);
                                if (uploadimg.getErrcode() == 0) {
                                    attachment.getImage().setPic_url(uploadimg.getUrl());
                                } else {
                                    return R.error("上传分时段好友欢迎语图片image失败:" + uploadimg.getErrMsg());
                                }
                            } catch (Exception e) {
                                return R.error("上传分时段好友欢迎语图片image出错:" + e);
                            }
                        }
                        if (attachment.getMsgtype().equals("video")) {
                            if(!video){
                                video = true;
                            }
                            try {
                                uploadVideo(qwApiService, attachment, corpId);
                            } catch (BaseException e) {
                                return R.error(e.getMessage());
                            } catch (Exception e) {
                                return R.error("视频上传出错:" + e);
                            }
                        }
                        if (attachment.getMsgtype().equals("link")) {
                            String linkPicurl = attachment.getLink().getPicurl();
                            if (linkPicurl != null && !linkPicurl.isEmpty() && !linkPicurl.contains("https://wework.qpic.cn")) {
                                try {
                                    QwUploadImgResult uploadimg = qwApiService.uploadimgs(linkPicurl, corpId);
                                    if (uploadimg.getErrcode() == 0) {
                                        attachment.getLink().setPicurl(uploadimg.getUrl());
                                    } else {
                                        return R.error("上传分时段好友欢迎语图片link失败:" + uploadimg.getErrMsg());
                                    }

                                } catch (Exception e) {
                                    return R.error("上传分时段好友欢迎语图片link出错:" + e);
                                }
                            }
                        }
                    }

                }
            }
            qwFriendWelcome.setDaypartingItemlist(JSON.toJSONString(schedules));
        }
        String key = FsConstants.FRIEND_WELCOME_VIDEO_KEY + qwFriendWelcome.getId();
        redisCache.deleteObject(key);
        if(video){
            redisCache.setCacheObject(key, qwFriendWelcome.getId(), 60, TimeUnit.HOURS);
        }
        return R.ok().put("msg", qwFriendWelcomeMapper.updateQwFriendWelcome(qwFriendWelcome));
    }

    /**
     * 批量删除好友欢迎语
     *
     * @param ids 需要删除的好友欢迎语主键
     * @return 结果
     */
    @Override
    public int deleteQwFriendWelcomeByIds(Long[] ids) {
        return qwFriendWelcomeMapper.deleteQwFriendWelcomeByIds(ids);
    }

    /**
     * 删除好友欢迎语信息
     *
     * @param id 好友欢迎语主键
     * @return 结果
     */
    @Override
    public int deleteQwFriendWelcomeById(Long id) {
        return qwFriendWelcomeMapper.deleteQwFriendWelcomeById(id);
    }

    /**
     * 查询欢迎语列表
     * @param qwFriendWelcomeParam 参数
     * @return list
     */
    @Override
    public List<QwFriendWelcomeVO> selectQwFriendWelcomeList(QwFriendWelcomeParam qwFriendWelcomeParam) {
        List<QwFriendWelcomeVO> qwFriendWelcomes = qwFriendWelcomeMapper.selectQwFriendWelcomeList(qwFriendWelcomeParam);

        if (qwFriendWelcomes.isEmpty()) {
            return qwFriendWelcomes;
        }

        List<Long> companyIds = qwFriendWelcomes.stream().map(QwFriendWelcomeVO::getCompanyId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
        List<String> corpIds = qwFriendWelcomes.stream().map(QwFriendWelcomeVO::getCorpId).filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());

        Map<Long, String> companyMap = companyIds.isEmpty()
                ? Collections.emptyMap()
                : companyMapper.selectCompanyByIds(companyIds).stream().collect(Collectors.toMap(Company::getCompanyId, Company::getCompanyName, (a, b) -> a));
        Map<String, String> corpMap = corpIds.isEmpty()
                ? Collections.emptyMap()
                : qwCompanyMapper.selectByCorpIds(corpIds).stream().collect(Collectors.toMap(QwCompany::getCorpId, QwCompany::getCorpName, (a, b) -> a
        ));
        qwFriendWelcomes.forEach(qwFriendWelcome -> {
            qwFriendWelcome.setCompanyName(companyMap.getOrDefault(qwFriendWelcome.getCompanyId(), ""));
            qwFriendWelcome.setCorpName(corpMap.getOrDefault(qwFriendWelcome.getCorpId(), ""));
        });
        return qwFriendWelcomes;
    }

    /**
     * url转临时文件filr
     */
    public static File urlToFile(String fileUrl) throws Exception {

        // 从URL中提取文件名，文件后缀
        String fileExtension = getFileExtension(new File(fileUrl).getName());
        String fileName = extractFileName(new URL(fileUrl)) + new Date().getTime();
        File tempFile = null;
        if (!StringUtil.strIsNullOrEmpty(fileExtension)) {
            // 创建一个临时文件
            tempFile = File.createTempFile(fileName, "." + fileExtension);
        } else {
            tempFile = File.createTempFile(fileName, null);
        }


        // 使用 try-with-resources 语句自动关闭资源
        try (BufferedInputStream in = new BufferedInputStream(new URL(fileUrl).openStream());
             FileOutputStream out = new FileOutputStream(tempFile)) {

            byte[] buffer = new byte[1024];
            int len;

            // 读取数据并写入到临时文件
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (IOException e) {
            // 处理异常，例如删除创建的临时文件
            tempFile.delete();
            throw e;
        }

        return tempFile;
    }

    /**
     * 获取文件名
     */
    private static String extractFileName(URL url) throws Exception {
        String path = url.getPath();
        int lastSlashIndex = path.lastIndexOf('/');
        String fileNameWithExt = path.substring(lastSlashIndex + 1);

        int dotIndex = fileNameWithExt.lastIndexOf('.');
        String baseName;
        if (dotIndex > 0) {
            // 如果有扩展名，移除扩展名
            baseName = fileNameWithExt.substring(0, dotIndex);
        } else {
            // 如果没有扩展名，直接使用文件名
            baseName = fileNameWithExt;
        }

        return baseName;
    }

    /**
     * 获取文件名后缀
     */

    public static String getFileExtension(String fileName) {
        int lastIndex = fileName.lastIndexOf('.');
        if (lastIndex != -1 && lastIndex + 1 < fileName.length()) {
            return fileName.substring(lastIndex + 1);
        }
        return ""; // 如果没有扩展名，返回空字符串
    }

    public static void uploadFileImage(MultipartFile file, String filePath) {
    }
}
