package org.shop.crop.dto;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import org.shop.crop.dao.CropMessage;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @description 拉取基础信息dto
 * @date 2024/11/21 17:50
 */
@Data
public class BaseMessageDto {
    /**
     * 消息id，消息的唯一标识
     */
    @JSONField(name = "msgid")
    private String msgId;

    /**
     * 消息动作
     */
    @JSONField(name = "action")
    private String action;

    /**
     * 消息发送方id
     */
    @JSONField(name = "from")
    private String from;

    /**
     * 消息接收方列表
     */
    @JSONField(name = "tolist")
    private List<String> toList;

    /**
     * 群聊消息的id
     */
    @JSONField(name = "roomid")
    private String roomId;


    /**
     * 消息类型
     */
    @JSONField(name = "msgtype")
    private String msgType;

    /**
     * 消息发送的时间
     */
    @JSONField(name = "msgtime")
    private Long  msgTime;
    /**
     * 消息类型
     */
    @JSONField(name = "text")
    private BaseMessageTextDto text;

    @JSONField(name = "file")
    private BaseMessageFileDto file;

    // getter setter

    public CropMessage convertToMessage(){
        CropMessage message = new CropMessage();
        message.setMsgId(this.msgId);
        message.setAction(this.action);
        message.setFrom(this.from);
        message.setMsgtype(this.msgType);
        message.setRoomid(this.roomId);
       // id数组转为字符串
        message.setTolist(JSON.toJSONString(this.toList));
        message.setToId(this.toList.get(0));
        if(this.getText() != null){
            message.setKeyword(this.getText().getContent());
        }

        if(this.getFile() != null){
            message.setKeyword(this.getFile().getFilename());
        }
        // 格式化时间
        if(this.getMsgTime() != null){
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");;
            long seconds = this.getMsgTime() / 1000;
            LocalDateTime dateTime = LocalDateTime.ofInstant(
                    Instant.ofEpochSecond(seconds),
                    ZoneId.systemDefault()
            );
            String timeStr=dateTime.format(formatter);
            message.setMsgtime(timeStr);
        }


        return message;
    }

}
