using Newtonsoft.Json;
using OASystem.Domain;
using OASystem.Domain.Dtos.Financial;
using OASystem.Domain.Dtos.Groups;
using OASystem.Domain.Entities.Financial;
using OASystem.Domain.ViewModels.Financial;
using OASystem.Infrastructure.Repositories.System;
using Serilog;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OASystem.Infrastructure.Repositories.Groups
{
    /// <summary>
    /// 团组汇率 仓库
    /// </summary>
    public class TeamRateRepository : BaseRepository<Grp_TeamRate, TeamRateView>
    {
        private readonly SetDataRepository _setDataRep;
        private readonly DelegationInfoRepository _deleInfoRep;

        public TeamRateRepository(SqlSugarClient sqlSugar, SetDataRepository setDataRep, DelegationInfoRepository deleInfoRep)
            : base(sqlSugar)
        {
            _setDataRep = setDataRep;
            _deleInfoRep = deleInfoRep;
        }

        /// <summary>
        /// 团组汇率 Rep
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Result> GetGroupRateDataSource(TeamRateDto dto)
        {

            Result result = new() { Code = -2 };

            GroupNameDto groupNameDto = new GroupNameDto() { PortType = dto.PortType};
            var groups = await _deleInfoRep.GetGroupNameList(groupNameDto);

            var teamRateDatas = await _setDataRep.GetSetDataBySTId(_setDataRep, 66); // STid=66 全球币种

            

            dynamic _data = null;

            if (dto.PortType == 1)
            {
                List<Sys_SetData> sys_SetDatas = new List<Sys_SetData>();
                sys_SetDatas = JsonConvert.DeserializeObject<List<Sys_SetData>>(JsonConvert.SerializeObject(teamRateDatas.Data));
                List<TeamRateDescView> teamRateDescViews = new List<TeamRateDescView>();
                foreach (Sys_SetData item in sys_SetDatas) 
                {
                    teamRateDescViews.Add(new TeamRateDescView() {
                        CurrencyName = item.Remark,
                        CurrencyCode = item.Name,
                        Rate = 0.0000M
                    });
                }
                _data = new { GroupData = groups.Data, TeamRateData = teamRateDescViews };

            }
            else if (dto.PortType == 2)
            {

            }
            else if (dto.PortType == 3)
            {

            }



            result.Code = 0;
            result.Msg = "查询成功!";
            result.Data = _data;

            return result;

        }


        /// <summary>
        /// 团组汇率 更改数据
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Result> GetGroupRateChangeData()
        {

            Result result = new() { Code = -2 };

           

            string teamRateInfoSql = string.Format(@"Select * From Grp_TeamRate tr Where tr.IsDel = 0");

            var teamRateInfo = await _sqlSugar.SqlQueryable<Grp_TeamRate>(teamRateInfoSql).ToListAsync();

            dynamic _data = null;

           
            #region 团组汇率 - 详细汇率信息

            List<SetDataInfoView> otherCurrencyData1 = new List<SetDataInfoView>();
            var otherCurrencyData = await _setDataRep.GetSetDataBySTId(_setDataRep, 13);
            if (otherCurrencyData.Code == 0 && otherCurrencyData.Data != null)
            {
                string otherCurrencyStr = JsonConvert.SerializeObject(otherCurrencyData.Data);
                otherCurrencyData1 = JsonConvert.DeserializeObject<List<SetDataInfoView>>(otherCurrencyStr);
                //var otherCurrency = otherCurrencyData1
            }

            foreach (Grp_TeamRate item1 in teamRateInfo)
            {

                string rateStr = string.Empty;
                if (item1.RateU != 0) rateStr += "美元(USD):" + item1.RateU + "|";
                if (item1.RateE != 0) rateStr += "欧元(EUR):" + item1.RateE + "|";

                if (item1.RateJ != 0)
                    rateStr += "日元(JPY):" + item1.RateJ + "|";
                if (item1.RateH != 0)
                    rateStr += "港币(HKD):" + item1.RateH + "|";
                if (item1.RateN != 0)
                    rateStr += "新西兰元(NZD):" + item1.RateN + "|";
                if (item1.RateS != 0)
                    rateStr += "新加坡币(SGD):" + item1.RateS + "|";
                if (item1.RateA != 0)
                    rateStr += "澳大利亚元(AUD):" + item1.RateA + "|";
                if (item1.RateC != 0)
                    rateStr += "加拿大元(CAD):" + item1.RateC + "|";
                if (item1.RateT != 0)
                    rateStr += "泰国铢(THB):" + item1.RateT + "|";
                if (item1.RateBL != 0)
                    rateStr += "波兰兹罗提(PLN):" + item1.RateBL + "|";
                if (item1.RateHB != 0)
                    rateStr += "韩国元(KRW):" + item1.RateHB + "|";
                if (item1.RateFJD != 0)
                    rateStr += "斐济元(FJD):" + item1.RateFJD + "|";
                if (item1.RateTL != 0)
                    rateStr += "土耳其里拉(TRY):" + item1.RateTL + "|";
                if (item1.RateRP != 0)
                    rateStr += "印度尼西亚卢比(IDR):" + item1.RateRP + "|";
                if (item1.RatePeso != 0)
                    rateStr += "菲律宾比索(PHP):" + item1.RatePeso + "|";
                if (item1.RateMYR != 0)
                    rateStr += "林吉特(MYR):" + item1.RateMYR + "|";
                if (item1.RateCZK != 0)
                    rateStr += "捷克货币(CZK):" + item1.RateCZK + "|";
                if (item1.RateMXN != 0)
                    rateStr += "墨西哥比索(MXN):" + item1.RateMXN + "|";
                if (item1.RateMOP != 0)
                    rateStr += "澳门元(MOP):" + item1.RateMOP + "|";
                if (item1.RateARS != 0)
                    rateStr += "阿根廷比索(ARS):" + item1.RateARS + "|";
                if (item1.RateHUF != 0)
                    rateStr += "匈牙利福林(HUF):" + item1.RateHUF + "|";
                if (item1.RateRUB != 0)
                    rateStr += "卢布(RUB):" + item1.RateRUB + "|";


                SetDataInfoView setData = otherCurrencyData1.Where(x => x.Id == item1.OtherRateId).FirstOrDefault();
                if (setData != null)
                {
                    if (item1.OtherPrice != 0)
                        rateStr += string.Format("{0}({1}):{2}", setData.Remark, setData.Name, item1.OtherPrice);
                }
                else
                {
                    if (rateStr.Length > 0)
                    {
                        rateStr = rateStr.Substring(0, rateStr.Length - 1);
                    }
                    
                }

                item1.Remark = rateStr;

                
            }




            #endregion

            try
            {

                var _result = _sqlSugar.Updateable(teamRateInfo)
                    .UpdateColumns(it => new {it.Remark} ) //更新列
                    .WhereColumns(it => new { it.DiId,it.CTable })     //更新条件
                    .ExecuteCommand(); 

                result.Code = 0;
                result.Msg = "数据修改成功!";
                result.Data = _data;
            }
            catch (Exception ex)
            {

                result.Msg = ex.Message;
            }

            return result;

        }

        /// <summary>
        /// 团组汇率 Rep
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Result> GetGroupRateInfoByDiid(TeamRateInfoDto dto)
        {

            Result result = new() { Code = -2 };

            GroupInfoDto groupInfoDto = new GroupInfoDto() { Id = dto.Diid,PortType = dto.PortType, PageIndex = dto.PageIndex, PageSize = dto.PageSize };
            var groupInfo = await _deleInfoRep.GetGroupInfo(groupInfoDto);

            string teamRateInfoSql = string.Format(@"Select sd.Name,tr.* From Grp_TeamRate tr 
                                                     Left Join Sys_SetData  sd On sd.IsDel=0 And sd.STid=16  And tr.CTable = sd.Id 
                                                     Where tr.DiId = {0} And tr.IsDel = 0",dto.Diid);

            var teamRateInfo = await _sqlSugar.SqlQueryable<TeamRateInfoView>(teamRateInfoSql).ToListAsync();

            dynamic _data = null;

            if (dto.PortType == 1)
            {

                #region 团组汇率 - 详细汇率信息


                //List<TeamRateModelView> teamRateModels = new List<TeamRateModelView>();

                //List<SetDataInfoView> otherCurrencyData1 = new List<SetDataInfoView>();
                //var otherCurrencyData = await _setDataRep.GetSetDataBySTId(_setDataRep, 13);
                //if (otherCurrencyData.Code == 0 && otherCurrencyData.Data != null)
                //{
                //    string otherCurrencyStr = JsonConvert.SerializeObject(otherCurrencyData.Data);
                //    otherCurrencyData1 = JsonConvert.DeserializeObject<List<SetDataInfoView>>(otherCurrencyStr);
                //    //var otherCurrency = otherCurrencyData1
                //}
                //foreach (TeamRateInfoView item in teamRateInfo)
                //{
                //    TeamRateModelView teamRateModelInfo = new TeamRateModelView();
                //    foreach (TeamRateInfoView item1 in teamRateInfo)
                //    {
                //        if (item.CTable == item1.CTable)
                //        {
                //            teamRateModelInfo.CTableId = item1.CTable;
                //            teamRateModelInfo.CTableName = item1.Name;
                //            List<TeamRateDescView> teamRateDescViews = new List<TeamRateDescView>();
                //            teamRateDescViews.Add(new TeamRateDescView() { CurrencyName = "美元", CurrencyCode = "USD", Rate = item1.RateU });
                //            teamRateDescViews.Add(new TeamRateDescView() { CurrencyName = "欧元", CurrencyCode = "EUR", Rate = item1.RateE });
                //            teamRateDescViews.Add(new TeamRateDescView() { CurrencyName = "日元", CurrencyCode = "JPY", Rate = item1.RateJ });
                //            teamRateDescViews.Add(new TeamRateDescView() { CurrencyName = "港币", CurrencyCode = "HKD", Rate = item1.RateH });
                //            teamRateDescViews.Add(new TeamRateDescView() { CurrencyName = "新西兰元", CurrencyCode = "NZD", Rate = item1.RateN });
                //            teamRateDescViews.Add(new TeamRateDescView() { CurrencyName = "新加坡币", CurrencyCode = "SGD", Rate = item1.RateS });
                //            teamRateDescViews.Add(new TeamRateDescView() { CurrencyName = "澳大利亚元", CurrencyCode = "AUD", Rate = item1.RateA });
                //            teamRateDescViews.Add(new TeamRateDescView() { CurrencyName = "加拿大元", CurrencyCode = "CAD", Rate = item1.RateC });
                //            teamRateDescViews.Add(new TeamRateDescView() { CurrencyName = "泰国铢", CurrencyCode = "THB", Rate = item1.RateT });
                //            teamRateDescViews.Add(new TeamRateDescView() { CurrencyName = "波兰兹罗提", CurrencyCode = "PLN", Rate = item1.RateBL });
                //            teamRateDescViews.Add(new TeamRateDescView() { CurrencyName = "韩国元", CurrencyCode = "KRW", Rate = item1.RateHB });
                //            teamRateDescViews.Add(new TeamRateDescView() { CurrencyName = "斐济元", CurrencyCode = "FJD", Rate = item1.RateFJD });
                //            teamRateDescViews.Add(new TeamRateDescView() { CurrencyName = "土耳其里拉", CurrencyCode = "TRY", Rate = item1.RateTL });
                //            teamRateDescViews.Add(new TeamRateDescView() { CurrencyName = "印度尼西亚卢比", CurrencyCode = "IDR", Rate = item1.RateRP });
                //            teamRateDescViews.Add(new TeamRateDescView() { CurrencyName = "菲律宾比索", CurrencyCode = "PHP", Rate = item1.RatePeso });
                //            teamRateDescViews.Add(new TeamRateDescView() { CurrencyName = "林吉特", CurrencyCode = "MYR", Rate = item1.RateMYR });
                //            teamRateDescViews.Add(new TeamRateDescView() { CurrencyName = "捷克货币", CurrencyCode = "CZK", Rate = item1.RateCZK });
                //            teamRateDescViews.Add(new TeamRateDescView() { CurrencyName = "墨西哥比索", CurrencyCode = "MXN", Rate = item1.RateMXN });
                //            teamRateDescViews.Add(new TeamRateDescView() { CurrencyName = "澳门元", CurrencyCode = "MOP", Rate = item1.RateMOP });
                //            teamRateDescViews.Add(new TeamRateDescView() { CurrencyName = "阿根廷比索", CurrencyCode = "ARS", Rate = item1.RateARS });
                //            teamRateDescViews.Add(new TeamRateDescView() { CurrencyName = "匈牙利福林", CurrencyCode = "HUF", Rate = item1.RateHUF });
                //            teamRateDescViews.Add(new TeamRateDescView() { CurrencyName = "卢布", CurrencyCode = "RUB", Rate = item1.RateRUB });

                //            SetDataInfoView setData = otherCurrencyData1.Where(x => x.Id == item1.OtherRateId).FirstOrDefault();
                //            if (setData != null)
                //            {
                //                teamRateDescViews.Add(new TeamRateDescView() { CurrencyName = setData.Remark, CurrencyCode = setData.Name, Rate = item1.OtherPrice });
                //            }

                //            teamRateModelInfo.TeamRates = teamRateDescViews;



                //        }
                //    }
                //    teamRateModels.Add(teamRateModelInfo);
                //}



                #endregion

                #region 团组汇率

                List<TeamRateModelView> teamRateModels = new List<TeamRateModelView>();

                foreach (TeamRateInfoView item in teamRateInfo)
                {
                    TeamRateModelView teamRateModelInfo = new TeamRateModelView();

                    teamRateModelInfo.Id = item.Id;
                    teamRateModelInfo.CTableId = item.CTable;
                    teamRateModelInfo.CTableName = item.Name;
                    List<TeamRateDescView> teamRateDescViews = new List<TeamRateDescView>();

                    #region 拆分remark里的汇率

                    if (item.Remark.Contains("|"))
                    {
                        string[] currencyArr = item.Remark.Split("|");
                        foreach (string currency in currencyArr) 
                        {
                            string[] currency1 = currency.Split(":");
                            string[] currency2 = currency1[0].Split("(");

                            TeamRateDescView rateDescView = new TeamRateDescView() {
                                CurrencyCode = currency2[1].Replace(")", "").TrimEnd(),
                                CurrencyName = currency2[0],
                                Rate = decimal.Parse(currency1[1]),
                            };
                            teamRateDescViews.Add(rateDescView);
                        }
                    }

                    #endregion

                    teamRateModelInfo.TeamRates = teamRateDescViews;
                    teamRateModels.Add(teamRateModelInfo);
                }

                #endregion
                _data = new { GroupInfo = groupInfo.Data, TeamRateData = teamRateModels };

            }
            else if (dto.PortType == 2)
            {

            }
            else if (dto.PortType == 3)
            {

            }



            result.Code = 0;
            result.Msg = "查询成功!";
            result.Data = _data;

            return result;

        }


        /// <summary>
        /// 团组汇率 更新 or 添加
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Result> PostGroupRateUpdate(TeamRateUpdateDto dto)
        {

            Result result = new() { Code = -2 };

            
            List<Grp_TeamRate> teamRates = new List<Grp_TeamRate>();
            foreach (TeamRateUpdateInfo item in dto.teamRateUpdateInfos)
            {
                Grp_TeamRate teamRateInfo = new Grp_TeamRate();
                string currencyStr = string.Empty;
                foreach (TeamRateDescView currency in item.teamRates)
                {
                    currencyStr += string.Format(@"{0}({1}):{2}|", currency.CurrencyName, currency.CurrencyCode, currency.Rate);
                }
                if (currencyStr.Length > 0)
                {
                    currencyStr = currencyStr.Substring(0, currencyStr.Length - 1);
                }

                teamRateInfo.DiId = dto.DiId;
                teamRateInfo.CreateUserId = dto.CreateUserId;
                teamRateInfo.Id = item.Id;
                teamRateInfo.CreateTime = DateTime.Now;
                teamRateInfo.CTable = item.CTable;
                teamRateInfo.Remark = currencyStr;
                teamRates.Add(teamRateInfo);
            }


            int addCount = 0, updateCount = 0;
            if (dto.PortType == 1)
            {
                try
                {
                    var x = _sqlSugar.Storageable(teamRates).ToStorage();
                    addCount= x.AsInsertable.ExecuteCommand();        //不存在插入
                    updateCount = x.AsUpdateable.ExecuteCommand();    //存在更新
                }
                catch (Exception ex)
                {

                    result.Msg = ex.Message;
                }
                

            }
            else if (dto.PortType == 2)
            {

            }
            else if (dto.PortType == 3)
            {

            }

            result.Code = 0;
            result.Msg = string.Format(@"操作成功!添加：{0}条；更新：{1}；", addCount,updateCount);

            return result;

        }
    }
}
