using AutoMapper;
using MathNet.Numerics.Distributions;
using MathNet.Numerics.Statistics.Mcmc;
using OASystem.Domain;
using OASystem.Domain.Dtos.Resource;
using OASystem.Domain.Entities.Groups;
using OASystem.Domain.Entities.Resource;
using OASystem.Domain.ViewModels.Resource;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

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



        /// <summary>
        /// 根据Diid查询公务出访数据List
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Result> QueryOfficialActivitiesByDiId(OfficialActivitiesByDiIdDto dto)
        {
            Result result = new Result() { Code = -2, Msg = "未知错误" };
            try
            {
                string sqlWhere = string.Empty;
                sqlWhere += string.Format(@"And o.Isdel={0} And o.DiId={1} ", 0, dto.DiId);

                if (!string.IsNullOrEmpty(sqlWhere.Trim()))
                {
                    Regex r = new Regex("And");
                    sqlWhere = r.Replace(sqlWhere, "Where", 1);
                }
                string sql = string.Format(@"select *,(select CnName from Sys_Users where o.CreateUserId=Id) as CreateUserName,OfficialForm
    from Res_OfficialActivities o {0} order by o.CreateTime desc", sqlWhere);
                List<OfficialActivitiesView> OfficialActivities = await _sqlSugar.SqlQueryable<OfficialActivitiesView>(sql).ToListAsync();
                List<Sys_SetData> data = await _sqlSugar.Queryable<Sys_SetData>().Where(a => a.IsDel == 0 && a.STid == 38).ToListAsync();
                if (OfficialActivities.Count != 0)
                {
                    List<Sys_SetData> sdList = Query<Sys_SetData>(s => s.STid == 38).ToList();

                    if (dto.PageSize == 0 && dto.PageIndex == 0)
                    {
                        foreach (var temp in OfficialActivities)
                        {
                            //2024年4月1日 11:55:44  -蒋金辰 -日期处理
                           
                            DateTime dt;
                            bool b_dt = DateTime.TryParse(temp.Date, out dt);
                            if (b_dt)
                            {

                                if (!string.IsNullOrEmpty(temp.Time)) temp.Date = dt.ToString("yyyy-MM-dd") + " " + temp.Time;
                                else temp.Date = dt.ToString("yyyy-MM-dd HH:mm:ss");

                            }

                            //2024年4月26日 17:43  -蒋金辰 -出访形式
                            Sys_SetData tempForm = sdList.FirstOrDefault(s => s.Id == temp.OfficialForm);
                            if (tempForm != null)
                            {
                                temp.OfficialFormName = tempForm.Name;
                            }
                            else
                            {
                                temp.OfficialFormName = "未知";
                            }
                        }

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

                        List<OfficialActivitiesView> _OfficialActivities = new List<OfficialActivitiesView>();
                        for (int i = 0; i < dto.PageSize; i++)
                        {
                            var RowIndex = i + (dto.PageIndex - 1) * dto.PageSize;
                            if (RowIndex < OfficialActivities.Count)
                            {
                                //2024年4月1日 11:55:44  -蒋金辰 -日期处理
                                DateTime dt;
                                bool b_dt = DateTime.TryParse(OfficialActivities[RowIndex].Date, out dt);
                                if (b_dt)
                                {
                                    OfficialActivities[RowIndex].Date = dt.ToString("yyyy-MM-dd HH:mm");
                                }

                                //2024年4月26日 17:43  -蒋金辰 -出访形式
                                Sys_SetData tempForm = sdList.FirstOrDefault(s => s.Id == OfficialActivities[RowIndex].OfficialForm);
                                if (tempForm != null)
                                {
                                    OfficialActivities[RowIndex].OfficialFormName = tempForm.Name;
                                }
                                else
                                {
                                    OfficialActivities[RowIndex].OfficialFormName = "未知";
                                }

                                _OfficialActivities.Add(OfficialActivities[RowIndex]);
                            }
                            else
                            {
                                break;
                            }
                        }


                        ListViewBase<OfficialActivitiesView> rst = new ListViewBase<OfficialActivitiesView>();
                        rst.DataList = _OfficialActivities;
                        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 = OfficialActivities };
                }
            }
            catch (Exception ex)
            {
                result = new Result() { Code = -2, Msg = "未知错误" };
            }
            return result;
        }

        /// <summary>
        /// 根据公务出访Id查询单个数据
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> QueryOfficialActivitiesById(OfficialActivitiesDiIdDto dto)
        {
            Result result = new Result() { Code = -2, Msg = "未知错误" };
            try
            {
                string sqlWhere = string.Empty;
                sqlWhere += string.Format(@"And o.Isdel={0} And o.DiId={1} And o.Id={2}", 0, dto.DiId, dto.Id);

                if (!string.IsNullOrEmpty(sqlWhere.Trim()))
                {
                    Regex r = new Regex("And");
                    sqlWhere = r.Replace(sqlWhere, "Where", 1);
                }
                string sql = string.Format(@"select *,(select CnName from Sys_Users where o.CreateUserId=Id) as CreateUserName,(select Name from Sys_SetData
                                            where Id=o.OfficialForm) as OfficialFormName from Res_OfficialActivities o {0}", sqlWhere);
                OfficialActivitiesView OfficialActivities = await _sqlSugar.SqlQueryable<OfficialActivitiesView>(sql).FirstAsync();
                result = new Result() { Code = 0, Msg = "查询成功！", Data = OfficialActivities };

            }
            catch (Exception ex)
            {
                result = new Result() { Code = -2, Msg = "未知错误" };
            }
            return result;
        }
        public async Task<Result> OpOfficialActivities(OpOfficialActivitiesDto dto)
        {
            Result result = new Result() { Code = -2, Msg = "未知错误" };
            try
            {
                #region 特殊字符转码  037 - 4.28 15:17

                if (!string.IsNullOrEmpty(dto.Contact))
                {
                    byte[] utf8Bytes = Encoding.UTF8.GetBytes(dto.Contact);
                    byte[] utf16Bytes = Encoding.Convert(Encoding.UTF8, Encoding.Unicode, utf8Bytes);
                    dto.Contact = Encoding.Unicode.GetString(utf16Bytes);
                }
                
                #endregion


                if (dto.Status == 1)//添加
                {
                    _sqlSugar.BeginTran();

                    string selectSql = string.Format(@"select * from Res_OfficialActivities where Client='{0}' and Address='{1}' and IsDel='{2}'", dto.Client, dto.Address, 0);
                    var res_InvitationOfficial = await _sqlSugar.SqlQueryable<Res_OfficialActivities>(selectSql).FirstAsync();//查询是否存在
                    if (res_InvitationOfficial != null)
                    {
                        _sqlSugar.RollbackTran();
                        return result = new Result() { Code = -1, Msg = "该信息已存在，请勿重复添加！" };

                    }
                    else//不存在，可添加
                    {

                        Res_OfficialActivities _InvitationOfficialActivityData = _mapper.Map<Res_OfficialActivities>(dto);
                        int id = await _sqlSugar.Insertable(_InvitationOfficialActivityData).ExecuteReturnIdentityAsync();
                        if (id == 0)
                        {
                            _sqlSugar.RollbackTran();
                            return result = new Result() { Code = -1, Msg = "添加失败！" };
                        }

                        //添加到资料库
                        Res_InvitationOfficialActivityData res_InvitationData = new Res_InvitationOfficialActivityData();
                        res_InvitationData.Country = "";
                        res_InvitationData.City = "";
                        res_InvitationData.UnitName = dto.Client;
                        res_InvitationData.Delegation = dto.DiId.ToString();
                        res_InvitationData.Address = dto.Address;
                        res_InvitationData.CreateUserId = dto.CreateUserId;
                        res_InvitationData.Contact = dto.Contact;
                        res_InvitationData.Job = dto.Job;
                        res_InvitationData.Tel = dto.Tel;

                        Res_InvitationOfficialActivityData ifNullUp = await _sqlSugar.Queryable<Res_InvitationOfficialActivityData>().FirstAsync
                            (a => a.Country == res_InvitationData.Country && a.City == res_InvitationData.City && a.UnitName == res_InvitationData.UnitName && a.IsDel == 0 && a.Address == res_InvitationData.Address);

                        if (ifNullUp == null)
                        {
                            int DataID = await _sqlSugar.Insertable(res_InvitationData).ExecuteReturnIdentityAsync();
                            if (DataID != 0)
                            {
                                result = new Result() { Code = 0, Msg = "添加成功！" };
                            }
                            else
                            {
                                result = new Result() { Code = -1, Msg = "添加失败！" };
                            }
                        }

                        _sqlSugar.CommitTran();
                        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_OfficialActivities
                    {
                        Type = dto.Type,
                        Client = dto.Client,
                        Date = dto.Date,
                        Time = dto.Time,
                        Address = dto.Address,
                        Contact = dto.Contact,
                        Job = dto.Job,
                        Tel = dto.Tel,
                        OfficialForm = dto.OfficialForm,
                        Setting = dto.Setting,
                        Dresscode = dto.Dresscode,
                        Attendees = dto.Attendees,
                        IsNeedTrans = dto.IsNeedTrans,
                        Translators = dto.Translators,
                        language = dto.language,
                        Trip = dto.Trip,
                        CreateUserId = dto.CreateUserId,
                        Remark = dto.Remark,
                    });
                    if (!res)
                    {
                        return result = new Result() { Code = -1, Msg = "修改失败！" };
                    }
                    return result = new Result() { Code = 0, Msg = "修改成功！", Data = new { Id = dto.Id } };
                }
                else
                {
                    return result = new Result() { Code = -1, Msg = "请传入Status参数，1添加 2修改！" };
                }
            }
            catch (Exception ex)
            {
                return result = new Result() { Code = -2, Msg = "程序错误！" };
            }
        }
    }
}
