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 DeviceApp : Repository<YB_Device>
    {
        /// <summary>
        /// 设备列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<PageParms<DeviceListModel>> GetListAsync(QueryParams param)
        {
            RefAsync<int> totalnum = 0;
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var temquery = dbClient.Queryable<YB_Device>();
                var currentUser = OperatorProvider.Provider.GetCurrent();
                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);
                    }
                }
                if(currentUser.AccountType != (int)AccountType.platform)
                {
                    temquery = temquery.Where(x => x.BusinessId == currentUser.BusinessId);
                }
                string sorts = string.Format("{0} {1}", param.sort, param.order);
                var query = await temquery.OrderBy(sorts)
                    .Select(x=>new DeviceListModel { 
                        Id=x.Id,
                        Name=x.Name,
                        Ecode=x.Ecode,
                        ActiveTime=x.ActiveTime,
                        BusinessId=x.BusinessId,
                        CreateTime=x.CreateTime,
                        EndTime=x.EndTime,
                        FacCode=x.FacCode,
                        LastHeartTime=x.LastHeartTime,
                        Status=x.Status,
                        Type=x.Type
                    })
                    .Mapper((it, cache) =>
                    {
                        var allbus = cache.Get(list => {
                            var ids = list.Select(x => x.BusinessId).ToList();
                            return dbClient.Queryable<YB_Business>().Where(x => ids.Contains(x.Id)).ToList();
                        });
                        it.BusinessName = allbus.FirstOrDefault(x => x.Id == it.BusinessId)?.Name;
                        var alltype = cache.Get(list => {
                            var ids = list.Select(x => x.Type).ToList();
                            return dbClient.Queryable<YB_DeviceType>().Where(x => ids.Contains(x.Code)).ToList();
                        });
                        it.TypeName = alltype.FirstOrDefault(x => x.Code == it.Type)?.Name;
                    })
                     .ToPageListAsync(param.offset, param.limit, totalnum);
                return new PageParms<DeviceListModel>
                {
                    page = param.offset,
                    Items = query,
                    totalnum = totalnum,
                    limit = param.limit
                };
            }
        }

        /// <summary>
        /// 信息编辑
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ResultInfo> SubmitAsync(YB_Device model)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var currentUser = OperatorProvider.Provider.GetCurrent();
                if (string.IsNullOrEmpty(model.Ecode))
                {
                    return new ResultInfo(ResultState.FAIL, "机器码不可为空");
                }
                if (string.IsNullOrEmpty(model.Name))
                {
                    return new ResultInfo(ResultState.FAIL, "设备名称不可为空");
                }
                if (string.IsNullOrEmpty(model.FacCode))
                {
                    return new ResultInfo(ResultState.FAIL, "序列号不可为空");
                }
                model.Remark = model.Remark.ToStr();
                if (model.Id > 0)
                {
                    //检查机器码是否已存在
                    if (await dbClient.Queryable<YB_Device>().AnyAsync(x => x.Ecode == model.Ecode && x.Id != model.Id))
                    {
                        return new ResultInfo(ResultState.FAIL, "机器码已存在");
                    }
                    //检查序列号是否已存在
                    if (await dbClient.Queryable<YB_Device>().AnyAsync(x => x.FacCode == model.FacCode && x.Id != model.Id))
                    {
                        return new ResultInfo(ResultState.FAIL, "序列号已存在");
                    }
                    //更新
                    //如果是管理员可以修改机器码和序列号
                    if (currentUser.AccountType != (int)AccountType.platform)
                    {
                        await dbClient.Updateable<YB_Device>().SetColumns(x => new YB_Device
                        {
                            Name = model.Name,
                            Remark = model.Remark
                        }).Where(x => x.Id == model.Id).ExecuteCommandAsync();
                    }
                    else
                    {
                        await dbClient.Updateable<YB_Device>().SetColumns(x => new YB_Device
                        {
                            FacCode = model.FacCode,
                            Ecode = model.Ecode,
                            Name = model.Name,
                            Remark = model.Remark,
                            Type = model.Type
                        }).Where(x => x.Id == model.Id).ExecuteCommandAsync();
                    }
                    return new ResultInfo(ResultState.SUCCESS, "更新成功");
                }
                else
                {
                    //检查机器码是否已存在
                    if (await dbClient.Queryable<YB_Device>().AnyAsync(x => x.Ecode == model.Ecode))
                    {
                        return new ResultInfo(ResultState.FAIL, "机器码已存在");
                    }
                    //检查序列号是否已存在
                    if (await dbClient.Queryable<YB_Device>().AnyAsync(x => x.FacCode == model.FacCode))
                    {
                        return new ResultInfo(ResultState.FAIL, "序列号已存在");
                    }
                    model.Status = (int)DeviceStatus.UnActive;
                    model.CreateTime = DateTime.Now;
                    model.ActiveTime = null;
                    model.BusinessId = 0;
                    model.LastHeartTime = null;
                    model.EndTime = null;
                    await dbClient.Insertable<YB_Device>(model).ExecuteCommandAsync();
                    return new ResultInfo(ResultState.SUCCESS, "添加成功");
                }
            }
        }

        /// <summary>
        /// 设备详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<YB_Device> DetailAsync(int id)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                return await dbClient.Queryable<YB_Device>().FirstAsync(x => x.Id == id);
            }
        }
        /// <summary>
        /// 设备类型列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<YB_DeviceType>> GetTypeListAsync()
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                return await dbClient.Queryable<YB_DeviceType>().ToListAsync();
            }
        }
        /// <summary>
        /// 设备类型列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<PageParms<YB_DeviceType>> GetTypeListAsync(QueryParams param)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                RefAsync<int> totalnum = 0;
                var temquery = dbClient.Queryable<YB_DeviceType>();
                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);
                    }
                }
                var query = await temquery.OrderBy(x=>x.CreateTime,OrderByType.Desc)
                                   .ToPageListAsync(param.offset, param.limit, totalnum);
                return new PageParms<YB_DeviceType>
                {
                    page = param.offset,
                    Items = query,
                    totalnum = totalnum,
                    limit = param.limit
                };
            }
        }
        /// <summary>
        /// 设备类型详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<YB_DeviceType> TypeDetailAsync(int id)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                return await dbClient.Queryable<YB_DeviceType>().Where(x => x.Id == id).FirstAsync();
            }
        }

        /// <summary>
        /// 信息编辑
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ResultInfo> SubmitTypeAsync(YB_DeviceType model)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var currentUser = OperatorProvider.Provider.GetCurrent();
                if (string.IsNullOrEmpty(model.Name))
                {
                    return new ResultInfo(ResultState.FAIL, "名称不可为空");
                }
                model.Remark = model.Remark.ToStr();
                if (model.Id > 0)
                {
                    //检查此类型编号是否已存在
                    if (await dbClient.Queryable<YB_DeviceType>().AnyAsync(x => x.Code == model.Code && x.Id != model.Id))
                    {
                        return new ResultInfo(ResultState.FAIL, "此类型已存在");
                    }
                    await dbClient.Updateable<YB_DeviceType>().SetColumns(x => new YB_DeviceType
                    {
                        Name = model.Name,
                        Code = model.Code,
                        ProType = model.ProType,
                        VerType = model.VerType,
                        Remark = model.Remark
                    }).Where(x => x.Id == model.Id).ExecuteCommandAsync();
                    return new ResultInfo(ResultState.SUCCESS, "更新成功");
                }
                else
                {
                    //检查此类型编号是否已存在
                    if (await dbClient.Queryable<YB_DeviceType>().AnyAsync(x => x.Code == model.Code))
                    {
                        return new ResultInfo(ResultState.FAIL, "此类型已存在");
                    }
                    await dbClient.Insertable<YB_DeviceType>(model).ExecuteCommandAsync();
                    return new ResultInfo(ResultState.SUCCESS, "添加成功");
                }
            }
        }
        /// <summary>
        /// 设备批量操作
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<ResultInfo> BatchSetAsync(DeviceBatchModel data)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var currentUser = OperatorProvider.Provider.GetCurrent();
                //分配
                if (data.type == 1)
                {
                    //如果是管理员分配
                    if (currentUser.AccountType == (int)AccountType.platform)
                    {

                        await dbClient.Updateable<YB_Device>().SetColumns(x => new YB_Device
                        {
                            BusinessId = data.BusinessId,
                            ActiveTime = DateTime.Now,
                            Status = (int)DeviceStatus.Run
                        }).Where(x => data.codes.Contains(x.Id)).ExecuteCommandAsync();
                    }
                    else
                    {
                        await dbClient.Updateable<YB_Device>().SetColumns(x => new YB_Device
                        {
                            BusinessId = data.BusinessId
                        }).Where(x => data.codes.Contains(x.Id)).ExecuteCommandAsync();
                    }
                    return new ResultInfo(ResultState.SUCCESS, "设备分配成功");
                }
                else
                {
                    //如果是管理员回收
                    if (currentUser.AccountType == (int)AccountType.platform)
                    {
                        await dbClient.Updateable<YB_Device>().SetColumns(x => new YB_Device
                        {
                            BusinessId = 0,
                            ActiveTime = null,
                            Status = (int)DeviceStatus.UnActive
                        }).Where(x => data.codes.Contains(x.Id)).ExecuteCommandAsync();
                    }
                    else
                    {
                        await dbClient.Updateable<YB_Device>().SetColumns(x => new YB_Device
                        {
                            BusinessId = currentUser.BusinessId
                        }).Where(x => data.codes.Contains(x.Id)).ExecuteCommandAsync();
                    }
                    return new ResultInfo(ResultState.SUCCESS, "设备回收成功");
                }
            }
        }
    }
}
