package com.miaxis.wx.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.miaxis.common.constant.Constants;
import com.miaxis.common.utils.http.HttpUtils;
import com.miaxis.feign.dto.WxGzhMini;
import com.miaxis.feign.dto.WxMessageCusom;
import com.miaxis.feign.dto.WxMessageTemplate;
import com.miaxis.feign.dto.WxQrTicket;
import com.miaxis.feign.service.IWxSendService;
import com.miaxis.spread.domain.WxSpreadRelation;
import com.miaxis.spread.service.IWxSpreadRelationService;
import com.miaxis.wx.service.IWxMessageEvenService;
import com.miaxis.wx.service.IWxTicketService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author wwl
 * @version 1.0
 * @date 2021/10/27 14:35
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class WxMessageEvenServiceImpl implements IWxMessageEvenService {

    private final RedisTemplate redisTemplate;

    private final IWxSendService wxSendService;

    private final IWxTicketService wxTicketService;

    private final IWxSpreadRelationService wxSpreadRelationService;

    @Value("${file.ticketPath}")
    private String ticketPath;

    @Value("${wxgzh.mediaUpload}")
    private String mediaUpload;

    @Value("${cos.bucketName}")
    private String bucketName;

    @Value("${cos.path}")
    private String path;

    @Value("${cos.preffix}")
    private String preffix;


    /**
     * 扫码关注事件
     * @param fromUserName 发送方帐号（一个OpenID）
     * @param ticket 二维码的ticket
     * @param token 凭证
     * @param userName 微信名称
     * @return
     */
    @Override
    public String scanSubscribeEvent(String fromUserName, String ticket,String token,String userName) {

        String message = "";
        //判断是否存在父、子级推广关系
        List<WxSpreadRelation> spreadRelations = wxSpreadRelationService.list(new QueryWrapper<WxSpreadRelation>().eq("openid", fromUserName));
        List<WxSpreadRelation> spreads = wxSpreadRelationService.list(new QueryWrapper<WxSpreadRelation>().eq("parent_openid", fromUserName));
        String openid = (String) redisTemplate.opsForValue().get(Constants.GZH_TICKET_KEY + ticket);

        if (spreadRelations.isEmpty() && spreads.isEmpty()){
            //保存推广关系表
            WxSpreadRelation wxSpreadRelation = new WxSpreadRelation();
            wxSpreadRelation.setOpenid(fromUserName);
            wxSpreadRelation.setParentOpenid(openid);
            wxSpreadRelationService.save(wxSpreadRelation);

            //推送绑定模板信息到上级
            messageTemplateSend(openid,token,userName);

            message = "已成功绑定推广关系！";
        }else if (!spreads.isEmpty()){
            message = "已存在下级绑定关系！";
        }else {
            message = "已存在推广关系！";
        }
        return message;
    }


    /**
     * click获取推广二维码事件
     * @param fromUserName 发送方帐号（一个OpenID）
     * @param token 凭证
     * @return
     */
    @Override
    public String gainTicketEvent(String fromUserName,String token) {

        //发送客服信息
        messageCustomSend(fromUserName,token);

        // 根据fromUserName查询缓存 判断用户推广码是否过期
        if (redisTemplate.hasKey(Constants.GZH_MATERIAL_KEY + fromUserName)){
            String mediaId = (String) redisTemplate.opsForValue().get(Constants.GZH_MATERIAL_KEY + fromUserName);
            return mediaId;
        }

        //生成带参数二维码ticket（永久）
        WxQrTicket wxQrTicket = new WxQrTicket();
        wxQrTicket.setExpire_seconds(259200);//3天
        wxQrTicket.setAction_name("QR_SCENE");//临时
        JSONObject jsonObject1 = new JSONObject();
        JSONObject jsonObject2 = new JSONObject();
        jsonObject1.put("scene_id","123");
        jsonObject2.put("scene",jsonObject1);
        wxQrTicket.setAction_info(jsonObject2);
        String wxTicketResult = wxSendService.generateTicket(token, wxQrTicket);
        JSONObject jsonStr = JSONObject.parseObject(wxTicketResult);
        log.info("---------ticket-------" + jsonStr);

        //获取用户信息
        String userInfoResult = wxSendService.userInfo(token, fromUserName, "zh_CN");
        JSONObject userInfo = JSONObject.parseObject(userInfoResult);
        log.info("---------userInfo-------" + userInfo);

        //根据ticket生成二维码图片存储
        File ticketFile = QrCodeUtil.generate(
                jsonStr.getString("url"), //二维码内容
                QrConfig.create().setImg(ticketPath + "logo.jpg"), //附带logo
                FileUtil.file(ticketPath + fromUserName + ".jpg")//写出到的文件
        );

        ImgUtil.pressImage(
                FileUtil.file(ticketPath+"jinpai.jpg"),
                FileUtil.file(ticketPath+fromUserName+"_img.jpg"),
                ImgUtil.read(FileUtil.file(ticketPath+fromUserName+".jpg")), //水印图片
                0, //x坐标修正值。 默认在中间，偏移量相对于中间偏移
                -340, //y坐标修正值。 默认在中间，偏移量相对于中间偏移
                1.0f
        );

        ImgUtil.pressText(
                FileUtil.file(ticketPath+fromUserName+"_img.jpg"),
                FileUtil.file(ticketPath+fromUserName+"_text1.jpg"),
                userInfo.getString("nickname"), Color.black, //文字
                new Font("黑体", Font.BOLD, 30), //字体
                0, //x坐标修正值。 默认在中间，偏移量相对于中间偏移
                -500, //y坐标修正值。 默认在中间，偏移量相对于中间偏移
                1.0f//透明度：alpha 必须是范围 [0.0, 1.0] 之内（包含边界值）的一个浮点数字
        );

        DateTime date = DateUtil.date();
        Date newDate = DateUtil.offsetDay(date, 3);
        String dateStr = DateUtil.format(newDate, "yyyy-MM-dd");
        log.info(dateStr);

        ImgUtil.pressText(
                FileUtil.file(ticketPath+fromUserName+"_text1.jpg"),
                FileUtil.file(ticketPath+fromUserName+"_text2.jpg"),
                "二维码有效期至："+dateStr, Color.black, //文字
                new Font("黑体", Font.BOLD, 28), //字体
                0, //x坐标修正值。 默认在中间，偏移量相对于中间偏移
                -80, //y坐标修正值。 默认在中间，偏移量相对于中间偏移
                1.0f//透明度：alpha 必须是范围 [0.0, 1.0] 之内（包含边界值）的一个浮点数字
        );


        try {
            File textTwoFile = new File(ticketPath + fromUserName+"_text2.jpg");
            //上传素材
            String path = mediaUpload + token + "&type=image";
            String result = HttpUtils.connectHttpsByPost(path,textTwoFile);
            result = result.replaceAll("[\\\\]", "");
            JSONObject resultJSON = JSONObject.parseObject(result);
            log.info("------result:" + resultJSON);

            //缓存用户推广码相关信息
            redisTemplate.opsForValue().set(Constants.GZH_TICKET_KEY+jsonStr.getString("ticket"),fromUserName,259200, TimeUnit.SECONDS);
            redisTemplate.opsForValue().set(Constants.GZH_MATERIAL_KEY+fromUserName,resultJSON.getString("media_id"),259200, TimeUnit.SECONDS);

            //删除服务器文件
            File imgFile = new File(ticketPath + fromUserName+"_img.jpg");
            File textOneFile = new File(ticketPath + fromUserName+"_text1.jpg");
            if (ticketFile.exists() && imgFile.exists() && textOneFile.exists() && textTwoFile.exists()) {
                if (ticketFile.delete()) {
                    log.info("删除:" + ticketFile.getName() + "成功！");
                } else {
                    log.info("删除:" + ticketFile.getName() + "失败！");
                }
                if (imgFile.delete()) {
                    log.info("删除:" + imgFile.getName() + "成功！");
                } else {
                    log.info("删除:" + imgFile.getName() + "失败！");
                }
                if (textOneFile.delete()) {
                    log.info("删除:" + textOneFile.getName() + "成功！");
                } else {
                    log.info("删除:" + textOneFile.getName() + "失败！");
                }
                if (textTwoFile.delete()) {
                    log.info("删除:" + textTwoFile.getName() + "成功！");
                } else {
                    log.info("删除:" + textTwoFile.getName() + "失败！");
                }
            }

            return resultJSON.getString("media_id");
        } catch (Exception e) {
            log.info("-----异常------click获取推广二维码事件");
        }
        return null;
    }


    /**
     * 发送客服消息
     * @param fromUserName
     * @param token
     */
    private void messageCustomSend(String fromUserName,String token){

        WxMessageCusom wxMessageCusom = new WxMessageCusom();
        wxMessageCusom.setTouser(fromUserName);
        wxMessageCusom.setMsgtype("text");
        HashMap<String, Object> contentMap = new HashMap<>();
        contentMap.put("content","正在努力生成推广码请稍等...");
        wxMessageCusom.setText(contentMap);
        String send = wxSendService.messageCustomSend(token, wxMessageCusom);
        JSONObject jsonObject = JSONObject.parseObject(send);
        log.info("回复客服消息：[{}],响应信息：[{}]",contentMap,jsonObject);
    }

    /**
     * 发送模板信息
     * @param openid
     * @param token
     * @param nickName
     */
    private void messageTemplateSend(String openid,String token,String nickName){

        WxMessageTemplate messageTemplate = new WxMessageTemplate();
        messageTemplate.setTouser(openid);
        messageTemplate.setTemplate_id("P4nKRB6L3dmhBjEj1VeE0gr9yC11Z0uBTAuu-XKmIjs");
        messageTemplate.setUrl("https://jpcj-h5.zzxcx.net/myBranch");
        WxGzhMini wxGzhMini = new WxGzhMini();
        messageTemplate.setMiniprogram(wxGzhMini);

        JSONObject jsonObject = new JSONObject();
        JSONObject first = new JSONObject();
        JSONObject keyword1 = new JSONObject();
        JSONObject keyword2 = new JSONObject();
        JSONObject keyword3 = new JSONObject();
        first.put("value","您好，已成功绑定您的账号！");
        first.put("color","#173177");
        keyword1.put("value",nickName);
        keyword1.put("color","#173177");
        keyword2.put("value", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm"));
        keyword2.put("color","#173177");
        keyword3.put("value","此用户下单后您将获得对应抽成，"+"\n点击 我的->我要提现,即可提现到余额！"+"\n点击查看已绑定信息！");
        keyword3.put("color","#173177");
        jsonObject.put("first",first);
        jsonObject.put("keyword1",keyword1);
        jsonObject.put("keyword2",keyword2);
        jsonObject.put("keyword3",keyword3);
        messageTemplate.setData(jsonObject);
        String result = wxSendService.messageTemplateSend(token,messageTemplate);
        JSONObject parseObject = JSONObject.parseObject(result);
        log.info("模板消息：[{}],响应信息：[{}]",messageTemplate,parseObject);

    }




}
