import datetime
import json
from configs.config import env
from src.libs.db_link import LinkMysql
from src.libs.functions import get_now_timestamp, str_to_time, AES_Encrypt, call_im_interface
from src.libs.log_utils import Logger
from src.modules.examine import Examinecontent, Examinecomment
from src.modules.friend import FriendMessage, FriendGive, FriendComment


def save_friends(data):
    try:
        friendmessage = FriendMessage().set_attrs(data).direct_commit_()
        Logger().logger.info(f"发送朋友圈参数:{friendmessage}")
        data['fcmid'] = friendmessage.id
        Examinecontent().set_attrs(data).direct_commit_()
    except Exception as e:
        Logger().logger.info(f"发送朋友圈失败:{e}")
        return None
    return friendmessage.id


def save_comment(data):
    try:
        data['create_time'] = datetime.datetime.now()
        Logger().logger.info(f"评论存入参数:{data}")
        friendcomment = FriendComment().set_attrs(data).direct_commit_()
        print(data)
        Examinecomment().set_attrs(data).direct_commit_()
    except Exception as e:
        print(e)
        return 0
    return friendcomment


def get_infoname(data):
    result = []
    uids = [item.get("uid", "") for item in data]
    if uids:
        if len(uids) == 1:
            sql = f"SELECT nickname,user_avatar_file_name,bg_image,user_uid,energy_ball_image FROM missu_users  where user_uid={uids[0]}"
        else:
            sql = f"SELECT nickname,user_avatar_file_name,bg_image,user_uid,energy_ball_image FROM missu_users  where user_uid in{tuple(uids)}"

        user_info = LinkMysql(env.BUSINESS).query_mysql(sql)
        for i in range(len(data)):
            for s in range(len(user_info)):
                if data[i].get("uid") == user_info[s].get("user_uid"):
                    data[i]['create_time'] = str_to_time(data[i].get("create_time", ""))
                    data[i]['nick_name'] = user_info[s].get("nickname", "")
                    data[i]['user_avatar_file_name'] = user_info[s].get("user_avatar_file_name", "")
                    data[i]['bg_image'] = user_info[s].get("bg_image", "")
                    data[i]['energy_ball_image'] = user_info[s].get("energy_ball_image", "")
                    result.append(data[i])
    return result


class FriendMessageNotice(object):
    def __init__(self, fcmid, praise, uid):
        self.fcmid = fcmid
        self.praise = praise
        self.uid = uid
        self.to_uuid = None  # 朋友圈发送者id
        Logger().logger.info(f"FriendMessageNotice接受参数:{self.fcmid}，，，praise：{self.praise},,,uid{self.uid}，，"
                             f"to_uuid:{self.to_uuid}")

    def query_friends_info(self, user_id):
        """获取朋友圈发送者"""
        sql = f"select uid from missu_friend_message where id={user_id}"
        user_info = LinkMysql(env.BUSINESS).query_mysql(sql)
        if user_info:
            self.to_uuid = user_info[0]['uid']

    def query_user_head_portrait(self, user_id=None):
        """获取用户头像"""
        if not user_id:
            user_id = self.uid
        sql = f"select nickname,user_avatar_file_name from missu_users where user_uid={user_id}"
        user_info = LinkMysql(env.BUSINESS).query_mysql(sql)
        if user_info:
            return user_info[0]
        return {}

    def query_praise_comment(self):
        """查看用户收到点赞，评论"""

        Logger().logger.info(f'接受参数fcmid:{self.fcmid}，，，uid：{self.uid}')
        self.query_friends_info(self.fcmid)
        user_data = self.query_user_head_portrait()
        source_user = self.query_user_head_portrait(self.to_uuid)
        friend_info = CircleOfFriends().query_info(self.praise.fcmid)
        friend_img_str = friend_info.get('file_name', '')
        friend_img_list = friend_img_str.split(',')
        if friend_img_list:
            img_str = friend_img_list[0]
            if 'mp4' in img_str:
                img_str = img_str.replace('mp4', 'jpg')
        else:
            img_str = ""
        if not user_data:
            return
        try:
            content = self.praise.content
        except Exception as e:
            content = ""
        if not content:  # 点赞数据
            add_data = {
                "id": self.praise.id,
                "fcmid": self.praise.fcmid,
                "uid": self.praise.uid,
                "head_path": user_data.get('user_avatar_file_name'),  # 点赞者头像
                "nick_name": user_data.get('nickname'),  # 点赞者名字
                "source_head_path": source_user.get('user_avatar_file_name'),  # 朋友圈发送者头像
                "source_name": source_user.get('nickname'),  # 朋友圈发送者名字
                "friend_path": img_str,
                "coding": "1",
                "create_time": str_to_time(str(self.praise.create_time))
            }
        else:  # 评论数据
            add_data = {
                "id": self.praise.id,
                "review_to": self.praise.review_to,
                "fcmid": self.praise.fcmid,
                "uid": self.praise.uid,
                "content": self.praise.content,
                "head_path": user_data.get('user_avatar_file_name'),
                "nick_name": user_data.get('nickname'),
                "source_head_path": source_user.get('user_avatar_file_name'),
                "source_name": source_user.get('nickname'),
                "friend_path": img_str,
                "coding": "2",
                "create_time": str_to_time(str(self.praise.create_time))
            }
        data = {
            "processorId": 1008,
            "jobDispatchId": 1,
            "actionId": 3,
            "newData": json.dumps({"to_uid": self.to_uuid, "typeu": "53", "msg": add_data})
        }
        aes = AES_Encrypt(json.dumps(data))
        Logger().logger.info(f'请求IM参数:{data}，，，密文：{aes}')
        result = call_im_interface(aes)
        Logger().logger.info(f'请求IM接口:{result.status_code}')
        if result and result.status_code == 200:
            res = json.loads(result.text)
            Logger().logger.info(f"接口返回结果:{res.get('success')}")


class CircleOfFriends(object):
    """朋友圈详情"""

    @staticmethod
    def query_info(fc_mid):
        sql = f"select uid,res_type,content,file_name,location,create_time from missu_friend_message where id={fc_mid}"
        friends = LinkMysql(env.BUSINESS).query_mysql(sql)
        if friends:
            friend = friends[0]
            friend['create_time'] = str_to_time(str(friend['create_time']))
            return friend
        return {}
