package com.fs.qw.service.impl;

import com.fs.common.core.domain.R;
import com.fs.common.utils.DateUtils;
import com.fs.company.service.ICompanyConfigService;
import com.fs.qw.domain.QwWelcome;
import com.fs.qw.mapper.QwWelcomeMapper;
import com.fs.qw.service.IQwWelcomeService;
import com.fs.qwApi.Result.QwAddWelcomeResult;
import com.fs.qwApi.Result.QwUploadImgResult;
import com.fs.qwApi.Result.QwUploadResult;
import com.fs.qwApi.domain.QwResult;
import com.fs.qwApi.param.QwGroupWelcomeTemplateParam;
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 java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.List;

/**
 * 入群欢迎语管理Service业务层处理
 *
 * @author fs
 * @date 2024-06-22
 */
@Service
public class QwWelcomeServiceImpl implements IQwWelcomeService
{
    @Autowired
    private QwWelcomeMapper qwWelcomeMapper;

    @Autowired
    private QwApiService qwApiService;

    @Autowired
    private ICompanyConfigService companyConfigService;

    /**
     * 查询入群欢迎语管理
     *
     * @param welcomeId 入群欢迎语管理主键
     * @return 入群欢迎语管理
     */
    @Override
    public QwWelcome selectQwWelcomeByWelcomeId(Long welcomeId)
    {
        return qwWelcomeMapper.selectQwWelcomeByWelcomeId(welcomeId);
    }

    /**
     * 查询入群欢迎语管理列表
     *
     * @param qwWelcome 入群欢迎语管理
     * @return 入群欢迎语管理
     */
    @Override
    public List<QwWelcome> selectQwWelcomeList(QwWelcome qwWelcome)
    {
        return qwWelcomeMapper.selectQwWelcomeList(qwWelcome);
    }

