using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Google.Protobuf.WellKnownTypes;
using Mall.Common.API;
using Mall.Common.Plugin;
using Mall.Model.Entity.User;
using Mall.Model.Extend.User;
using Mall.Module.User;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace Mall.WebApi.Controllers.ByteDance
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class ByteDanceController : BaseController
    {

        private readonly UserModule userModule = new UserModule();
        /// <summary>
        /// 保存客户formId
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ApiResult SaveFormId()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            int customerId = parmsJob.GetInt("customerId");
            string formId = parmsJob.GetStringValue("formId");
            // string openid = GetWx(code);
            RB_Member_User customerInfo = new RB_Member_User();
            //判断是否绑定了openid
            customerInfo = userModule.GetMemberUserInfo(customerId);
            if (customerInfo != null)
            {
                ByteDanceCustomer wechatExtend = new ByteDanceCustomer
                {
                    FormCreateDate = System.DateTime.Now,
                    FormId = formId,
                    Openid = customerInfo.OpenId,
                    UserID = customerInfo.Id
                };
                List<ByteDanceCustomer> listCustomerWechat = new List<ByteDanceCustomer>
                    {
                        wechatExtend
                    };
                CacheManager.ByteDance.ByteDanceRedis.SetDyteDanceInfo(listCustomerWechat);
            }
            return ApiResult.Success("");
        }


        ///// <summary>
        ///// 向客户抖音小程序发送消息
        ///// </summary>
        ///// <param name="content"></param>
        ///// <param name="model"></param>
        ///// <param name="ID"></param>
        ///// <param name="guestModel"></param>
        //public void SendMsg(string content, ByteDanceCustomer model, int ID, RB_Member_User userModel)
        //{

        //    //谁来接受微信消息通知
        //    string tempOpenId = model.Openid;
        //    //要使用的form_id
        //    string formId = "";

        //    var list = CacheManager.ByteDance.ByteDanceRedis.GetByteDanceList(model.UserID, formId);
        //    if (list != null && list.Any())
        //    {
        //        formId = list.OrderBy(x => x.FormCreateDate).FirstOrDefault().FormId;
        //        string WeChatSendTemplate = Common.Config.ByteDanceSendTemplate;
        //        var tempData = new
        //        {

        //            keyword1 = new
        //            {
        //                value = "旅客意见调查表",
        //            },
        //            keyword2 = new
        //            {
        //                value = userModel.AliasName,
        //            },
        //            keyword3 = new
        //            {
        //                value = content,
        //            },
        //        };
        //        //拼接字符串
        //        var msgData = new
        //        {
        //            access_token = "",
        //            touser = tempOpenId,//openId，推送给谁，给那个用户
        //            template_id = WeChatSendTemplate,//模板消息ID，在微信小程序后台的模板消息里有.。这个是*****成功通知。的id
        //                                             // topcolor = "#173177",
        //            page = "",//点击消息卡片之后打开的小程序页面地址，空则无跳转。        
        //            form_id = formId,//要从服务器数据库里取最近7天时间最长的一条没有使用的来，用完了要设置这个formId被用过了。
        //            data = tempData
        //        };

        //        string postData = JsonHelper.Serialize(msgData);
        //        string tempUrl = "https://developer.toutiao.com/api/apps/game/template/send";
        //        string resulr = WebRequestPostOrGet(tempUrl, postData);
        //        CacheManager.ByteDance.ByteDanceRedis.RemoveCacheKey(model.UserID.ToString(), formId, model);
        //    }
        //}

        ///// <summary>
        ///// 发送消息
        ///// </summary>
        ///// <param name="sUrl"></param>
        ///// <param name="sParam"></param>
        ///// <returns></returns>
        //public static string WebRequestPostOrGet(string sUrl, string sParam)
        //{
        //    byte[] bt = System.Text.Encoding.UTF8.GetBytes(sParam);
        //    Uri uriurl = new Uri(sUrl);
        //    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uriurl);//HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url + (url.IndexOf("?") > -1 ? "" : "?") + param);
        //    req.Method = "Post";
        //    req.Timeout = 120 * 1000;
        //    req.ContentType = "application/x-www-form-urlencoded;";
        //    req.ContentLength = bt.Length;
        //    using (Stream reqStream = req.GetRequestStream())//using 使用可以释放using段内的内存
        //    {
        //        reqStream.Write(bt, 0, bt.Length);
        //        reqStream.Flush();
        //    }
        //    try
        //    {
        //        using (WebResponse res = req.GetResponse())
        //        {
        //            Stream resStream = res.GetResponseStream();
        //            StreamReader resStreamReader = new StreamReader(resStream, System.Text.Encoding.UTF8);
        //            string resLine;
        //            System.Text.StringBuilder resStringBuilder = new System.Text.StringBuilder();
        //            while ((resLine = resStreamReader.ReadLine()) != null)
        //            {
        //                resStringBuilder.Append(resLine + System.Environment.NewLine);
        //            }
        //            resStream.Close();
        //            resStreamReader.Close();
        //            return resStringBuilder.ToString();
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        return ex.Message;//url错误时候回报错
        //    }
        //}

        /// <summary>
        /// 输入手机号码获取抖音小程序短信验证码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMobileCode()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            string mobile = parmsJob.GetStringValue("mobile");
            string info = ExecuteInCmd($"bytecli -l {mobile}");
            if (info.IndexOf("获取验证码成功") > -1)
            {
                return ApiResult.Success("获取验证码成功，请查看手机，输入验证码", info);
            }
            else
            {
                return ApiResult.Failed("获取验证失败");
            }
        }




        /// <summary>
        /// 输入手机号码获取抖音小程序短信验证码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetLogin()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            string mobile = parmsJob.GetStringValue("mobile");
            string code = parmsJob.GetStringValue("code");
            string info = ExecuteInCmd($"bytecli -l {mobile}@{code}");
            if (info.IndexOf("获取验证码成功") > -1)
            {
                return ApiResult.Success("获取验证码成功，请查看手机，输入验证码", info);
            }
            else
            {
                return ApiResult.Failed("获取验证失败");
            }
        }


        /// <summary>
        /// 执行内部命令（cmd.exe 中的命令）
        /// </summary>
        /// <param name="cmdline">命令行</param>
        /// <returns>执行结果</returns>
        public static string ExecuteInCmd(string cmdline)
        {
            //创建ProcessInfo对象
            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("cmd.exe");
            psi.UseShellExecute = false;
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardInput = true;
            psi.RedirectStandardError = true;
            psi.WorkingDirectory = "D:\\Tool\\bytedance\\bytedanceide\\resources\\app.asar.unpacked";
            psi.StandardOutputEncoding = Encoding.UTF8;
            // psi.StandardInputEncoding = Encoding.UTF8;
            // Start the process
            System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi);

            proc.StandardInput.AutoFlush = true;
            proc.StandardInput.WriteLine(cmdline + "&exit");

            //获取cmd窗口的输出信息  
            string output = proc.StandardOutput.ReadToEnd();

            proc.WaitForExit();
            proc.Close();

            return output;
        }

    }
}