
using New_College.IServices;
using New_College.Model.Models;
using New_College.Services.BASE;
using New_College.IRepository.Base;
using New_College.Model.ViewModels;
using System.Threading.Tasks;
using New_College.Common;
using static New_College.Common.AliyunSmsSender;
using System;
using System.Collections.Generic;
using System.Linq;
using New_College.Common.Helper;
using New_College.Model;
using LinqKit;
using New_College.Model.Request;

namespace New_College.Services
{
    public class V_CustomerInfoServices : BaseServices<V_CustomerInfo>, IV_CustomerInfoServices
    {
        private readonly IBaseRepository<V_CustomerInfo> _dal;
        public V_CustomerInfoServices(IBaseRepository<V_CustomerInfo> dal)
        {
            this._dal = dal;
            base.BaseDal = dal;
        }



        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<CustomerInfoResult> UpdateCustomerInfo(UpdateCustomerQuery query)
        {
            var info = await _dal.QueryById(query.Id);
            if (info == null)
                return new CustomerInfoResult() { Status = 3 };
            info.NickName = query.NickName;
            //info.Phone = query.Phone;
            info.Gender = query.Gender;
            info.AvatarUrl = query.AvatarUrl;
            if (!string.IsNullOrWhiteSpace(query.UserPwd))
            {
                var salt = RadomHelper.RandCode(6);
                info.UserPwd = MD5Helper.MD5Encrypt16(query.UserPwd + salt);
            }
            var result = await _dal.Update(info);
            return new CustomerInfoResult()
            {
                Status = 1,
                AvatarUrl = info.AvatarUrl,
                Gender = info.Gender,
                Id = info.Id,
                OpenId = info.OpenId,
                NickName = info.NickName,
                AreaId = info.AreaId,
                AreaName = info.AreaName,
                Datainit = info.Datainit,
                Expectedscore = info.Expectedscore,
                IsVIP = info.IsVIP,
                Subject = info.Subject,
                Subjectgroup = info.Subjectgroup,
                subjectgroupName = info.subjectgroupName,
                VipCode = info.VipCode,
                IsUpdateScore = info.IsUpdateScore,
                Year = info.Year
            };
        }




        /// <summary>
        /// 更改分数和学科
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<CustomerInfoResult> UpdateScore(UpdateScoreQuery query)
        {
            var info = await _dal.QueryById(query.StudentId);
            if (info == null)
                return new CustomerInfoResult() { Status = 3 };
            info.IsUpdateScore += 1;
            info.Expectedscore = query.Score;
            info.Subject = query.Subject;
            info.Subjectgroup = query.Subjectgroup;
            var result = await _dal.Update(info);
            if (result)
            {
                return new CustomerInfoResult()
                {
                    Status = 1,
                    AvatarUrl = info.AvatarUrl,
                    Gender = info.Gender,
                    Id = info.Id,
                    OpenId = info.OpenId,
                    NickName = info.NickName,
                    AreaId = info.AreaId,
                    AreaName = info.AreaName,
                    Datainit = info.Datainit,
                    Expectedscore = info.Expectedscore,
                    IsVIP = info.IsVIP,
                    Subject = info.Subject,
                    Subjectgroup = info.Subjectgroup,
                    subjectgroupName = info.subjectgroupName,
                    VipCode = info.VipCode,
                    IsUpdateScore = info.IsUpdateScore,
                    Year = info.Year
                };
            }
            else
            {
                return new CustomerInfoResult() { Status = 3 };
            }
        }

