using Common.system;

using Newtonsoft.Json.Linq;

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

using XHWK.Model;

namespace XHWK.WKTool.DAL
{
    public class XHApi
    {
        /// <summary>
        /// 激活信息--添加
        /// </summary>
        /// <param name="request">
        /// </param>
        /// <returns>
        /// </returns>
        public int ActivationAdd(string mac, string device, string projectcode)
        {
            try
            {
                string url = App.certapiUrl + "/activation/add"; //地址
                Dictionary<string, object> dic = new Dictionary<string, object>
                {
                    { "mac", mac },
                    { "device", device },
                    { "projectcode", projectcode }
                };
                string body = JsonHelper.ToJson(dic);

                string xmlDoc = HttpHelper.HttpPost(body, url);

                if (string.IsNullOrEmpty(xmlDoc))
                {
                    App.ServerMsg = "网络异常！";
                    return 1;
                }
                else
                {
                    JObject obj = JObject.Parse(xmlDoc);
                    if (obj != null)
                    {
                        if (obj["code"].ToString().Equals("0"))
                        {
                            App.Signature = obj["obj"].ToString();
                            if (!Directory.Exists(App.DataPath))
                            {
                                Directory.CreateDirectory(App.DataPath);
                            }
                            string ApplicationData = App.DataPath + "signature.txt";
                            System.IO.File.WriteAllText
                            (
                                ApplicationData,
                                App.Signature,
                                Encoding.Default
                            ); //存放签名
                            return 0;
                        }
                        else
                        {
                            App.ServerMsg = obj["msg"].ToString();
                            return Convert.ToInt32(obj["code"].ToString());
                        }
                    }
                    else
                    {
                        return 1;
                    }
                }
            }
            catch (Exception ex)
            {
                App.ServerMsg = "网络异常！";
                LogHelper.WriteErrLog("【调用接口（RegisterController）】错误日志：" + ex.Message, ex);
                return 1;
            }
        }

