using Nirvana.Common;
using Nirvana.Common.ApiBase;
using Nirvana.Data;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YBDevice.Entity;

namespace YBDevice.Service.DBServices
{
    /// <summary>
    /// 客户管理
    /// </summary>
    public partial class BusinessApp : Repository<YB_Business>
    {
        /// <summary>
        /// 客户列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<PageParms<YB_Business>> GetListAsync(QueryParams param)
        {
            RefAsync<int> totalnum = 0;
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var currentUser = OperatorProvider.Provider.GetCurrent();
                var temquery = dbClient.Queryable<YB_Business>();
                if (param.queryParam != null && param.queryParam.Count > 0)
                {
                    List<IConditionalModel> conModels = new List<IConditionalModel>();
                    param.queryParam.ForEach(x =>
                    {
                        if (!string.IsNullOrEmpty(x.Value))
                        {
                            conModels.Add(new ConditionalModel()
                            {
                                FieldName = x.Name,
                                ConditionalType = (ConditionalType)x.Type,
                                FieldValue = x.Value.Trim()
                            });
                        }
                    });
                    if (conModels.Count > 0)
                    {
                        temquery = temquery.Where(conModels);
                    }
                }
                string sorts = string.Format("{0} {1}", param.sort, param.order);
                var query = await temquery.OrderBy(sorts)
                     .ToPageListAsync(param.offset, param.limit, totalnum);
                return new PageParms<YB_Business>
                {
                    page = param.offset,
                    Items = query,
                    totalnum = totalnum,
                    limit = param.limit
                };
            }
        }