        /// <summary>
        /// 完善用户信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<CustomerInfoResult> UpdateCustomer(CustomerUpdateQuery query)
        {
            var info = await _dal.QueryById(query.StudentId);
            if (info == null)
                return new CustomerInfoResult() { Status = 3 };
            info.Datainit = true;
            if (query.AreaId > 0)
            {
                info.AreaId = query.AreaId;
            }
            if (!string.IsNullOrEmpty(query.AreaName))
            {
                info.AreaName = query.AreaName;
            }
            if (query.Subject >= 0)
            {
                info.Subject = query.Subject;
            }
            if (!string.IsNullOrEmpty(query.Subjectgroup))
            {
                info.Subjectgroup = query.Subjectgroup;
            }
            if (!string.IsNullOrEmpty(query.subjectgroupName))
            {
                info.subjectgroupName = query.subjectgroupName;
            }
            if (query.Expectedscore > 0)
            {
                info.Expectedscore = query.Expectedscore;
            }
            if (query.Year > 0)
            {
                info.Year = query.Year;
            }
            if (!string.IsNullOrEmpty(query.SchoolName))
            {
                info.SchoolName = query.SchoolName;
            }
            if (!string.IsNullOrEmpty(query.ClassName))
            {
                info.ClassName = query.ClassName;
            }
            var result = await _dal.Update(info);
            if (result)
            {
                return new CustomerInfoResult()
                {
                    Status = 1,
                    AvatarUrl = info.AvatarUrl,
                    Gender = info.Gender,
                    Id = info.Id,
                    OpenId = info.OpenId,
                    NickName = info.NickName,
                    AreaId = info.AreaId,
                    AreaName = info.AreaName,
                    Datainit = info.Datainit,
                    Expectedscore = info.Expectedscore,
                    IsVIP = info.IsVIP,
                    Subject = info.Subject,
                    Subjectgroup = info.Subjectgroup,
                    subjectgroupName = info.subjectgroupName,
                    VipCode = info.VipCode,
                    IsUpdateScore = info.IsUpdateScore,
                    CustomerType = info.CustomerType,
                    Phone = info.Phone,
                    SchoolName = info.SchoolName,
                    ClassName = info.ClassName,
                    Year = info.Year
                };
            }
            else
            {
                return new CustomerInfoResult() { Status = 3 };
            }
        }

        /// <summary>
        /// 根绝Id获取用户信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<MessageModel<CustomerInfoResult>> GetCustomerInfoById(IdQuery query)
        {
            var info = await _dal.QueryById(query.Id);
            if (info == null)
                return new MessageModel<CustomerInfoResult>() { success = false, msg = "获取失败，用户信息为空" };
            return new MessageModel<CustomerInfoResult>()
            {
                success = true,
                msg = "获取成功",
                response = new CustomerInfoResult()
                {
                    AvatarUrl = info.AvatarUrl,
                    Gender = info.Gender,
                    Id = info.Id,
                    OpenId = info.OpenId,
                    NickName = info.NickName,
                    AreaId = info.AreaId,
                    AreaName = info.AreaName,
                    Datainit = info.Datainit,
                    Expectedscore = info.Expectedscore,
                    IsVIP = info.IsVIP,
                    Subject = info.Subject,
                    Subjectgroup = info.Subjectgroup,
                    subjectgroupName = info.subjectgroupName,
                    VipCode = info.VipCode,
                    IsUpdateScore = info.IsUpdateScore,
                    Year = info.Year,
                    SchoolName = info.SchoolName,
                    ClassName = info.ClassName
                }
            };
        }

        /// <summary>
        /// 查询CustomerInfo表信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<MessageModel<PageModel<CustomerInfoListResult>>> GetCustomerInfoListByPage(CustomerSeachQuery query)
        {
            var wheres = PredicateBuilder.New<V_CustomerInfo>();
            wheres = wheres.And(x => x.IsDelete == false);
            if (!string.IsNullOrWhiteSpace(query.Phone))
                wheres = wheres.And(x => x.Phone.Contains(query.Phone));
            if (query.Subject != 2)
                wheres = wheres.And(x => (int)x.Subject == query.Subject);
            if (!string.IsNullOrWhiteSpace(query.VipCode))
                wheres = wheres.And(x => x.VipCode.Contains(query.VipCode));
            var info = await _dal.QueryPage(wheres, query.PageIndex, query.PageSize);
            if (info.data.Count <= 0)
                return new MessageModel<PageModel<CustomerInfoListResult>>()
                {
                    success = false,
                    msg = "获取失败"
                };
            //var regioninfo = await sysRegionRepository.Query(x => x.ParentCode == "100000");
            PageModel<CustomerInfoListResult> pageModel = new PageModel<CustomerInfoListResult>() { };
            List<CustomerInfoListResult> list = new List<CustomerInfoListResult>() { };
            foreach (var item in info.data)
            {
                list.Add(new CustomerInfoListResult()
                {
                    Id = item.Id,
                    Phone = item.Phone,
                    Subject = item.Subject,
                    Subjectgroup = item.Subjectgroup,
                    AreaName = item.AreaName,
                    Expectedscore = item.Expectedscore,
                    VipCode = item.VipCode,
                    NickName = item.NickName
                });
            }
            pageModel.data = list;
            pageModel.dataCount = info.dataCount;
            pageModel.page = info.page;
            pageModel.pageCount = info.pageCount;
            pageModel.PageSize = info.PageSize;
            return new MessageModel<PageModel<CustomerInfoListResult>>()
            {
                success = true,
                msg = "获取成功",
                response = pageModel
            };
        }

