package com.ruoyi.message.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.controller.resp.GoeasyResult;
import com.ruoyi.enums.user.UserEnums;
import com.ruoyi.frequency.customer.entity.Customer;
import com.ruoyi.frequency.customer.mapper.CustomerMapper;
import com.ruoyi.frequency.store.entity.Store;
import com.ruoyi.frequency.store.mapper.StoreMapper;
import com.ruoyi.message.frequency.goeasymessage.entity.GoeasyMessage;
import com.ruoyi.message.frequency.goeasymessage.service.GoeasyMessageService;
import com.ruoyi.vo.RyController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;


/**
 * goeasy消息
 *
 * @author liwenlong
 */
@CrossOrigin
@RestController
@RequestMapping("/api/goeasy")
@Slf4j
@Api(tags = "goeasy消息")
public class ApiGoeasyMessageController extends RyController {

    @Autowired
    private GoeasyMessageService goeasyMessageService;


    @RequestMapping("/goeasyMessage")
    @ApiOperation(value = "数据同步Webhook", notes = "数据同步Webhook")
    public GoeasyResult goeasyMessage(HttpServletRequest request) {
        log.info("进入goeasy历史消息通知");

        String content = request.getParameter("content");
        System.out.println(content);

        if (content == null || "".equals(content)) {
            return GoeasyResult.success();
        }

        //判断请求签名是否合法
        String goeasy_signature = request.getHeader("x-goeasy-signature");
        log.info("goeasy_signature:" + goeasy_signature);
        String signature = goeasyWebhookSignature(secretKey, content);
        log.info("signature:" + signature);
        if (!signature.equals(goeasy_signature)) {
            return GoeasyResult.success();
        }

        JSONArray jsonArray = JSONObject.parseArray(content);
        System.out.println(jsonArray);

        List<GoeasyMessage> goeasyMessages = jsonArray.stream().filter(s -> {
            JSONObject messageJson = JSONObject.parseObject(s.toString());
            return !messageJson.containsKey("channel");
        }).map(s -> {
            JSONObject messageJson = JSONObject.parseObject(s.toString());
            GoeasyMessage goeasyMessage = new GoeasyMessage();
            //每条消息唯一标识，可用于去重操作
            goeasyMessage.setMessageId((String) messageJson.get("messageId"));
            //消息类型
            goeasyMessage.setType((String) messageJson.get("type"));
            //发送方userId
            goeasyMessage.setSenderId((String) messageJson.get("senderId"));
            //解析发送用户
            String[] sender = goeasyMessage.getSenderId().split("_");
            if (sender.length == 2) {
                goeasyMessage.setSenderUserType(UserEnums.valueOf(sender[0]).getCode());
                goeasyMessage.setSenderUserId(Long.valueOf(sender[1]));
            }
            //接收方userId
            goeasyMessage.setReceiverId((String) messageJson.get("receiverId"));
            //解析接收用户
            String[] receiver = goeasyMessage.getReceiverId().split("_");
            if (receiver.length == 2) {
                goeasyMessage.setReceiverUserType(UserEnums.valueOf(receiver[0]).getCode());
                goeasyMessage.setReceiverUserId(Long.valueOf(receiver[1]));
            }
            //消息体
            goeasyMessage.setPayload((String) messageJson.get("payload"));
            //发送的时间，可用于排序
            goeasyMessage.setGoeasyTime(DateUtil.date((Long) messageJson.get("timestamp")));
            System.out.println(goeasyMessage);

            if (goeasyMessage.getSenderUserType().equals(UserEnums.customer.getCode())) {
                Customer customer = customerMapper.selectById(goeasyMessage.getSenderUserId());
                if (customer != null) {
                    return goeasyMessage;
                }
            } else if (goeasyMessage.getSenderUserType().equals(UserEnums.store.getCode())) {
                Store store = storeMapper.selectById(goeasyMessage.getSenderUserId());
                if (store != null) {
                    return goeasyMessage;
                }
            }
            return null;

        }).collect(Collectors.toList());

        goeasyMessageService.goeasyMessage(goeasyMessages);


        log.info("goeasy历史消息通知结束");

        return GoeasyResult.success();
    }



    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private StoreMapper storeMapper;


    @Value("${push.goeasy.secretKey}")
    private String secretKey;

    public String goeasyWebhookSignature(String secretKey, String content) {
        try {
            SecretKeySpec signinKey = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(signinKey);
            byte[] rawHmac = mac.doFinal(content.getBytes("UTF8"));

            return new BASE64Encoder().encode(rawHmac);
        } catch (Exception e) {
            log.error("HMACSHA1 failed for key:{} and content:{}", secretKey, content, e);
            return null;
        }
    }

    public static void main(String[] args) {
    }

}
