using iWareCommon.Utils;
using iWareModel;
using iWareTestForm.Utility;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace iWareTestForm
{
    public partial class InterFaceTestForm : Form
    {
        AutoSizeFormClass asc = new AutoSizeFormClass();
        delegate string GetSelectInterFaceCallBack();
        delegate void Delegate_SetPostResult(int count, string content);
        delegate void Delegate_SetPost(int count, string param);
        string wipHost = BLLHelpler.GetConfigValue("wipHost");
        /// 
        /// 频率
        /// 
        private int callHZ = 1;
        /// 
        /// 请求次数
        /// 
        private int requestCount = 0;
        /// 
        /// 默认请求次数
        /// 
        private int default_requestCount = 200;
        private string curSelUrl = "";
        private long totalUseTime = 0;//全部请求的时间和
        public InterFaceTestForm()
        {
            InitializeComponent();
            this.WindowState = FormWindowState.Maximized;
            Init();
        }
        private void Init()
        {
            List itemList = GetItems();
            foreach (var item in itemList)
            {
                comBox_InterFaces.Items.Add(item);
            }
            comBox_InterFaces.SelectedIndex = 0;
            this.tb_CallHZ.Text = "1000";
            callHZ = 1;
            this.tb_RequestCount.Text = default_requestCount.ToString();
            requestCount = default_requestCount;
            this.tb_timestamp.Text = SimulatorCommonHelper.GetTimeStampWithlocals();
        }
        private void btn_Test_Click(object sender, EventArgs e)
        {
            InitData();
            Post(1);
        }
        private void Post(int count)
        {
            string param = this.tb_Params.Text.Trim();
            #region POST请求
            try
            {
                string url = GetSelectInterFace();
                string result = RealPost(wipHost, url, param, count);
                ShowResult(count, string.Format("第{0}次请求返回结果{1}", count.ToString(), result));
            }
            catch (Exception ex)
            {
                MessageBox.Show("出现异常:" + ex.Message);
                return;
            }
            #endregion
        }
        /// 
        /// 性能测试
        /// 
        /// 
        /// 
        private void btn_performanceTest_Click(object sender, EventArgs e)
        {
            InitData();
            string param = this.tb_Params.Text.Trim();
            //*/
            try
            {
                totalUseTime = 0;
                callHZ = Convert.ToInt32(this.tb_CallHZ.Text.Trim());
                requestCount = Convert.ToInt32(this.tb_RequestCount.Text.Trim());
            }
            catch (Exception ex)
            {
                MessageBox.Show("出现异常:" + ex.Message);
                return;
            }
            if (!this.cb_timestamp.Checked)
            {//时间戳不突变
                if (this.tb_timestamp.Text.Trim() == string.Empty)
                {
                    MessageBox.Show("时间戳不突变的情况下,时间戳不能为空!");
                    this.tb_timestamp.Focus();
                    return;
                }
            }
            ParameterizedThreadStart paramStart = new ParameterizedThreadStart(PerformanceTest);
            Thread thread = new Thread(paramStart);
            Object obj = param;
            thread.Start(obj);
        }
        private void PerformanceTest(object param)
        {
            string url = GetSelectInterFace();
            DateTime bgtime = DateTime.Now;
            var timestamp = "";
            string start_timestamp = "", end_timestamp = "";//开始和结束时间戳
            for (int i = 1; i < requestCount + 1; i++)
            {
                if (i != 1)
                    Thread.Sleep(callHZ);
                var str_param = param.ToString();
                if (this.ckb_ParamChange.Checked)
                {//参数突变
                    str_param = str_param.Replace("$MutationParam$", Guid.NewGuid().ToString().Substring(0, 5));
                }
                if (this.cb_timestamp.Checked)
                {//时间戳突变
                    timestamp = SimulatorCommonHelper.GetTimeStampWithlocals();
                }
                else
                {//时间戳不突变
                    timestamp = this.tb_timestamp.Text.Trim();
                }
                str_param = str_param.Replace("$timestamp$", timestamp);
                if (i == 1)
                {
                    start_timestamp = timestamp;
                }
                else if (i == requestCount)
                {
                    end_timestamp = timestamp;
                }
                MyMethod(bgtime, start_timestamp, end_timestamp, i, str_param, url);
                //SetPostResult22(i, "异步方法" + i.ToString() + "调用完成");
            }
        }
        /// 
        /// 获取接口下拉
        /// 
        /// 
        private string GetSelectInterFace()
        {
            //多线程调用时要查检控件的InvokeRequired,若未在其他线程中访问,可直接赋值。若在调用,要用Invoke来调用代理完成。
            if (this.comBox_InterFaces.InvokeRequired)
            {
                GetSelectInterFaceCallBack callBack = new GetSelectInterFaceCallBack(GetSelectInterFace);
                return this.Invoke(callBack).ToString();
            }
            else
            {
                return (this.comBox_InterFaces.SelectedItem as ListItem).Value;
            }
        }
        /// 
        /// 显示请求结果
        /// 
        /// 
        /// 
        private void ShowResult(int count, string content)
        {
            if (this.tb_PostResult.InvokeRequired)
            {
                Delegate_SetPostResult delegate_SetPostResult = new Delegate_SetPostResult(ShowResult);
                this.Invoke(delegate_SetPostResult, new object[] { count, content });
            }
            else
            {
                content = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "  " + content + " \r\n";
                this.tb_ResponseResult.Text = this.tb_ResponseResult.Text + content;
            }
        }
        /// 
        /// 显示请求信息
        /// 
        /// 
        /// 
        private void ShowPostInfo(int count, string param)
        {
            if (this.tb_PostResult.InvokeRequired)
            {
                Delegate_SetPost delegate_SetPostResult = new Delegate_SetPost(ShowPostInfo);
                this.Invoke(delegate_SetPostResult, new object[] { count, param });
            }
            else
            {
                string content = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "  第" + count.ToString() + "次请求... \r\n";
                content += "参数:" + param + "\r\n";
                this.tb_PostResult.Text = this.tb_PostResult.Text + content;
            }
        }
        #region 异步方法
        private async Task MyMethod(DateTime bgtime, string start_timestamp, string end_timestamp, int i, string param, string url)
        {
            string r = await Task.Run(() =>
            {
                Stopwatch stopWatch = new Stopwatch();
                stopWatch.Start();
                //var startTime = WIPCommon.ForamtCurDateTimeWithF();
                string result = RealPost(wipHost, url, param, i);
                //var endTime = WIPCommon.ForamtCurDateTimeWithF();
                stopWatch.Stop();
                ShowResult(i, string.Format("第{0}次请求返回结果{1}", i.ToString(), result));
                ShowResult(i, string.Format("第{0}次请求结束,用时:" + stopWatch.ElapsedMilliseconds.ToString() + "(毫秒)", i.ToString()));
                totalUseTime += stopWatch.ElapsedMilliseconds;
                return result;
                //return (i * 2).ToString();
            });
            //ShowResult(i, string.Format("异步方法{0}执行完毕,结果{1}", i.ToString(), r));
            if (i == requestCount)
            {
                ShowResult(i,
                    "请求结束,总用时:" + (DateTime.Now - bgtime).TotalMilliseconds.ToString()
                    + "(毫秒),平均用时:" + (totalUseTime / requestCount).ToString("0") + "(毫秒)"
                    + ",【开始时间戳:" + start_timestamp + ",结束时间戳:" + end_timestamp + "】"
                    + ",【查询开始时间戳:" + (Convert.ToInt64(start_timestamp) - 1).ToString() + "000,查询结束时间戳:" + (Convert.ToInt64(end_timestamp) + 1).ToString() + "000】");
            }
            return r;
        }
        #endregion
        private string RealPost(string host, string url, string param, int count)
        {
            return "";
            /*
            string result = "";
            try
            {
                ShowPostInfo(count, param);
                //result = new HTTPService(host).postContentForString(url, param, new Guid());
                result = new HTTPLongConnectionService2().postContentForString(url, param);
            }
            catch (Exception ex)
            {
                result = string.Format("请求出现异常,ex:{0},参数->host:{1},url:{2},param:{3},count:{4}",
                     JsonConvert.SerializeObject(ex), host, url, param, count.ToString());
            }
            return result;
            //*/
        }
        private void btn_Stop_Click(object sender, EventArgs e)
        {
            requestCount = 0;
            this.btn_performanceTest.Enabled = true;
            this.btn_Test.Enabled = true;
        }
        #region 公共方法
        /// 
        /// 获取完整地址
        /// 
        /// 
        /// 
        private string GetURL(string url)
        {
            return wipHost + url;
        }
        private List GetItems()
        {
            List list = new List();
            InterfaceSection services = InterfaceSection.GetConfig();
            foreach (TheKeyValue item in services.KeyValues)
            {
                list.Add(new ListItem()
                {
                    Text = item.Name,
                    Value = item.Url
                });
            }
            return list;
        }
        private void InitData()
        {
            this.tb_PostResult.Text = "";
            this.tb_ResponseResult.Text = "";
            //this.btn_performanceTest.Enabled = false;
            //this.btn_Test.Enabled = false;
            if (this.comBox_InterFaces.SelectedIndex == -1)
            {
                MessageBox.Show("请选择接口!");
                return;
            }
            curSelUrl = GetSelectInterFace();
            this.lbl_URL.Text = GetURL(curSelUrl);
        }
        #endregion
        private void comBox_InterFaces_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                curSelUrl = GetSelectInterFace();
                this.lbl_URL.Text = GetURL(curSelUrl);
                var selItem = (ListItem)this.comBox_InterFaces.SelectedItem;
                if (selItem != null)
                {
                    string json = JsonFileHelper.ReadJson(@"Templete\" + selItem.Text + ".json");
                    //json = json.Replace("$timestamp$", CommonHelper.GetTimeStampWithlocals());
                    json = json.Replace("$testValue$", "test");
                    this.tb_Params.Text = json;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("出现错误:" + ex.Message);
            }
        }
        private void InterFaceTestForm_Load(object sender, EventArgs e)
        {
            asc.controllInitializeSize(this);
        }
        private void tb_PostResult_TextChanged(object sender, EventArgs e)
        {
            tb_PostResult.SelectionStart = tb_PostResult.Text.Length;
            tb_PostResult.ScrollToCaret();
        }
        private void tb_ResponseResult_TextChanged(object sender, EventArgs e)
        {
            tb_ResponseResult.SelectionStart = tb_ResponseResult.Text.Length;
            tb_ResponseResult.ScrollToCaret();
        }
        private void InterFaceTestForm_SizeChanged(object sender, EventArgs e)
        {
            asc.controlAutoSize(this);
        }
        private void btn_Close_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void btn_NewTimeStamp_Click(object sender, EventArgs e)
        {
            this.tb_timestamp.Text = SimulatorCommonHelper.GetTimeStampWithlocals();
        }
    }
}