package com.bjtdba.poster.service.Impl;

import com.bjtdba.entity.poster.SharePosters;
import com.bjtdba.entity.poster.SystemAttachment;
import com.bjtdba.entity.userCenter.User;
import com.bjtdba.poster.dao.SharePostersDao;
import com.bjtdba.poster.dao.SystemAttachmentDao;
import com.bjtdba.poster.dao.UserDao;
import com.bjtdba.poster.entity.Poster;
import com.bjtdba.poster.service.PosterService;
import com.bjtdba.poster.service.QrCodeService;
import com.bjtdba.poster.utils.FontUtil;
import com.bjtdba.poster.utils.PosterUtil;
import com.bjtdba.utils.ResponseUtil;
import com.bjtdba.utils.uploadDownload;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.font.FontDesignMetrics;

import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class PosterServiceImpl implements PosterService {
    @Autowired
    private PosterUtil posterUtil;
    @Autowired
    private SharePostersDao sharePostersDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private SystemAttachmentDao systemAttachmentDao;
    @Autowired
    private QrCodeService qrCodeService;

    @Value("${phpPath}")
    private String phpPath;
    @Override
    public Object select(String imgId,String uid,String type) throws Exception {

        log.info("去php获取二维码qrCodeUrl================== 开始");
        Map<String,Object> data=new HashMap<String,Object>();
        if(type==null){
            type="0";
        }
        /**
         * 先判断该用户  是否拥有该背景图片的邀请图片。如果有直接返回图片路径，如果没有在生成图片返回图片路径
         */
        SystemAttachment systemAttachment1 = systemAttachmentDao.selectAttachmentSrcByIdUidAndCategoryId(Integer.parseInt(uid), 9, Integer.parseInt(imgId),type);
        if(systemAttachment1!=null){
            String shareImgs = systemAttachment1.getAttachment_src();
            data.put("shareImgs",shareImgs);
            log.info("shareImgs=="+shareImgs);
            return ResponseUtil.ok(data);
        }

        /**
         * 根据图片id查询合成图片相关信息
         */
        Poster poster = new Poster();
        SharePosters sharePosters = sharePostersDao.selectSharePostersById(Integer.parseInt(imgId));
        User user = userDao.selectByUid(Integer.parseInt(uid));
        if(!sharePosters.getHead_coordinate().equals("0")){//需要头像、昵称
            //昵称
            poster.setName(user.getNickname());
            Font font = FontUtil.getFont(35);
            poster.setNameFont(font);
            poster.setNameColor(new Color(255, 255, 255));//颜色字体

            String[] qr_coordinateList = spli(sharePosters.getNickname_coordinate());
            //poster.setNameX(Integer.parseInt(qr_coordinateList[0]));//名字在海报的什么位置
            poster.setNameY(Integer.parseInt(qr_coordinateList[1]));
            //头像定位
            poster.setPortraitCodeUrl(user.getAvatar()!=null?user.getAvatar():"https://cdn.bjtdba.com/vod/image/2025-01-20/20250120125206881.png");
            String[] head_coordinateList = spli(sharePosters.getHead_coordinate());
            poster.setPortraitCodeX(Integer.parseInt(head_coordinateList[0]));
            poster.setPortraitCodeY(Integer.parseInt(head_coordinateList[1]));
            String[] head_sizeList = spli(sharePosters.getHead_size());
            poster.setPortraitCodeWidth(Integer.parseInt(head_sizeList[0]));
            poster.setPortraitCodeHeight(Integer.parseInt(head_sizeList[1]));
            /**
             * 计算昵称的位置坐标
             */
            FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font);
            String name = user.getNickname();
            int namepx = metrics.stringWidth(name);//昵称的长度像素
            int nameX = Integer.parseInt(qr_coordinateList[0]) - (namepx - Integer.parseInt(head_sizeList[0]))/2;//昵称横坐标
            poster.setNameX(nameX);//昵称在海报的什么位置
        }
        poster.setPathUrl(sharePosters.getImage());
        //画布宽高   背景图片
        poster.setWidth(560);
        poster.setHeight(995);
        //去php获取二维码
//        String qrCodeUrl=HttpUtil.doGet("https://test.bjtdba.com/api/invite_code?uid="+uid+"&imgId="+imgId,"");
//        String qrCodeUrl=HttpUtil.doGet(phpPath+"/api/invite_code?uid="+uid+"&imgId="+imgId,"");
//        log.info("去php获取二维码,请求地址"+phpPath+"/api/invite_code?uid="+uid+"&imgId="+imgId+"qrCodeUrl="+qrCodeUrl);
//        if(qrCodeUrl.equals("")){
//            return ResponseUtil.fail("生成失败，请稍后再试");
//        }
        String qrCodeUrl = null;
//        SystemAttachment systemAttachment = systemAttachmentDao.selectAttachmentSrcByIdUidAndCategoryId(Integer.parseInt(uid),8,null,null);
        if(systemAttachment1!=null){
            //二维码
            qrCodeUrl = systemAttachment1.getAttachment_src(); //二维码
        }else{
            //新建分享二维码
            String text = "https://api.hxxfb.com/share?spread="+uid;
            qrCodeUrl = qrCodeService.insterQrCode(Integer.parseInt(uid), text);
        }
        poster.setQrCodeUrl(qrCodeUrl);
        String[] qr_coordinateList = spli(sharePosters.getQr_coordinate());
        poster.setQrCodeX(Integer.parseInt(qr_coordinateList[0]));
        poster.setQrCodeY(Integer.parseInt(qr_coordinateList[1]));
        String[] qr_sizeList = spli(sharePosters.getQr_size());
        poster.setQrCodeWidth(Integer.parseInt(qr_sizeList[0]));
        poster.setQrCodeHeight(Integer.parseInt(qr_sizeList[1]));
        File file = posterUtil.drawImg(poster,Integer.parseInt(uid));
        FileInputStream input = new FileInputStream(file);
        MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(input));
        Map<String, String> qrCode = uploadDownload.qrCode(multipartFile);
        String url = qrCode.get("url");
        /**
         * 将上传的美化照片上传到cdn 并且将图片的url添加到数据库中
         */
        SystemAttachment systemAttachmentTool = new SystemAttachment();
        systemAttachmentTool.setAttachment_category_id(9);
        systemAttachmentTool.setAttachment_name(file.getName());
        systemAttachmentTool.setAttachment_src(url);
        systemAttachmentTool.setUser_type(1);
        systemAttachmentTool.setUser_id(Integer.parseInt(uid));
        systemAttachmentTool.setShare_image_id(sharePosters.getId());
        int attachment = systemAttachmentDao.insterSystemAttachment(systemAttachmentTool);
        qrCodeService.deleteDir(new File("/Users/hanyuxing"));
        data.put("shareImgs",url);
        log.info("去php获取二维码qrCodeUrl================== 结束");
        return ResponseUtil.ok(data);
    }

    /**
     * 分割字符串
     * @return
     */
    private String[] spli(String sp){
        String[] split = sp.split(",");
        return split;
    }

}
