using HandyControl.Controls;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WCS.Model;
using WCS.Model.ApiModel;
using WCS.Model.ApiModel.StoreInfo;
using WCS.Model.ApiModel.User;
using 智能仓储WCS管理系统.Api;

namespace 智能仓储WCS管理系统
{
    /// <summary>
    /// CalibrationWindow.xaml 的交互逻辑
    /// </summary>
    public partial class CalibrationWindow : System.Windows.Window
    {
        public int BoardId { get; set; }

        public int ModuleId { get; set; }
        public string ModuleCode { get; set; }
        public CalibrationWindow(int boardId, int moduleId, string moduleCode)
        {
            InitializeComponent();
            BoardId = boardId;
            ModuleId = moduleId;
            tagIdTxt.Text = $"板ID：{boardId}";
            ModuleCode = moduleCode;
            moduleCodeTxt.Text = $"库位：{moduleCode}";
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            #region 输入框验证
            //偏差值输入框的验证
            var offSet = 0;
            try
            {
                offSet = Convert.ToInt32(offSetTxt.Text.Trim());
                if (offSet <= 0)
                {
                    System.Windows.MessageBox.Show($"偏差值请输入大于0的自然数！", "提示");
                    offSetTxt.Focus();
                    return;
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"偏差值请输入大于0的自然数！", "提示");
                offSetTxt.Focus();
                return;
            }

            var loginName = ComboBoxId.Text.Trim();
            var pass = PasswordBoxPass.Password.ToString();

            if (string.IsNullOrEmpty(loginName))
            {
                System.Windows.MessageBox.Show("请输入账号！", "提示");
                ComboBoxId.Focus();
                return;
            }
            if (string.IsNullOrEmpty(pass))
            {
                System.Windows.MessageBox.Show("请输入密码！", "提示");
                PasswordBoxPass.Focus();
                return;
            }
            #endregion
            try
            {
                #region 调用接口：验证账号密码
                var body = new UserLoginRequest()
                {
                    UserName = loginName,
                    DeviceType = LocalFile.Config.DeviceType + "标定",
                    GroupNames = LocalFile.Config.GroupName,
                    PassWord = pass,
                    IsNoLogin = false,
                };
                var Result = ApiHelp.GetDataFromHttp<ResponseBase<UserModel>>(LocalFile.Config.ApiIpHost + "user/userLogin", body, "POST");
                if (Result != null && Result.Code != 200)
                {
                    HandyControl.Controls.MessageBox.Warning(Result.Message, "提示");
                    return;
                }
                else if (Result == null)
                {
                    HandyControl.Controls.MessageBox.Warning("登录失败：接口调用失败！", "提示");
                    return;
                }
                else
                {
                    if (!Result.Data.IsAdmin && !Result.Data.IsGCYF)
                    {
                        HandyControl.Controls.MessageBox.Warning("登录成功！权限不足", "提示");
                        return;
                    }
                    else
                    {
                        //此分支可以继续
                    }
                }
                #endregion

                #region 调用接口：发送标定和设置偏移量指令
                try
                {
                    var body1 = new CalibrationSetOffsetRequest()
                    {
                        MouduleIds = new List<int>() { ModuleId },
                        OffSet = offSet,
                        UserName = LocalStatic.CurrentUser,
                        DeviceType = LocalFile.Config.DeviceType,
                    };
                    var Result1 = ApiHelp.GetDataFromHttp<ResponseCommon>(LocalFile.Config.ApiIpHost + "storeInfo/calibrationSetOffset", body1, "POST");
                    if (Result1 != null && Result1.Code == 200)
                    {
                        Growl.Success("发送标定指令成功！");
                        this.Close();
                    }
                    else if (Result != null)
                    {
                        Growl.Error(Result1.Message);
                    }
                }
                catch (Exception ex)
                {
                    Growl.Error("操作失败：" + ex.Message);
                }
                finally
                {

                }
                #endregion
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message, "错误");
                return;
            }
        }

        private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                Button_Click(null, null);
            }
            else if (e.Key == Key.Escape)
            {
                this.Close();
            }
        }


        public string GetDataFromHttp(string data, string url, string httpMethod)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = httpMethod;
                request.ContentType = "application/json";
                if (!string.IsNullOrEmpty(data))
                {
                    string strContent = data; //参数data
                    using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
                    {
                        dataStream.Write(strContent);
                        dataStream.Close();
                    }
                }

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string encoding = response.ContentEncoding;
                if (encoding == null || encoding.Length < 1)
                {
                    encoding = "UTF-8"; //默认编码  
                }
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
                string retString = reader.ReadToEnd();
                return retString;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public class RootLogin
        {
            public int code { get; set; }

            public string msg { get; set; }

            public object data { get; set; }
        }
    }
}
