using AutoMapper;
using OASystem.Domain;
using OASystem.Domain.AesEncryption;
using OASystem.Domain.Dtos.Resource;
using OASystem.Domain.Entities.Groups;
using OASystem.Domain.Entities.Resource;
using OASystem.Domain.ViewModels.Resource;
using Org.BouncyCastle.Utilities;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OASystem.Infrastructure.Repositories.Resource
{
    public class LocalGuideDataRepository : BaseRepository<Res_LocalGuideData, LocalGuideDataView>
    {
        private readonly IMapper _mapper;
        public LocalGuideDataRepository(SqlSugarClient sqlSugar, IMapper mapper) : base(sqlSugar)
        {
            _mapper = mapper;
        }
        public async Task<Result> LocalGuideOperation(LocalGuideOperationDto dto)
        {
            var localGuideDat = _mapper.Map<Res_LocalGuideData>(dto);
            localGuideDat.LastUpdateTime = DateTime.Now;
            localGuideDat.LastUpdateUserId = dto.CreateUserId;
            EncryptionProcessor.EncryptProperties(localGuideDat);

            if (dto.Status == 1)//添加
            {
                string selectSql = string.Format(@"select * from Res_LocalGuideData where UnitArea='{0}' and UnitName='{1}' and Contact='{2}' and ContactTel='{3}'",
                                                   AesEncryptionHelper.Encrypt(dto.UnitArea),
                                                   AesEncryptionHelper.Encrypt(dto.UnitName),
                                                   AesEncryptionHelper.Encrypt(dto.Contact),
                                                   AesEncryptionHelper.Encrypt(dto.ContactTel));
                var LocalGuideData = await _sqlSugar.SqlQueryable<Res_LocalGuideData>(selectSql).FirstAsync();//查询是否存在
                if (LocalGuideData != null) return new Result() { Code = -1, Msg = "该信息已存在,请勿重复添加!" };
                else//不存在,可添加
                {
                    int id = await AddAsyncReturnId(localGuideDat);
                    if (id == 0) return new Result() { Code = -1, Msg = "添加失败!" };
                    return new Result() { Code = 0, Msg = "添加成功!", Data = new { Id = id } };
                }
            }
            else if (dto.Status == 2)//修改
            {
                var res = await _sqlSugar.Updateable(localGuideDat).IgnoreColumns(x => new { x.IsDel, x.CreateUserId, x.CreateTime, x.DeleteUserId, x.DeleteTime }).ExecuteCommandAsync();

                if (res < 1)
                {
                    return new Result() { Code = -1, Msg = "修改失败!" };
                }
                return new Result() { Code = 0, Msg = "修改成功!" };
            }

            return new Result() { Code = -1, Msg = "请传入Status参数,1添加 2修改!" };
        }

        public async Task<Result> QueryLocalGuide(QueryLocalGuide dto)
        {
            Result result = new Result() { Code = -2, Msg = "未知错误" };

            string unitName = dto.UnitName, unitArea = dto.UnitArea, contact = dto.Contact, contactTel = dto.ContactTel;
            int pageSize = dto.PageSize, pageIndex = dto.PageIndex;

            var localGuideDataSearch = await _sqlSugar
                .Queryable<Res_LocalGuideData>()
                .Where(x => x.IsDel == 0)
                .Select(x => new Res_LocalGuideData()
                {
                    Id = x.Id,
                    UnitName = x.UnitName,
                    UnitArea = x.UnitArea,
                    Contact = x.Contact,
                    ContactTel = x.ContactTel
                })
                .ToListAsync();

            //处理要查询的字段解密
            foreach (var item in localGuideDataSearch)
            {
                item.UnitName = AesEncryptionHelper.Decrypt(item.UnitName);
                item.UnitArea = AesEncryptionHelper.Decrypt(item.UnitArea);
                item.Contact = AesEncryptionHelper.Decrypt(item.Contact);
                item.ContactTel = AesEncryptionHelper.Decrypt(item.ContactTel);
            }
            var localGuideIds = localGuideDataSearch
                .WhereIF(!string.IsNullOrEmpty(unitName), x => !string.IsNullOrEmpty(x.UnitName) && x.UnitName.Contains(unitName))
                .WhereIF(!string.IsNullOrEmpty(unitArea), x => !string.IsNullOrEmpty(x.UnitArea) && x.UnitArea.Contains(unitArea))
                .WhereIF(!string.IsNullOrEmpty(contact), x => !string.IsNullOrEmpty(x.Contact) && x.Contact.Contains(contact))
                .WhereIF(!string.IsNullOrEmpty(contactTel), x => !string.IsNullOrEmpty(x.ContactTel) && x.ContactTel.Contains(contactTel))
                .Select(x => x.Id)
                .ToList();

            var localGuideDataInfos = await _sqlSugar
                .Queryable<Res_LocalGuideData>()
                .WhereIF(localGuideIds.Any(), x => localGuideIds.Contains(x.Id))
                .ToListAsync();
            var localGuideDatas = _mapper.Map<List<LocalGuideDataView>>(localGuideDataInfos);
            if (dto.PortType == 1 || dto.PortType == 2)
            {
                if (localGuideDatas.Count == 0)
                {
                    return result = new Result() { Code = 0, Msg = "暂无数据" };
                }
                localGuideDatas = localGuideDatas.OrderByDescending(x => x.CreateTime).ToList();

                if (dto.PageSize == 0 || dto.PageIndex == 0)
                {
                    foreach (var item in localGuideDatas) EncryptionProcessor.DecryptProperties(item);

                    return result = new Result()
                    {
                        Code = 0,
                        Msg = "查询成功",
                        Data = localGuideDatas,
                    };
                }
                else
                {
                    int totalItems = localGuideDatas.Count(); 
                    int totalPages = (int)Math.Ceiling((double)totalItems / pageSize);
                    int skip = (pageIndex - 1) * pageSize;

                    var pageSource = localGuideDatas.Skip(skip).Take(pageSize).ToList();
                    foreach (var item in pageSource) EncryptionProcessor.DecryptProperties(item);
                    return result = new Result()
                    {
                        Code = 0,
                        Msg = "查询成功",
                        Data = new { pageCount = totalItems, totalPage = totalPages, pageIndex = dto.PageIndex, pageSize = dto.PageSize, pageSource = pageSource },
                    };
                }

            }
            else if (dto.PortType == 3)
            {
                if (localGuideDatas.Count == 0)
                {
                    return result = new Result() { Code = 0, Msg = "暂无数据" };
                }
                localGuideDatas = localGuideDatas.OrderByDescending(x => x.CreateTime).ToList();

                if (dto.PageSize == 0 && dto.PageIndex == 0)
                {
                    foreach (var item in localGuideDatas) EncryptionProcessor.DecryptProperties(item);
                    return result = new Result()
                    {
                        Code = 0,
                        Msg = "查询成功",
                        Data = localGuideDatas,
                    };
                }
                else
                {

                    int totalItems = localGuideDatas.Count();
                    int totalPages = (int)Math.Ceiling((double)totalItems / pageSize);
                    int skip = (pageIndex - 1) * pageSize;

                    var pageSource = localGuideDatas.Skip(skip).Take(pageSize).ToList();

                    foreach (var item in pageSource) EncryptionProcessor.DecryptProperties(item); ;

                    var pageSoure1 = _mapper.Map<Res_LocalGuideData_ListItemView>(pageSource);

                    return result = new Result()
                    {
                        Code = 0,
                        Msg = "查询成功",
                        Data = new { pageCount = totalItems, totalPage = pageSource, pageIndex = dto.PageIndex, pageSize = dto.PageSize, pageSource = pageSoure1 },
                    };
                }
            }

            return result = new Result() { Code = -2, Msg = "请传入PortType参数!1:Web,2:Android,3:IOS" };
        }

    }
}