using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authorization;
using System.Web;
using MySystem.MainModels;
using LitJson;
using Library;

namespace MySystem.Areas.Api.Controllers.v1
{
    [Area("Api")]
    [Route("Api/v1/[controller]/[action]")]
    public class UserAddressController : BaseController
    {
        public UserAddressController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting) : base(accessor, logger, setting)
        {
        }




        #region 创客-商城-修改收货地址
        [Authorize]
        public JsonResult Update(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = UpdateDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson UpdateDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            string Address = data["Address"].ToString(); //详细地址
            string RealName = data["RealName"].ToString(); //收货人姓名
            string Mobile = data["Mobile"].ToString(); //手机号码
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //所属创客Id
            string Areas = data["Areas"].ToString(); //所在地区
            ulong IsDefault = ulong.Parse(data["IsDefault"].ToString()); //是否默认
            if (string.IsNullOrEmpty(data["Areas"].ToString()))
            {
                return new AppResultJson() { Status = "-1", Info = "请填写所在地区" };
            }
            if (data["Areas"].ToString().Length > 30)
            {
                return new AppResultJson() { Status = "-1", Info = "所在地区最多30个字符" };
            }
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            UserAddress query = maindb.UserAddress.FirstOrDefault(m => m.Id == Id);
            if(query != null)
            {
                query.UpdateDate = DateTime.Now; //修改时间
                query.Address = Address; //详细地址
                query.RealName = RealName; //收货人姓名
                query.Mobile = Mobile; //手机号码
                query.UserId = UserId; //所属创客Id
                query.Areas = Areas; //所在地区
                query.IsDefault = IsDefault; //是否默认
                maindb.SaveChanges();
                if(IsDefault == 1)
                {
                    SetDefaultDo("{\"Id\":\"" + Id + "\",\"UserId\":\"" + UserId + "\"}");
                }
            }
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion


        #region 创客-商城-删除收货地址
        [Authorize]
        public JsonResult Delete(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = DeleteDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson DeleteDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //所属创客Id
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            UserAddress query = maindb.UserAddress.FirstOrDefault(m => m.Id == Id && m.UserId == UserId);
            if(query != null)
            {
                maindb.UserAddress.Remove(query);
                maindb.SaveChanges();
            }
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion



        #region 创客-商城-收货地址列表
        [Authorize]
        public JsonResult List(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            List<Dictionary<string, object>> dataList = ListDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList });
        }
        public List<Dictionary<string, object>> ListDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //所属创客Id
            int PageSize = int.Parse(function.CheckInt(data["PageSize"].ToString()));
            int PageNum = int.Parse(function.CheckInt(data["PageNum"].ToString()));
            List<Dictionary<string, object>> dataList = new List<Dictionary<string, object>>();
            IQueryable<UserAddress> query = maindb.UserAddress.Where(m => m.Status > -1 && m.UserId == UserId);
            query = query.OrderByDescending(m => m.Id);
            if (PageNum == 1)
            {
                query = query.Take(PageSize);
            }
            else
            {
                int skipNum = PageSize * (PageNum - 1);
                query = query.Skip(skipNum).Take(PageSize);
            }
            foreach (var subdata in query.ToList())
            {
                Dictionary<string, object> curData = new Dictionary<string, object>();
                curData.Add("Address", subdata.Address); //详细地址
                curData.Add("RealName", subdata.RealName); //收货人姓名
                curData.Add("Mobile", subdata.Mobile); //手机号码
                curData.Add("Areas", function.CheckNull(subdata.Areas).Replace(",", "")); //所在地区
                curData.Add("IsDefault", subdata.IsDefault); //是否默认
                curData.Add("Id", subdata.Id); //Id
                dataList.Add(curData);
            }
            return dataList;
        }
        #endregion



        #region 创客-商城-添加收货地址
        [Authorize]
        public JsonResult Add(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = AddDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson AddDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string Address = data["Address"].ToString(); //详细地址
            string RealName = data["RealName"].ToString(); //收货人姓名
            string Mobile = data["Mobile"].ToString(); //手机号码
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //所属创客Id
            string Areas = data["Areas"].ToString(); //所在地区
            ulong IsDefault = ulong.Parse(data["IsDefault"].ToString()); //是否默认
            if (string.IsNullOrEmpty(data["Areas"].ToString()))
            {
                return new AppResultJson() { Status = "-1", Info = "请填写所在地区" };
            }
            if (data["Areas"].ToString().Length > 30)
            {
                return new AppResultJson() { Status = "-1", Info = "所在地区最多30个字符" };
            }
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            UserAddress query = maindb.UserAddress.Add(new UserAddress()
            {
                CreateDate = DateTime.Now, //创建时间
                UpdateDate = DateTime.Now, //修改时间
                Address = Address, //详细地址
                RealName = RealName, //收货人姓名
                Mobile = Mobile, //手机号码
                UserId = UserId, //所属创客Id
                Areas = Areas, //所在地区
                IsDefault = IsDefault, //是否默认
            }).Entity;
            maindb.SaveChanges();
            if(IsDefault == 1)
            {
                SetDefaultDo("{\"Id\":\"" + query.Id + "\",\"UserId\":\"" + UserId + "\"}");
            }
            Obj.Add("Id", query.Id); //Id
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion



        #region 创客-商城-获取收货地址
        [Authorize]
        public JsonResult Detail(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = DetailDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> DetailDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //所属创客Id
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            UserAddress query = UserAddressDbconn.Instance.Get(Id) ?? new UserAddress();
            Obj.Add("Address", query.Address); //详细地址
            Obj.Add("RealName", query.RealName); //收货人姓名
            Obj.Add("Mobile", query.Mobile); //手机号码
            Obj.Add("Areas", query.Areas); //所在地区
            Obj.Add("IsDefault", query.IsDefault); //是否默认
            return Obj;
        }
        #endregion



        #region 创客-商城-设置默认收货地址
        [Authorize]
        public JsonResult SetDefault(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = SetDefaultDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson SetDefaultDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //所属创客Id
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            List<int> query = UserAddressDbconn.Instance.GetList(UserId);
            foreach (int AddressId in query)
            {
                UserAddress subdata = maindb.UserAddress.FirstOrDefault(m => m.Id == AddressId);
                if (subdata != null)
                {
                    if (Id == AddressId)
                    {
                        subdata.IsDefault = 1;
                    }
                    else
                    {
                        subdata.IsDefault = 0;
                    }
                }
            }
            maindb.SaveChanges();
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion



        #region 检查签名是否合法，合法返回1，不合法返回提示信息

        /// <summary>
        /// 检查签名是否合法，合法返回1，不合法返回提示信息
        /// </summary>
        /// <param name="value">请求的参数(json字符串)</param>
        /// <param name="signField">要签名的字段</param>
        /// <returns></returns>
        private string CheckSign(string value, string[] signField)
        {
            JsonData json = JsonMapper.ToObject(value);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            for (int i = 0; i < signField.Length; i++)
            {
                dic.Add(signField[i], json[signField[i]].ToString());
            }
            string sign = json["sign"].ToString(); //客户端签名字符串
            return new Sign().sign(dic, sign);
        }

        #endregion

    }
}
