using AutoMapper;
using OASystem.Domain;
using OASystem.Domain.Dtos.Groups;
using OASystem.Domain.Dtos.Resource;
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 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<Result> QueryInvitationOfficialActivityData(QueryInvitationOfficialActivityDataDto dto)
        {
            Result result = new Result() { Code = -2, Msg = "未知错误" };
            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<Result> QueryInvitationOfficialActivityById(QueryInvitationOfficialActivityByIdDto dto)
        {
            Result result = new Result() { Code = -2, Msg = "未知错误" };
            try
            {
                Res_InvitationOfficialActivityData res_Invitation = await _sqlSugar.Queryable<Res_InvitationOfficialActivityData>().FirstAsync(a => a.Id == dto.Id && a.IsDel == 0);
                if (res_Invitation!=null) {
                    result = new Result() { Code = 0, Msg = "查询成功!", Data = res_Invitation };
                }
                else
                {
                    result = new Result() { Code = 0, Msg = "暂无数据!", Data = res_Invitation };
                }
            }
            catch (Exception ex)
            {
                result = new Result() { Code = -2, Msg = "未知错误" };
            }
            return result;
        }

        public async Task<Result> OpInvitationOfficialActivity(OpInvitationOfficialActivityDto dto)
        {
            Result result = new Result() { Code = -2, Msg = "未知错误" };
            try
            {
                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)
                    {
                        return result = new Result() { Code = -1, Msg = "该信息已存在,请勿重复添加!" };

                    }
                    else//不存在,可添加
                    {
                        Res_InvitationOfficialActivityData _InvitationOfficialActivityData = _mapper.Map<Res_InvitationOfficialActivityData>(dto);
                        int id = await _sqlSugar.Insertable(_InvitationOfficialActivityData).ExecuteReturnIdentityAsync();
                        if (id == 0)
                        {
                            return result = new Result() { Code = -1, Msg = "添加失败!" };

                        }
                        return result = new Result() { Code = 0, Msg = "添加成功!", Data = new { Id = id } };
                    }
                }
                else if (dto.Status == 2)//修改
                {
                    bool res = await UpdateAsync(a => a.Id == dto.Id, a => new Res_InvitationOfficialActivityData
                    {
                        Country = dto.Country,
                        City = dto.City,
                        UnitName = dto.UnitName,
                        UnitWeb = dto.UnitWeb,
                        Field = dto.Field,
                        Address = dto.Address,
                        UnitInfo = dto.UnitInfo,
                        Contact = dto.Contact,
                        Job = dto.Job,
                        Tel = dto.Tel,
                        Email = dto.Email,
                        WeChat = dto.WeChat,
                        FaceBook = dto.FaceBook,
                        Ins = dto.Ins,
                        Delegation = dto.Delegation,
                        FilePath = dto.FilePath,
                        SndFilePath = dto.SndFilePath,
                        Fax = dto.Fax,
                        CreateUserId = dto.CreateUserId,
                        Remark = dto.Remark
                    });
                    if (!res)
                    {
                        return result = new Result() { Code = -1, Msg = "修改失败!" };
                    }
                    return result = new Result() { Code = 0, Msg = "修改成功!" };
                }
                else
                {
                    return result = new Result() { Code = -1, Msg = "请传入Status参数,1添加 2修改!" };
                }
            }
            catch (Exception ex)
            {
                return result = new Result() { Code = -2, Msg = "程序错误!" };
            }
        }
    }
}