    /**
     * 新增入群欢迎语管理
     *
     * @param qwWelcome 入群欢迎语管理
     * @return 结果
     */
    @Override
    public R insertQwWelcome(QwWelcome qwWelcome) throws Exception {

//        CompanyConfig companyConfig = companyConfigService.selectCompanyConfigByKey(qwWelcome.getCompanyId(), "sys:qw:config");
//        QWCompanyConfig qwCompanyConfig = JSON.parseObject(companyConfig.getConfigValue(), QWCompanyConfig.class);

//        String corpId = qwCompanyConfig.getCorpId();
//        qwWelcome.setCorpId(corpId);
        qwWelcome.setCreateTime(DateUtils.getNowDate());
        //发送消息体
        QwGroupWelcomeTemplateParam qwGroupWelcomeTemplateParam=new QwGroupWelcomeTemplateParam();
        qwGroupWelcomeTemplateParam.setContent(qwWelcome.getTextContent());
        qwGroupWelcomeTemplateParam.setNotify(qwWelcome.getNotify()==1?true:false);
        //上传素材
        QwAddWelcomeResult qwAddWelcomeResult=null;


        switch (qwWelcome.getWelcomeType()){
            //文字+图片
            case 1:
                if (!StringUtil.strIsNullOrEmpty(qwWelcome.getImagePicUrl())){
                    QwUploadImgResult uploadimg = qwApiService.uploadimgs(qwWelcome.getImagePicUrl(), qwWelcome.getCorpId());

                    //发送消息体
                    qwWelcome.setImagePicUrl(uploadimg.getUrl());

                    //记录
                    qwGroupWelcomeTemplateParam.setImagePicUrl(uploadimg.getUrl());
                    qwGroupWelcomeTemplateParam.setType(2);

                }else {
                    qwGroupWelcomeTemplateParam.setType(1);
                }
                break;
            //图文
            case 2:
                if (!StringUtil.strIsNullOrEmpty(qwWelcome.getLinkUrl())){

                    if (!StringUtil.strIsNullOrEmpty(qwWelcome.getLinkPicurl())) {
                        QwUploadImgResult  uploadimgOne = qwApiService.uploadimgs(qwWelcome.getLinkPicurl(), qwWelcome.getCorpId());
                        if (uploadimgOne.getErrcode()!=0){
                            return R.error("图片上传失败:"+uploadimgOne.getErrMsg());
                        }
                        qwGroupWelcomeTemplateParam.setLinkPicurl(uploadimgOne.getUrl());

                    }
                    qwGroupWelcomeTemplateParam.setType(3);
                    qwGroupWelcomeTemplateParam.setLinkTitle(qwWelcome.getLinkTitle());
                    qwGroupWelcomeTemplateParam.setLinkDesc(qwWelcome.getLinkDesc());
                    qwGroupWelcomeTemplateParam.setLinkUrl(qwWelcome.getLinkUrl());
                }
                break;
            //小程序
            case 3:
                break;
            //文件
            case 4:
                File fileOne = urlToFile(qwWelcome.getFileUrl());
                QwUploadResult file = qwApiService.upload(fileOne, "file", qwWelcome.getCorpId());
                qwWelcome.setFileMediaId(file.getMediaId());
                qwGroupWelcomeTemplateParam.setFileMediaId(file.getMediaId());
                qwGroupWelcomeTemplateParam.setType(5);
                qwGroupWelcomeTemplateParam.setCreatedAt(file.getCreatedAt());
                fileOne.delete();
                break;
            //视频
            case 5:
                File fileVideo = urlToFile(qwWelcome.getVideoUrl());
                QwUploadResult videoResult = qwApiService.upload(fileVideo, "video", qwWelcome.getCorpId());
                qwWelcome.setVideoMediaId(videoResult.getMediaId());
                qwGroupWelcomeTemplateParam.setVideoMediaId(videoResult.getMediaId());
                qwGroupWelcomeTemplateParam.setType(6);
                qwGroupWelcomeTemplateParam.setCreatedAt(videoResult.getCreatedAt());
                fileVideo.delete();
                break;
        }


//        if (qwWelcome.getWelcomeType()==3){
//            return R.error("暂时无法上传小程序");
//        }


//
//        if (qwWelcome.getWelcomeType()==5){
//
//        }

        //上传素材
        qwAddWelcomeResult = qwApiService.addGroupWelcomeTemplate(qwGroupWelcomeTemplateParam, qwWelcome.getCorpId());
        qwWelcome.setTemplateId(qwAddWelcomeResult.getTemplateId());
        qwWelcome.setCreatedAt(qwGroupWelcomeTemplateParam.getCreatedAt());
        if (qwAddWelcomeResult.getErrcode()!=0){
            return R.error("素材上传失败:"+qwAddWelcomeResult.getErrmsg());
        }

        return R.ok().put("data",qwWelcomeMapper.insertQwWelcome(qwWelcome));
    }

//    public R insertQwWelcome(QwWelcome qwWelcome,MultipartFile fileOne,MultipartFile fileTwo) throws Exception {
//        CompanyConfig companyConfig = companyConfigService.selectCompanyConfigByKey(qwWelcome.getCompanyId(), "sys:qw:config");
//        QWCompanyConfig qwCompanyConfig = JSON.parseObject(companyConfig.getConfigValue(), QWCompanyConfig.class);
//        String corpId = qwCompanyConfig.getCorpId();
//        qwWelcome.setCorpId(corpId);
//        qwWelcome.setCreateTime(DateUtils.getNowDate());
//        //发送消息体
//        QwGroupWelcomeTemplateParam qwGroupWelcomeTemplateParam=new QwGroupWelcomeTemplateParam();
//        qwGroupWelcomeTemplateParam.setContent(qwWelcome.getTextContent());
//        qwGroupWelcomeTemplateParam.setNotify(qwWelcome.getNotify()==1?true:false);
//        //上传素材
//        QwAddWelcomeResult qwAddWelcomeResult=null;
//        //文字+图片
//        if (qwWelcome.getWelcomeType()==1&& !StringUtil.strIsNullOrEmpty(qwWelcome.getImagePicUrl())){
//
////            QwUploadImgResult uploadimg = qwApiService.uploadimg(fileOne, qwWelcome.getCompanyId());
////            qwWelcome.setImagePicUrl(uploadimg.getUrl());
////
////            qwGroupWelcomeTemplateParam.setImagePicUrl(uploadimg.getUrl());
////            qwGroupWelcomeTemplateParam.setType(2);
//
//        }
//        //图文
//        if (qwWelcome.getWelcomeType()==2
//                &&!StringUtil.strIsNullOrEmpty(qwWelcome.getLinkUrl())
//                &&!StringUtil.strIsNullOrEmpty(qwWelcome.getLinkPicurl())){
//
////            QwUploadImgResult uploadimgOne = qwApiService.uploadimg(fileOne, qwWelcome.getCompanyId());
////            QwUploadImgResult uploadimgTwo = qwApiService.uploadimg(fileTwo, qwWelcome.getCompanyId());
//
////            qwGroupWelcomeTemplateParam.setType(3);
////            qwGroupWelcomeTemplateParam.setLinkTitle(qwWelcome.getLinkTitle());
////            qwGroupWelcomeTemplateParam.setLinkPicurl(uploadimgOne.getUrl());
////            qwGroupWelcomeTemplateParam.setLinkDesc(qwWelcome.getLinkDesc());
////            qwGroupWelcomeTemplateParam.setLinkUrl(uploadimgTwo.getUrl());
//
//        }
//
//        //小程序
//        if (qwWelcome.getWelcomeType()==3){
//            return R.error("暂时无法上传小程序");
//        }
//        //文件
//        if (qwWelcome.getWelcomeType()==4){
//            QwUploadResult file = qwApiService.upload(fileOne, "file", qwWelcome.getCompanyId());
//            qwGroupWelcomeTemplateParam.setFileMediaId(file.getMediaId());
//            qwGroupWelcomeTemplateParam.setType(5);
//            qwGroupWelcomeTemplateParam.setCreatedAt(file.getCreatedAt());
//        }
//
//        //视频
//        if (qwWelcome.getWelcomeType()==5){
//            QwUploadResult file = qwApiService.upload(fileOne, "video", qwWelcome.getCompanyId());
//            qwGroupWelcomeTemplateParam.setVideoMediaId(file.getMediaId());
//            qwGroupWelcomeTemplateParam.setType(6);
//            qwGroupWelcomeTemplateParam.setCreatedAt(file.getCreatedAt());
//        }
//
//        //上传素材
//        qwAddWelcomeResult = qwApiService.addGroupWelcomeTemplate(qwGroupWelcomeTemplateParam, qwWelcome.getCompanyId());
//        qwWelcome.setTemplateId(qwAddWelcomeResult.getTemplateId());
//        qwWelcome.setCreatedAt(qwGroupWelcomeTemplateParam.getCreatedAt());
//        if (qwAddWelcomeResult.getErrcode()!=0){
//            return R.error("素材上传失败:"+qwAddWelcomeResult.getErrmsg());
//        }
//
//        return R.ok().put("data",qwWelcomeMapper.insertQwWelcome(qwWelcome));
//    }