        /// <summary>
        /// 激活信息--添加激活历史
        /// </summary>
        /// <param name="request">
        /// </param>
        /// <returns>
        /// </returns>
        public int ActivationAddHistory()
        {
            try
            {
                string url = App.certapiUrl + "/activation/add_history";
                Dictionary<string, object> dic = new Dictionary<string, object> { { "sign", App.Signature } };
                string body = JsonHelper.ToJson(dic);
                string xmlDoc = HttpHelper.HttpPost(body, url);

                if (string.IsNullOrEmpty(xmlDoc))
                {
                    return 1;
                    //returnObj.message = "账号密码不正确";
                }
                else
                {
                    JObject obj = JObject.Parse(xmlDoc);
                    if (obj != null)
                    {
                        App.ServerMsg = obj["msg"].ToString();
                        return Convert.ToInt32(obj["code"].ToString());
                    }
                    else
                    {
                        return 1;
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLog("【调用接口（RegisterController）】错误日志：" + ex.Message, ex);
                return 1;
            }
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request">
        /// </param>
        /// <returns>
        /// </returns>
        public int Login(string loginname, string loginpwd)
        {
            Console.WriteLine(FileToolsCommon.GetConfigValue("APIRequestAddress"));
            string url = App.apiUrl + "/suser/user/login"; //地址

            //1.193.37.200
            string Address = "";//河南 郑州
            HttpHelper.GetAddressIP(out string AddressIP, out AddressIP);
            Dictionary<string, object> dic = new Dictionary<string, object>
            {
                { "loginname", loginname},
                { "loginpwd", loginpwd},
                {"logip", AddressIP},
                {"logaddress", Address},
                {"ultype", "microlecture_pc_t"},
                {"versionnum", FileToolsCommon.GetConfigValue("VersionName")}
            };
            string body = JsonHelper.ToJson(dic);
            ResultVo<Model_UserInfo> result = HttpHelper.PostAndRespSignle<ResultVo<Model_UserInfo>>(url, postData: body);
            if (result != null)
            {
                App.UserInfo = new Model_UserInfo();
                App.ServerMsg = result.msg;
                if (result.obj != null)
                {
                    App.UserInfo = result.obj;
                }
                return result.code;
            }
            else
            {
                App.ServerMsg = "网络异常！";
                App.UserInfo = new Model_UserInfo();
                return 1;
            }
        }

        /// <summary>
        /// 下载头像
        /// </summary>
        /// <param name="headPortrait">
        /// </param>
        /// <param name="SavePath">
        /// </param>
        /// <returns>
        /// </returns>
        public bool DownloadAvatar(string headPortrait, string SavePath)
        {
            string url = App.showImageUrl + headPortrait;
            bool result = HttpHelper.GetDataGetHtml(url, SavePath, "");
            return result;
        }

        /// <summary>
        /// 教师教材列表
        /// </summary>
        /// <param name="request">
        /// </param>
        /// <returns>
        /// </returns>
        public int TsubjectbookList()
        {
            App.TsubjectbookList = new List<Model_TsubjectbookList>();
            try
            {
                string url = App.apiUrl + "/sstudy/tsubjectbook/list"; //地址
                Dictionary<string, int> dic = new Dictionary<string, int> { { "teacherid", App.UserInfo.Userid } };
                string body = JsonHelper.ToJson(dic);
                ResultVo<List<Model_TsubjectbookList>> result = HttpHelper.PostAndRespSignle<ResultVo<List<Model_TsubjectbookList>>>(url, postData: body);
                if (result != null)
                {
                    App.ServerMsg = result.msg;
                    App.TsubjectbookList = result.obj;
                    return result.code;
                }
                else
                {
                    App.ServerMsg = "网络异常！";
                    return 1;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLog("【调用接口（RegisterController）】错误日志：" + ex.Message, ex);
                return 1;
            }
        }

        /// <summary>
        /// 章节--列表
        /// </summary>
        /// <param name="request">
        /// </param>
        /// <returns>
        /// </returns>
        public int DirectorList(string lsbid, int belong, int createid)
        {
            App.DirectorList = new List<Model_DirectorList>();
            try
            {
                string url = App.apiUrl + "/sstudy/director/list"; //地址
                Dictionary<string, string> dic = new Dictionary<string, string>
                {
                    { "lsbid", lsbid },
                    { "belong", belong.ToString() },
                    { "createid", createid.ToString() }
                };
                string body = JsonHelper.ToJson(dic);
                ResultVo<List<Model_DirectorList>> result = HttpHelper.PostAndRespSignle<ResultVo<List<Model_DirectorList>>>(url, postData: body);
                if (result != null)
                {
                    App.ServerMsg = result.msg;
                    App.DirectorList = result.obj;
                    return result.code;
                }
                else
                {
                    App.ServerMsg = "网络异常！";
                    return 1;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLog("【调用接口（RegisterController）】错误日志：" + ex.Message, ex);
                return 1;
            }
        }

        /// <summary>
        /// 资源--添加
        /// </summary>
        /// <param name="request">
        /// </param>
        /// <returns>
        /// </returns>
        public int ResourceAdd(Model_ResourceAdd model)
        {
            App.DirectorList = new List<Model_DirectorList>();
            try
            {
                string url = App.apiUrl + "/sstudy/resource/add"; //地址
                Dictionary<string, object> dic = new Dictionary<string, object>
                {
                    //            converted: 0
                    //createid: 80
                    //directorid: 1009
                    //duration: 39
                    //imgUrl: ""
                    //level: 2
                    //lsbid: 40
                    //mp4code: "h264"
                    //resourcebelong: 3
                    //resourceclass: 2
                    //resourcecover: "12/resource/20200917/4f297df0-f8c0-11ea-adf5-81f24b97d4ff/weather_pic.jpg"
                    //resourcename: "weather_pic"
                    //resourcesize: 6105268
                    //resourcetype: 0
                    //resourceurl: "12/resource/20200917/4f297df0-f8c0-11ea-adf5-81f24b97d4ff/weather_pic.mp4"
                    //schoolid: 12
                    //suffix: "mp4"
                    //uid: 80
                    { "converted", model.converted },
                    { "createid", model.createid }
                };
                if (model.directorid != "999999")//章节上传可以不选
                {
                    dic.Add("directorid", model.directorid);
                }
                dic.Add("duration", model.duration);
                dic.Add("subjectid", model.subjectid);
                dic.Add("imgUrl", model.imgUrl);
                dic.Add("level", model.level);
                dic.Add("lsbid", model.lsbid);
                dic.Add("mp4code", model.mp4code);
                dic.Add("resourcebelong", model.resourcebelong);
                dic.Add("resourceclass", model.resourceclass);
                dic.Add("resourcecover", model.resourcecover);
                dic.Add("resourcename", model.resourcename);
                dic.Add("resourcesize", model.resourcesize);
                dic.Add("resourcetype", model.resourcetype);
                dic.Add("resourceurl", model.resourceurl);
                dic.Add("schoolid", model.schoolid);
                dic.Add("suffix", model.suffix);
                //dic.Add("uid", model.uid);

                string body = JsonHelper.ToJson(dic);
                string xmlDoc = HttpHelper.HttpPost(body, url);
                JObject obj = JObject.Parse(xmlDoc);
                if (obj != null)
                {
                    App.ServerMsg = obj["msg"].ToString();
                    return Convert.ToInt32(obj["code"].ToString());
                }
                else
                {
                    App.ServerMsg = "网络异常！";
                    return 1;
                }
            }
            catch (Exception ex)
            {
                App.ServerMsg = "网络异常！";
                LogHelper.WriteErrLog("【调用接口（RegisterController）】错误日志：" + ex.Message, ex);
                return 1;
            }
        }

        /// <summary>
        /// 请求服务地址
        /// </summary>
        /// <param name="Schoolcode">
        /// </param>
        /// <returns>
        /// </returns>
        public bool GetServiceAddress(string Schoolcode, out string Message)
        {
            string url = App.certapiUrl + "/school/find_code"; //地址
            Dictionary<string, object> dic = new Dictionary<string, object>
            {
                { "schoolcode", Schoolcode}
            };
            string body = JsonHelper.ToJson(dic);
            ResultVo<Model_ServiceAddress> result = HttpHelper.PostAndRespSignle<ResultVo<Model_ServiceAddress>>(url, postData: body);
            if (result != null)
            {
                if (result.code == 0)
                {
                    if (result.obj != null)
                    {
                        Message = result.msg;
                        App.ServiceAddress = result.obj;
                        App.SaveServiceAddressData();
                        return true;
                    }
                    else
                    {
                        Message = "服务地址错误，请输入正确的地址！";
                        return false;
                    }
                }
                else
                {
                    Message = result.msg;
                    return false;
                }
            }
            else
            {
                Message = "无法与服务器建立连接，请检查网络状态。";
                return false;
            }
        }
    }
}
