using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using dodohold.core;
using Dataoke;
using System.Text.RegularExpressions;
using Org.BouncyCastle.Ocsp;
using System.Diagnostics;
using TencentCloud.Fmu.V20191213.Models;
using Microsoft.VisualBasic;
using System.Text.Json;
using static System.Runtime.InteropServices.JavaScript.JSType;
using System.Security.Cryptography;
using Google.Protobuf.WellKnownTypes;
using System.Threading.Channels;
using TencentCloud.Tione.V20211111.Models;


namespace molilian.core
{
    public partial class ToolParsePlus
    {
        private static string _end_point;
        static ToolParsePlus()
        {
            _end_point = Environment.GetEnvironmentVariable("EndPoint");
        }

        public static string GetLink(string content)
        {
            if (string.IsNullOrEmpty(content)) return content;
            string result = content;
            //string pattern = @"https?:\/\/?([\da-z\.-]+)\.([a-z]{2,6})(:\d{1,5})?([\/\w\.-]*)*\/?(#[\S]+)?(\?[\S]+)?";
            Regex regex = new(AlimamaPlus._url_pattern);
            MatchCollection matches = regex.Matches(content);

            foreach (Match m in matches.Cast<Match>())
            {
                string url = m.Value;
                return url;
            }
            return string.Empty;
        }

        public static ToolParseDataDTO GetFormattedObject(TkChannelEnum type, string content, string ip = "", string oaid = "")
        {
            string itemName = string.Empty;
            switch (type)
            {
                case TkChannelEnum.bdpan:
                    itemName = "打开百度网盘";
                    break;
                case TkChannelEnum.wemeet:
                    itemName = "加入腾讯会议";
                    break;

            }

            return new ToolParseDataDTO()
            {
                message = string.Empty,
                success = false,
                content = content,
                ip = ip,
                oaid = oaid,
                elapsedTime = 0,
                create_time = DateTime.Now,
                itemName = itemName,
                end_point = _end_point,
            };
        }


        public static string GetPanLink(string text, ref string surl, ref string pwd)
        {
            surl = string.Empty;
            pwd = string.Empty;

            text = text.Replace("pan。baidu。com", "pan.baidu.com");

            string result = string.Empty;
            string linkPattern = @"(https?://pan\.baidu\.com/s/[A-Za-z0-9?\-_=]+)";
            string codePattern = @"提取码[：:]\s*([A-Za-z0-9]{4})";
            Regex linkRegex = new(linkPattern);
            Regex codeRegex = new(codePattern);

            Match linkMatch = linkRegex.Match(text);
            if (linkMatch.Success)
            {
                result = linkMatch.Groups[1].Value;

                if (result.Contains("?pwd="))
                {
                    pwd = result.GetContentPart("?pwd=", "");
                    surl = result.GetContentPart("/s/1", "?pwd=");
                }
                else
                {
                    surl = result.GetContentPart("/s/1", "");

                    // 匹配提取码
                    Match codeMatch = codeRegex.Match(text);
                    if (codeMatch.Success)
                    {
                        pwd = codeMatch.Groups[1].Value;
                    }
                }
            }

            return result;
        }


        public static void PanParse(string content, ref ToolParseDataDTO result, CancellationToken cancellationToken = default)
        {
            string message = "OK";
            string surl = string.Empty, pwd = string.Empty;
            string shortLinkurl = GetPanLink(content, ref surl, ref pwd);
            result.shortLinkurl = shortLinkurl;
            result.deeplink_url = string.IsNullOrEmpty(shortLinkurl) ? "" : "bdnetdisk://n/action.EXTERNAL_ACTIVITY";

            if (string.IsNullOrEmpty(surl))
            {
                result.channel = TkChannelEnum.bdpan;
                result.content = content;
                result.success = false;
                result.message = "转链失败";
                result.reason = "内容不匹配";
                return;
            }

            string deeplink_url = $"bdnetdisk://n/action.SHARE_LINK?surl={surl}";
            if (!string.IsNullOrEmpty(pwd)) deeplink_url += $"&pwd={pwd}";
            result.deeplink_url = deeplink_url;
            result.channel = TkChannelEnum.bdpan;
            result.content = content;
            result.success = true;
            result.message = message;
        }