    /**
     * 修改入群欢迎语管理
     *
     * @param qwWelcome 入群欢迎语管理
     * @return 结果
     */
    @Override
    public R updateQwWelcome(QwWelcome qwWelcome) throws Exception {
        qwWelcome.setUpdateTime(DateUtils.getNowDate());
        //发送消息体
        QwGroupWelcomeTemplateParam qwGroupWelcomeTemplateParam=new QwGroupWelcomeTemplateParam();

        qwGroupWelcomeTemplateParam.setTemplateId(qwWelcome.getTemplateId());
        qwGroupWelcomeTemplateParam.setContent(qwWelcome.getTextContent());
        qwGroupWelcomeTemplateParam.setNotify(qwWelcome.getNotify()==1?true:false);
        //上传素材
        QwAddWelcomeResult qwAddWelcomeResult=null;

        //文字+图片
        if (qwWelcome.getWelcomeType()==1&& !StringUtil.strIsNullOrEmpty(qwWelcome.getImagePicUrl())){

//            File file = urlToFile(qwWelcome.getImagePicUrl());
            QwUploadImgResult uploadimg = qwApiService.uploadimgs(qwWelcome.getImagePicUrl(), qwWelcome.getCorpId());
            qwWelcome.setImagePicUrl(uploadimg.getUrl());

            qwGroupWelcomeTemplateParam.setImagePicUrl(uploadimg.getUrl());
            qwGroupWelcomeTemplateParam.setType(2);
//            file.delete();
        }
        //图文
        if (qwWelcome.getWelcomeType()==2
                &&!StringUtil.strIsNullOrEmpty(qwWelcome.getLinkUrl())){

            if (!StringUtil.strIsNullOrEmpty(qwWelcome.getLinkPicurl())) {
                QwUploadImgResult uploadimgOne = qwApiService.uploadimgs(qwWelcome.getLinkPicurl(), qwWelcome.getCorpId());
                qwGroupWelcomeTemplateParam.setLinkPicurl(uploadimgOne.getUrl());

            }
            qwGroupWelcomeTemplateParam.setType(3);
            qwGroupWelcomeTemplateParam.setLinkTitle(qwWelcome.getLinkTitle());
            qwGroupWelcomeTemplateParam.setLinkDesc(qwWelcome.getLinkDesc());
            qwGroupWelcomeTemplateParam.setLinkUrl(qwWelcome.getLinkUrl());


        }

        //小程序
        if (qwWelcome.getWelcomeType()==3){
            return R.error("暂时无法上传小程序");
        }
        //文件
        if (qwWelcome.getWelcomeType()==4){
            File fileOne = urlToFile(qwWelcome.getFileUrl());
            QwUploadResult file = qwApiService.upload(fileOne, "file", qwWelcome.getCorpId());
            qwWelcome.setFileMediaId(file.getMediaId());
            qwGroupWelcomeTemplateParam.setFileMediaId(file.getMediaId());
            qwGroupWelcomeTemplateParam.setType(5);
            qwGroupWelcomeTemplateParam.setCreatedAt(file.getCreatedAt());

            fileOne.delete();
        }

        //视频
        if (qwWelcome.getWelcomeType()==5){

            File fileOne = urlToFile(qwWelcome.getVideoUrl());
            QwUploadResult file = qwApiService.upload(fileOne, "video", qwWelcome.getCorpId());
            qwWelcome.setVideoMediaId(file.getMediaId());
            qwGroupWelcomeTemplateParam.setVideoMediaId(file.getMediaId());
            qwGroupWelcomeTemplateParam.setType(6);
            qwGroupWelcomeTemplateParam.setCreatedAt(file.getCreatedAt());
            fileOne.delete();
        }
        QwResult qwResult = qwApiService.editGroupWelcomeTemplate(qwGroupWelcomeTemplateParam, qwWelcome.getCorpId());
        if (qwResult.getErrcode()!=0){
            return R.error("素材更新失败:"+qwResult.getErrmsg());
        }

        return   R.ok().put("data",qwWelcomeMapper.updateQwWelcome(qwWelcome));
    }

//    @Override
//    public R updateQwWelcome(QwWelcome qwWelcome, MultipartFile fileOne, MultipartFile fileTwo) throws IOException {
//        qwWelcome.setUpdateTime(DateUtils.getNowDate());
//        //发送消息体
//        QwGroupWelcomeTemplateParam qwGroupWelcomeTemplateParam=new QwGroupWelcomeTemplateParam();
//
//        qwGroupWelcomeTemplateParam.setTemplateId(qwWelcome.getTemplateId());
//        qwGroupWelcomeTemplateParam.setContent(qwWelcome.getTextContent());
//        qwGroupWelcomeTemplateParam.setNotify(qwWelcome.getNotify()==1?true:false);
//        //上传素材
//        QwAddWelcomeResult qwAddWelcomeResult=null;
//
//        //文字+图片
//        if (qwWelcome.getWelcomeType()==1&& !StringUtil.strIsNullOrEmpty(qwWelcome.getImagePicUrl())){
//
//            File file = urlToFile(qwWelcome.getImagePicUrl());
//            QwUploadImgResult uploadimg = qwApiService.uploadimg(file, qwWelcome.getCompanyId());
//            qwWelcome.setImagePicUrl(uploadimg.getUrl());
//
//            qwGroupWelcomeTemplateParam.setImagePicUrl(uploadimg.getUrl());
//            qwGroupWelcomeTemplateParam.setType(2);
//            file.delete();
//        }
//        //图文
//        if (qwWelcome.getWelcomeType()==2
//                &&!StringUtil.strIsNullOrEmpty(qwWelcome.getLinkUrl())
//                &&!StringUtil.strIsNullOrEmpty(qwWelcome.getLinkPicurl())){
//
//            File LinkPicurl = urlToFile(qwWelcome.getLinkPicurl());
//            File LinkUrl = urlToFile(qwWelcome.getLinkUrl());
//
//            QwUploadImgResult uploadimgOne = qwApiService.uploadimg(LinkPicurl, qwWelcome.getCompanyId());
//            QwUploadImgResult uploadimgTwo = qwApiService.uploadimg(LinkUrl, qwWelcome.getCompanyId());
//
//            qwGroupWelcomeTemplateParam.setType(3);
//            qwGroupWelcomeTemplateParam.setLinkTitle(qwWelcome.getLinkTitle());
//            qwGroupWelcomeTemplateParam.setLinkPicurl(uploadimgOne.getUrl());
//            qwGroupWelcomeTemplateParam.setLinkDesc(qwWelcome.getLinkDesc());
//            qwGroupWelcomeTemplateParam.setLinkUrl(uploadimgTwo.getUrl());
//
//            LinkPicurl.delete();
//            LinkUrl.delete();
//
//        }
//
//        //小程序
//        if (qwWelcome.getWelcomeType()==3){
//            return R.error("暂时无法上传小程序");
//        }
//        //文件
//        if (qwWelcome.getWelcomeType()==4){
//            QwUploadResult file = qwApiService.upload(fileOne, "file", qwWelcome.getCompanyId());
//            qwGroupWelcomeTemplateParam.setFileMediaId(file.getMediaId());
//            qwGroupWelcomeTemplateParam.setType(5);
//            qwGroupWelcomeTemplateParam.setCreatedAt(file.getCreatedAt());
//        }
//
//        //视频
//        if (qwWelcome.getWelcomeType()==5){
//            QwUploadResult file = qwApiService.upload(fileOne, "video", qwWelcome.getCompanyId());
//            qwGroupWelcomeTemplateParam.setVideoMediaId(file.getMediaId());
//            qwGroupWelcomeTemplateParam.setType(6);
//            qwGroupWelcomeTemplateParam.setCreatedAt(file.getCreatedAt());
//        }
//        QwResult qwResult = qwApiService.editGroupWelcomeTemplate(qwGroupWelcomeTemplateParam, qwWelcome.getCompanyId());
//        if (qwResult.getErrcode()!=0){
//            return R.error("素材更新失败");
//        }
//
//        return   R.ok().put("data",qwWelcomeMapper.updateQwWelcome(qwWelcome));
//    }

    /**
     * 删除入群欢迎语管理信息
     *
     * @param welcomeId 入群欢迎语管理主键
     * @return 结果
     */
    public R deleteQwWelcomeByWelcomeId(Long welcomeId, String templateId)
    {
        QwWelcome qwWelcome = qwWelcomeMapper.selectQwWelcomeByWelcomeId(welcomeId);
        QwResult qwResult = qwApiService.delGroupWelcomeTemplate(templateId, qwWelcome.getCorpId());
        if (qwResult.getErrcode()!=0){
            return R.error("素材删除失败"+qwResult.getErrmsg());
        }
        return R.ok().put("data",qwWelcomeMapper.deleteQwWelcomeByWelcomeId(welcomeId));
    }

    /**
     *  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 ""; // 如果没有扩展名，返回空字符串
    }
}