        public Weixinauthinfo AuthCode2Session(string Code)
        {
            var result = WeixinHelper.AuthCode2Session<Weixinauthinfo>(WeixinConfig.Appid, WeixinConfig.Secret, Code);
            return result;

        }

        public string GetWeixinPhone(GetPhoneInfo phoneInfo)
        {
            string phone = string.Empty;
            try
            {
                phone = WeixinHelper.getPhoneNumber(phoneInfo.encryptedData, phoneInfo.iv, phoneInfo.session_key);
            }
            catch (Exception ex)
            {
            }
            return phone;
        }

        public async Task<Tuple<bool, CustomerInfoResult>> Logined(LoginQuery query)
        {

            var userinfo = (await _dal.Query(w => w.OpenId == query.openId)).ToList().FirstOrDefault();
            if (userinfo != null)
            {
                return new Tuple<bool, CustomerInfoResult>(true, new CustomerInfoResult()
                {
                    AreaId = userinfo.AreaId,
                    AreaName = userinfo.AreaName,
                    AvatarUrl = userinfo.AvatarUrl,
                    CustomerType = userinfo.CustomerType,
                    NickName = userinfo.NickName,
                    OpenId = userinfo.OpenId,
                    Phone = userinfo.Phone,
                    Gender = userinfo.Gender,
                    Datainit = userinfo.Datainit,
                    Expectedscore = userinfo.Expectedscore,
                    IsVIP = userinfo.IsVIP,
                    Subject = userinfo.Subject,
                    Subjectgroup = userinfo.Subjectgroup,
                    subjectgroupName = userinfo.subjectgroupName,
                    ClassName = userinfo.ClassName,
                    SchoolName = userinfo.SchoolName,
                    Year = userinfo.Year,
                    Id = userinfo.Id
                });
            }
            else
            {
                return new Tuple<bool, CustomerInfoResult>(false, null);
            }
        }

        public async Task<Tuple<bool, CustomerInfoResult>> GetUserInfo(LoginQuery query)
        {
            var userinfo = (await _dal.Query(w => w.OpenId == query.openId)).ToList().First();
            if (userinfo != null)
            {
                return new Tuple<bool, CustomerInfoResult>(true, new CustomerInfoResult()
                {

                    AreaId = userinfo.AreaId,
                    AreaName = userinfo.AreaName,
                    AvatarUrl = userinfo.AvatarUrl,
                    CustomerType = userinfo.CustomerType,
                    NickName = userinfo.NickName,
                    OpenId = userinfo.OpenId,
                    Phone = userinfo.Phone,
                    Gender = userinfo.Gender,
                    Datainit = userinfo.Datainit,
                    Expectedscore = userinfo.Expectedscore,
                    IsVIP = userinfo.IsVIP,
                    Subject = userinfo.Subject,
                    Subjectgroup = userinfo.Subjectgroup,
                    subjectgroupName = userinfo.subjectgroupName,
                    Year = userinfo.Year
                });
            }
            else
            {
                return new Tuple<bool, CustomerInfoResult>(false, null);
            }
        }

        public async Task<int> GetCustomerId(string OpenId)
        {
            var customerinfo = await _dal.Query(x => x.IsDelete == false && x.OpenId == OpenId);
            if (customerinfo.Count == 0)
                return -1;
            return customerinfo.FirstOrDefault().Id;
        }

        public async Task<string> GetOpenId(int CustomerId)
        {
            var customerinfo = await _dal.QueryById(CustomerId);
            if (customerinfo == null)
                return "";
            return customerinfo.OpenId;
        }

        public async Task<int> CustomerSave(DecryptUserInfoRequest register)
        {
            var i = await _dal.Add(new V_CustomerInfo()
            {
                OpenId = register.openid,
                CustomerType = CustomerTypeEnum.General
            });
            return i;
        }

        public Task<CustomerInfoResult> Login(CustomerInfoQuery query)
        {
            throw new NotImplementedException();
        }

        public Task<bool> SendLogin(PhoneQuery query)
        {
            throw new NotImplementedException();
        }

        public Task<int> ResetPwd(ResetPwdQuery query)
        {
            throw new NotImplementedException();
        }

        public Task<bool> SendReset(PhoneQuery query)
        {
            throw new NotImplementedException();
        }
    }
}