        /// <summary>
        /// 所有客户列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<YB_Business>> GetAllListAsync()
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var currentUser = OperatorProvider.Provider.GetCurrent();
                var tempquery = dbClient.Queryable<YB_Business>();
                if(currentUser.AccountType != (int)AccountType.platform)
                {
                    tempquery = tempquery.Where(x => SqlFunc.StartsWith(x.Code, currentUser.BusinessCode));
                }
                return await tempquery.OrderBy(x => x.CreateTime, OrderByType.Desc).ToListAsync();
            }
        }

        /// <summary>
        /// 信息提交
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ResultInfo> SubmitAsync(BusinessSubmitModel model)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var currentUser = OperatorProvider.Provider.GetCurrent();
                if (model.Id > 0)
                {
                    //检查手机号是否存在
                    if (await dbClient.Queryable<YB_Business>().AnyAsync(x => x.Id != model.Id && x.Phone == model.Phone))
                    {
                        return new ResultInfo(ResultState.FAIL, "此手机号已注册");
                    }
                    model.Remark = model.Remark.ToStr();
                    await dbClient.Updateable<YB_Business>().SetColumns(x => new YB_Business
                    {
                        Name = model.Name,
                        Phone = model.Phone,
                        Remark = model.Remark
                    }).Where(x => x.Id == model.Id).ExecuteCommandAsync();

                    await dbClient.Updateable<YB_Account>().SetColumns(x => new YB_Account
                    {
                        AccountType = model.AccountType,
                        Phone = model.Phone,
                        RealName = model.Name
                    }).Where(x => x.BusinessId == model.Id).ExecuteCommandAsync();
                    return new ResultInfo(ResultState.SUCCESS, "修改成功");
                }
                else
                {
                    //检查手机号是否存在
                    if (await dbClient.Queryable<YB_Business>().AnyAsync(x => x.Phone == model.Phone))
                    {
                        return new ResultInfo(ResultState.FAIL, "此手机号已注册");
                    }
                    //生成编码
                    var code = currentUser.BusinessCode.ToStr();
                    string scode = "0001";
                    int parentid = 0;
                    if (currentUser.AccountType != (int)AccountType.platform)
                    {
                        var cnt = await dbClient.Queryable<YB_Business>().CountAsync(x => x.ParentId == currentUser.BusinessId);
                        scode = GenCode(cnt);
                        if (string.IsNullOrEmpty(scode))
                        {
                            return new ResultInfo(ResultState.FAIL, "超过最大注册数量");
                        }
                        parentid = currentUser.BusinessId;
                    }
                    else
                    {
                        var cnt = await dbClient.Queryable<YB_Business>().CountAsync(x => x.ParentId == 0);
                        scode = GenCode(cnt);
                        if (string.IsNullOrEmpty(scode))
                        {
                            return new ResultInfo(ResultState.FAIL, "超过最大注册数量");
                        }
                    }
                    code = $"{code}{scode}";
                    var buss = new YB_Business
                    {
                        CreateTime = DateTime.Now,
                        Status = (int)StatusType.Enabled,
                        Name = model.Name,
                        Phone = model.Phone,
                        Remark = model.Remark.ToStr(),
                        ParentId = parentid,
                        Type = 1,
                        Code=code
                    };
                    var bid = await dbClient.Insertable<YB_Business>(buss).ExecuteReturnIdentityAsync();
                    var user = new YB_Account
                    {
                        Secret = Md5.md5(Common.CreateNo(), 16).ToLower(),
                        AccountType = model.AccountType,
                        Status = (int)StatusType.Enabled,
                        BusinessId = bid,
                        CreateTime = DateTime.Now,
                        LastVisitIP = "",
                        LastVisitTime = DateTime.Now,
                        Phone = model.Phone,
                        RealName = model.Name,
                        RoleId = 2,
                        UserName = model.Phone
                    };
                    user.Password = Md5.md5(DESEncrypt.Encrypt(Md5.md5(model.password, 32).ToLower(), user.Secret).ToLower(), 32).ToLower();
                    await dbClient.Insertable<YB_Account>(user).ExecuteCommandAsync();
                    return new ResultInfo(ResultState.SUCCESS, "添加成功");
                }
            }
        }
        /// <summary>
        /// 生成code
        /// </summary>
        /// <param name="cnt"></param>
        /// <returns></returns>
        private string GenCode(int cnt) =>
            cnt switch
            {
                < 9 => $"000{cnt + 1}",
                < 99 and >= 9 => $"00{cnt + 1}",
                < 999 and >= 99 => $"0{cnt + 1}",
                < 9999 and >= 999 => $"{cnt + 1}",
                _ => ""
            };
        /// <summary>
        /// 客户详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<BusinessSubmitModel> Detail(int id)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var buss = await dbClient.Queryable<YB_Business>().FirstAsync(x => x.Id == id);
                var user = await dbClient.Queryable<YB_Account>().FirstAsync(x => x.BusinessId == buss.Id);
                return new BusinessSubmitModel
                {
                    AccountType = user.AccountType,
                    Name = buss.Name,
                    Phone = buss.Phone,
                    Id = buss.Id,
                    Remark = buss.Remark
                };
            }
        }
        /// <summary>
        /// 状态变更
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public async Task<ResultInfo> SetStatusAsync(int id, int status)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                if (!await dbClient.Queryable<YB_Business>().AnyAsync(x => x.Id == id))
                {
                    return new ResultInfo(ResultState.FAIL, "用户未找到");
                }
                await dbClient.Updateable<YB_Business>().SetColumns(x => new YB_Business
                {
                    Status = status
                }).Where(x => x.Id == id).ExecuteCommandAsync();
                await dbClient.Updateable<YB_Account>().SetColumns(x => new YB_Account
                {
                    Status = status
                }).Where(x => x.Id == id).ExecuteCommandAsync();
                return new ResultInfo(ResultState.SUCCESS, "更新成功");
            }
        }
        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultInfo> ResetPasswordAsync(int id)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var buss = await dbClient.Queryable<YB_Business>().FirstAsync(x => x.Id == id);
                if (buss == null)
                {
                    return new ResultInfo(ResultState.FAIL, "用户未找到");
                }
                var password = "123456";
                var user = await dbClient.Queryable<YB_Account>().FirstAsync(x => x.BusinessId == buss.Id);
                var Password = Md5.md5(DESEncrypt.Encrypt(Md5.md5(password, 32).ToLower(), user.Secret).ToLower(), 32).ToLower();
                await dbClient.Updateable<YB_Account>().SetColumns(x => new YB_Account
                {
                    Password = Password
                }).Where(x => x.Id == user.Id).ExecuteCommandAsync();
                return new ResultInfo(ResultState.SUCCESS, "重置成功");
            }
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ResultInfo> ChangePasswordAsync(BusinessSubmitModel model)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var currentUser = OperatorProvider.Provider.GetCurrent();
                if (model.password != model.repassword)
                {
                    return new ResultInfo(ResultState.FAIL, "两次密码不一致");
                }
                var user = await dbClient.Queryable<YB_Account>().FirstAsync(x => x.BusinessId == currentUser.BusinessId);
                var Password = Md5.md5(DESEncrypt.Encrypt(Md5.md5(model.password, 32).ToLower(), user.Secret).ToLower(), 32).ToLower();
                await dbClient.Updateable<YB_Account>().SetColumns(x => new YB_Account
                {
                    Password = Password
                }).Where(x => x.Id == user.Id).ExecuteCommandAsync();
                return new ResultInfo(ResultState.SUCCESS, "修改成功");
            }
        }


    }
}