        public static async Task<ToolParseDataDTO> WemeetParseAsync(string content, ToolParseDataDTO result, CancellationToken cancellationToken = default)
        {
            string message = "OK";
            string wemeetId = await GetWemeetIdAsync(content);
            var deeplink_url = "";
            result.deeplink_url = deeplink_url;
            if (!string.IsNullOrEmpty(wemeetId))
            {
                result.deeplink_url = $"wemeet://page/inmeeting?meeting_code={wemeetId}";
                result.channel = TkChannelEnum.wemeet;
                result.content = wemeetId;
                result.success = true;
                result.message = message;
                return result;
            }

            var url = await GetWemeetUrlAsync(content);
            if (!string.IsNullOrEmpty(url))
            {
                result.deeplink_url = $"wemeet://page/external_link?url={url.UrlEncode()}";
                result.channel = TkChannelEnum.wemeet;
                result.content = wemeetId;
                result.success = true;
                result.message = message;
                return result;
            }

            result.channel = TkChannelEnum.wemeet;
            result.content = content;
            result.success = false;
            result.message = "转链失败";
            result.reason = "内容不匹配";
            return result;
        }
        public static async Task<string> GetWemeetUrlAsync(string content)
        {
            string pattern = @"https?:\/\/meeting\.tencent\.com[^\s]*";

            Regex regex = new Regex(pattern);
            Match match = regex.Match(content);
            string url = string.Empty;
            // 判断是否匹配成功
            if (match.Success)
            {
                // 提取会议编码
                url = match.Groups[0].Value;
            }
            return url;
        }
        public static async Task<string> GetWemeetIdAsync(string content)
        {
            string pattern = @"#腾讯会议：(\d{3}-\d{3}-\d{3})";
            Regex regex = new Regex(pattern);
            Match match = regex.Match(content);
            string meetingCode;
            // 判断是否匹配成功
            if (match.Success)
            {
                // 提取会议编码
                meetingCode = match.Groups[1].Value;
                meetingCode = meetingCode.Replace("-", "");
                if (!string.IsNullOrEmpty(meetingCode)) return meetingCode;
            }
            meetingCode = await GetWemeetIdFromUrlAsync(content);
            return meetingCode;
        }

        public static async Task<string> GetDesiredUrlAsync(string url)
        {
            try
            {
                WebClientUtility client = new()
                {
                    AllowAutoRedirect = false
                };
                var response = await client.RequestAsync(url);
                if (!response.Successed) return null;

                return response.Body();
            }
            catch (Exception ex)
            {
            }
            return null;
        }



        public static async Task<string> GetMeetingCodeAsync(string url)
        {
            try
            {
                url = url.Replace("/dm/", "/l/");
                WebClientUtility client = new()
                {
                    AllowAutoRedirect = false
                };
                var response = await client.RequestAsync(url);
                if (!response.Successed) return null;
                if (response.ResponseMessage.StatusCode == System.Net.HttpStatusCode.Redirect)
                {
                    string redirectUrl = response.ResponseMessage?.Headers?.Location.ToString();
                    //https://meeting.tencent.com/detail.html?mtoken=uGjRUgQFhvDCowb28odPQ__&meetingcode=116399514&sdkappid=1400115281&show8k=0

                    string meetingCode = redirectUrl.GetContentPart("&meetingcode=", "&");
                    return meetingCode;
                }
            }
            catch (Exception ex)
            {
            }
            return null;
        }

        public static async Task<string> GetWemeetIdFromUrlAsync(string content)
        {
            {
                string pattern = @"https?:\/\/meeting\.tencent\.com\/p\/([0-9]+)";

                Regex regex = new Regex(pattern);
                Match match = regex.Match(content);

                // 判断是否匹配成功
                if (match.Success)
                {
                    // 提取会议编码
                    string meetingCode = match.Groups[1].Value;
                    return meetingCode;
                }
            }

            {
                content = content.Replace("meeting.tencent.com/dw/", "meeting.tencent.com/dm/");
                string pattern = @"https?:\/\/meeting\.tencent\.com\/dm\/[a-zA-Z0-9]+";

                Regex regex = new Regex(pattern);
                Match match = regex.Match(content);

                // 判断是否匹配成功
                if (match.Success)
                {
                    // 提取会议编码
                    string meeting_url = match.Value;

                    //重定向获取会议Code
                    string meetingCode = await GetMeetingCodeAsync(meeting_url);
                    if (string.IsNullOrEmpty(meetingCode))
                    {
                        //正文获取Code
                        string body = await GetDesiredUrlAsync(meeting_url);
                        if (string.IsNullOrEmpty(body)) return string.Empty;
                        meetingCode = body.GetContentPart("\"meeting_code\":\"", "\"");
                    }
                    return meetingCode;
                }
                return string.Empty;
            }
        }
    }
}
