using AutoMapper;
using Newtonsoft.Json;
using OASystem.Domain;
using OASystem.Domain.AesEncryption;
using OASystem.Domain.Dtos.Groups;
using OASystem.Domain.Dtos.Resource;
using OASystem.Domain.Entities.Customer;
using OASystem.Domain.Entities.Groups;
using OASystem.Domain.Entities.Resource;
using OASystem.Domain.ViewModels;
using OASystem.Domain.ViewModels.Groups;
using OASystem.Domain.ViewModels.Resource;
using OASystem.Infrastructure.Tools;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace OASystem.Infrastructure.Repositories.Resource
{
    public class InvitationOfficialActivityDataRepository : BaseRepository<Res_InvitationOfficialActivityData, InvitationOfficialActivitiesByIdDto>
    {
        private readonly IMapper _mapper;
        public InvitationOfficialActivityDataRepository(SqlSugarClient sqlSugar, IMapper mapper) : base(sqlSugar)
        {
            _mapper = mapper;
        }

        /// <summary>
        /// 查询商邀资料列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<JsonView> QueryInvitationOfficialActivityData(QueryInvitationOfficialActivityDataDto dto)
        {
            var result = new JsonView() { Msg = "操作失败!" };

            //验证日期格式
            DateTime _beginDt, _endDt;
            var _beginDtBool = DateTime.TryParse(dto.StartCreateTime+" 00:00:00", out _beginDt);
            var _endDtBool = DateTime.TryParse(dto.EndCreateTime + " 23:59:59", out _endDt);

            RefAsync<int> total = 0;
            
            var _view = await _sqlSugar.Queryable<Res_InvitationOfficialActivityData>()
                                        .LeftJoin<Sys_Users>((ioa, u) => ioa.CreateUserId == u.Id)
                                        .Where((ioa,u) => ioa.IsDel == 0)
                                        .WhereIF(!string.IsNullOrEmpty(dto.Country), (ioa, u) => ioa.Country.Contains(dto.Country))
                                        .WhereIF(!string.IsNullOrEmpty(dto.UnitName), (ioa, u) => ioa.UnitName.Contains(dto.UnitName))
                                        .WhereIF(!string.IsNullOrEmpty(dto.Contact), (ioa, u) => ioa.Contact.Contains(dto.Contact))
                                        .WhereIF(!string.IsNullOrEmpty(dto.Delegation), (ioa, u) => ioa.Delegation.Contains(dto.Delegation))
                                        .WhereIF(!string.IsNullOrEmpty(dto.Field), (ioa, u) => ioa.Field.Contains(dto.Field))
                                        .WhereIF(_beginDtBool && _endDtBool, (ioa, u) => ioa.CreateTime >= _beginDt && ioa.CreateTime <= _endDt)
                                        .WhereIF(dto.CreateUserId > 0, (ioa, u) => ioa.CreateUserId == dto.CreateUserId)
                                        .Select((ioa, u) => new { 
                                            Row_Number = ioa.RowIndex,
                                            ioa.Id,
                                            ioa.Country,
                                            ioa.City,
                                            ioa.UnitName,
                                            ioa.Field,
                                            ioa.Contact,
                                            ioa.Job,
                                            ioa.Tel,
                                            ioa.CreateTime,
                                            CreateUserName = u.CnName,
                                            DelegationStr = ioa.Delegation
                                        })
                                        .OrderByDescending((ioa) => ioa.CreateTime)
                                        .ToPageListAsync(dto.PageIndex, dto.PageSize, total);


            foreach (var item in _view)
            {
                string groupNameStr = "";
                int[] groupIds = item.DelegationStr.Split(',').Select(x =>
                {
                    int id;
                    if (int.TryParse(x, out id)) return id;
                    else return id;
                }).ToArray();

               var _DelegationInfos = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => groupIds.Contains(x.Id)).ToList();
                foreach (var group in _DelegationInfos)
                {
                    groupNameStr += $"{group.TeamName},";
                }
                if (groupNameStr.Length > 1)
                {
                    groupNameStr= groupNameStr.Substring(0, groupNameStr.Length - 1);
                }
            }
            result.Code = StatusCodes.Status200OK;
            result.Msg = $"操作成功!";
            result.Data = _view;
            result.Count = _view.Count;

            return result;






            //try
            //{
            //    string sqlWhere = string.Empty;
            //    if (!string.IsNullOrWhiteSpace(dto.Country)) { sqlWhere += string.Format(@" And i.Country like '%{0}%'", dto.Country); }
            //    if (!string.IsNullOrWhiteSpace(dto.UnitName)) { sqlWhere += string.Format(@" And i.UnitName like '%{0}%'", dto.UnitName); }
            //    if (!string.IsNullOrWhiteSpace(dto.Contact)) { sqlWhere += string.Format(@" And i.Contact like '%{0}%'", dto.Contact); }
            //    if (!string.IsNullOrWhiteSpace(dto.Delegation)) { sqlWhere += string.Format(@" And ','+i.Delegation+',' like '%,{0},%'", dto.Delegation); }
            //    if (!string.IsNullOrWhiteSpace(dto.Field)) { sqlWhere += string.Format(@" And i.Field like '%{0}%'", dto.Field); }

            //    if (dto.CreateUserId != 0 && !string.IsNullOrWhiteSpace(dto.CreateUserId.ToString())) { sqlWhere += string.Format(@" And i.CreateUserId={0}", dto.CreateUserId); }
            //    if (!string.IsNullOrWhiteSpace(dto.StartCreateTime) && !string.IsNullOrWhiteSpace(dto.EndCreateTime))
            //    {
            //        sqlWhere += string.Format(@" And i.CreateTime between '{0}' and '{1}'", dto.StartCreateTime, dto.EndCreateTime);
            //    }
            //    sqlWhere += string.Format(@"And Isdel={0}", 0);

            //    if (!string.IsNullOrEmpty(sqlWhere.Trim()))
            //    {
            //        Regex r = new Regex("And");
            //        sqlWhere = r.Replace(sqlWhere, "Where", 1);
            //    }
            //    string sql = string.Format(@"select i.*,(select CnName from Sys_Users where Id=i.CreateUserId ) as CreateUserName from 
            //                                Res_InvitationOfficialActivityData i {0} order by CreateTime desc", sqlWhere);
            //    List<InvitationOfficialActivityDataView> _ivitiesViews =  _sqlSugar.SqlQueryable<InvitationOfficialActivityDataView>(sql).ToList();
            //    if (_ivitiesViews.Count != 0)
            //    {
            //        List<Grp_DelegationInfo> _DelegationInfos = _sqlSugar.Queryable<Grp_DelegationInfo>().ToList();

            //        foreach (var item in _ivitiesViews)
            //        {
            //            string delegationNameList = "";
            //            string[] DelegationName = item.Delegation.Split(',');
            //            for (int i = 0; i < DelegationName.Length; i++)
            //            {
            //                //Grp_DelegationInfo _DelegationInfo = await _sqlSugar.Queryable<Grp_DelegationInfo>().FirstAsync(a => a.Id ==int.Parse(DelegationName[i]));
            //                //if (_DelegationInfo != null) { delegationNameList += _DelegationInfo.TeamName + ","; }

            //                delegationNameList += _DelegationInfos.Find(it => it.Id == int.Parse(DelegationName[i]))?.TeamName ?? "Unknown" + ",";
            //            }
            //            if (!string.IsNullOrWhiteSpace(delegationNameList))
            //            {
            //                item.DelegationStr = delegationNameList.Substring(0, delegationNameList.Length - 1);
            //            }

            //        }
            //        if (dto.PageSize == 0 && dto.PageIndex == 0)
            //        {
            //            result = new Result() { Code = 0, Msg = "查询成功!", Data = _ivitiesViews };
            //        }
            //        else
            //        {
            //            int count = _ivitiesViews.Count;
            //            float totalPage = (float)count / dto.PageSize;//总页数
            //            if (totalPage == 0) totalPage = 1;
            //            else totalPage = (int)Math.Ceiling((double)totalPage);

            //            List<InvitationOfficialActivityDataView> invitations = new List<InvitationOfficialActivityDataView>();
            //            for (int i = 0; i < dto.PageSize; i++)
            //            {
            //                var RowIndex = i + (dto.PageIndex - 1) * dto.PageSize;
            //                if (RowIndex < _ivitiesViews.Count)
            //                {
            //                    invitations.Add(_ivitiesViews[RowIndex]);
            //                }
            //                else
            //                {
            //                    break;
            //                }
            //            }
            //            ListViewBase<InvitationOfficialActivityDataView> rst = new ListViewBase<InvitationOfficialActivityDataView>();
            //            rst.DataList = invitations; 
            //            rst.DataCount = count;
            //            rst.CurrPageIndex = dto.PageIndex;
            //            rst.CurrPageSize = dto.PageSize;
            //            result = new Result() { Code = 0, Msg = "查询成功!", Data = rst };
            //        }

            //    }
            //    else
            //    {
            //        result = new Result() { Code = 0, Msg = "暂无数据!", Data = _ivitiesViews };
            //    }
            //}
            //catch (Exception ex)
            //{
            //    result = new Result() { Code = -2, Msg = ex.Message };
            //}
            //return result;
        }
        /// <summary>
        /// 根据Id查询商邀资料信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<JsonView> Info(int id)
        {
            var res = await _sqlSugar.Queryable<Res_InvitationOfficialActivityData>()
                                     .Where(x => x.Id == id && x.IsDel == 0)
                                     .FirstAsync();
            EncryptionProcessor.DecryptProperties(res);
            var _view = _mapper.Map<IOAInfoView>(res);
            return new JsonView() { Code = StatusCodes.Status200OK, Msg = "操作成功", Data = _view };
        }

        public async Task<JsonView> IOA_OP(OpInvitationOfficialActivityDto dto)
        {
            JsonView result = new JsonView() { Code = StatusCodes.Status400BadRequest, Msg = "操作失败!" };

            var _info = _mapper.Map<Res_InvitationOfficialActivityData>(dto);

            if (dto.Status == 1)//添加
            {
                //string selectSql = string.Format(@"select * from Res_InvitationOfficialActivityData where UnitName='{0}' and IsDel='{1}'", dto.UnitName, 0);
                //var res_InvitationOfficial = await _sqlSugar.SqlQueryable<Res_InvitationOfficialActivityData>(selectSql).FirstAsync();//查询是否存在
                //if (res_InvitationOfficial != null)
                //{
                //    result.Msg = $"该信息已存在,请勿重复添加!";
                //    return result;
                //}

                #region 处理上传文件
                var fileNames = await Upload(dto.Files);
                if (fileNames.Count > 0)
                {
                    _info.SndFileName = JsonConvert.SerializeObject(fileNames);
                }

                #endregion
                EncryptionProcessor.EncryptProperties(_info);
                var id = await _sqlSugar.Insertable(_info).ExecuteReturnIdentityAsync();
                if (id < 1) return result;

            }
            else if (dto.Status == 2)//修改
            {
                var fileNameJsonStr = string.Empty;
                var fileNames = await Upload(dto.Files);
                if (fileNames.Count > 0)
                { 
                    var ioaInfo = await _sqlSugar.Queryable<Res_InvitationOfficialActivityData>().FirstAsync(x => x.IsDel == 0 && x.Id == dto.Id);
                    if (ioaInfo != null) {
                        var fileName = ioaInfo.SndFileName;
                        if (!string.IsNullOrEmpty(fileName))
                        {
                            try
                            {
                                var ioaFiles = JsonConvert.DeserializeObject<List<string>>(fileName);
                                fileNames.AddRange(ioaFiles);
                            }
                            catch (Exception)
                            {
                                fileNames.Add(fileName);
                            }
                        }
                    }

                    fileNameJsonStr = JsonConvert.SerializeObject(fileNames);
                }
                _info.SndFileName = fileNameJsonStr;
                EncryptionProcessor.EncryptProperties(_info);
                bool res = await UpdateAsync(a => a.Id == dto.Id, a => new Res_InvitationOfficialActivityData
                {
                    Country = _info.Country,
                    City = _info.City,
                    UnitName = _info.UnitName,
                    UnitWeb = _info.UnitWeb,
                    Field = _info.Field,
                    Address = _info.Address,
                    UnitInfo = _info.UnitInfo,
                    Contact = _info.Contact,
                    Job = _info.Job,
                    Tel = _info.Tel,
                    Email = _info.Email,
                    WeChat = _info.WeChat,
                    FaceBook = _info.FaceBook,
                    Ins = _info.Ins,
                    Delegation = _info.Delegation,
                    FilePath = _info.FilePath,
                    SndFileName = _info.SndFileName,
                    Fax = _info.Fax,
                    //CreateUserId = _info.CreateUserId,
                    Remark = _info.Remark
                });

                if (!res) return result;

                //操作成功记录操作
                Crm_TableOperationRecord operationRecord = new Crm_TableOperationRecord
                {
                    CreateTime = DateTime.Now,
                    CreateUserId = dto.CreateUserId,
                    DataId = dto.Id,
                    IsDel = 0,
                    OperationItem = OperationEnum.Edit,
                    PortType = 1,
                    TableName = "Res_InvitationOfficialActivityData",
                };

                await _sqlSugar.Insertable(operationRecord).ExecuteCommandAsync();
            }
            else
            {
                result.Msg = $"请传入Status参数,1添加 2修改!";
                return result;
            }

            result.Msg = $"操作成功!";
            result.Code = StatusCodes.Status200OK;
            return result;
        }


        public async Task< List<string>> Upload(IFormFile[] formFiles)
        {
            var fileNames = new List<string>();

            if (formFiles != null && formFiles.Length > 0)
            {
                var filePath = $@"{AppSettingsHelper.Get("GrpFileBasePath")}/商邀相关文件";
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }

                foreach (var file in formFiles)
                {
                    //filePath = @$"{filePath}/{file.FileName}";

                    var path = Path.Combine(filePath, file.FileName);

                    using (var stream = new FileStream(path, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);
                    }

                    fileNames.Add(file.FileName);
                }
            }

            return fileNames;
        }
    }
}