package com.fs.qw.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.fs.common.core.domain.R;
import com.fs.common.utils.DictUtils;
import com.fs.qw.domain.QwFriendWelcome;
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.param.SendWelcomeMsgParam;
import com.fs.qwApi.service.QwApiService;
import com.fs.voice.utils.StringUtil;
import com.hc.openapi.tool.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
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.Arrays;
import java.util.Date;
import java.util.List;

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

    @Autowired
    private QwFriendWelcomeItemMapper  qwFriendWelcomeItemMapper;

    @Autowired
    private QwUserMapper qwUserMapper;

    @Autowired
    private QwApiService qwApiService;


    private static final String registerLink = "/registerCourse/pages/index?qwExternalId=";

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

        // 假设 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)
    {
        List<QwFriendWelcome> qwFriendWelcomes = qwFriendWelcomeMapper.selectQwFriendWelcomeListVO(qwFriendWelcomeParam);
        for (QwFriendWelcome qwFriendWelcome : qwFriendWelcomes) {
            if(ObjectUtils.isNotNull(qwFriendWelcome.getProject())){
                String sysCourseProject = DictUtils.getDictLabel("sys_course_project", String.valueOf(qwFriendWelcome.getProject()));
                if(StringUtils.isNotBlank(sysCourseProject)){
                    qwFriendWelcome.setProjectName(sysCourseProject);
                }
            }
        }
        return qwFriendWelcomes;
    }

    @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);

        if(attachmentsAll!=null && !attachmentsAll.isEmpty()){

            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("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) {

                    for (SendWelcomeMsgParam.Attachment attachment: schedule.getAttachments() ) {
                        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);
                            }
                        }
                        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);
                                }
                            }
                        }
                    }

                }
            }
            qwFriendWelcomeParam.setDaypartingItemlist(JSON.toJSONString(schedules));
        }

        int i = qwFriendWelcomeMapper.insertQwFriendWelcomeVO(qwFriendWelcomeParam);
        if (i>0){
            return R.ok("新增成功");
        }else {
            return R.error("新增失败");
        }

    }

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

        if(attachmentsAll!=null && !attachmentsAll.isEmpty()){

            for (SendWelcomeMsgParam.Attachment attachment : attachmentsAll) {

                if (attachment.getMsgtype().equals("image")&&!attachment.getImage().getPic_url().contains("https://wework.qpic.cn")){

                        try {
                            QwUploadImgResult uploadimg = qwApiService.uploadimgs(attachment.getImage().getPic_url(), qwFriendWelcome.getCorpId());
                            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("link")){
                    String LinkPicUrl = attachment.getLink().getPicurl();
                    if (LinkPicUrl!=null && !LinkPicUrl.isEmpty()&&!LinkPicUrl.contains("https://wework.qpic.cn")){
                        try {
                            QwUploadImgResult uploadimg = qwApiService.uploadimgs(LinkPicUrl, qwFriendWelcome.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);
                        }
                    }

                }
            }

            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) {

                    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(), qwFriendWelcome.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);
                            }
                        }
                        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, qwFriendWelcome.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);
                                }
                            }
                        }
                    }

                }
            }
            qwFriendWelcome.setDaypartingItemlist(JSON.toJSONString(schedules));
        }

        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);
    }

    /**
     *  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){}
}
