
using AutoMapper;
using OASystem.Domain;
using OASystem.Domain.Dtos.Groups;
using OASystem.Domain.Entities.Groups;
using OASystem.Domain.ViewModels.Groups;
using OASystem.Infrastructure.Repositories.System;
using OASystem.Infrastructure.Tools;
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 EnterExitCostRepository:BaseRepository<Grp_EnterExitCost, EnterExitCostView>
    {
        private readonly IMapper _mapper;
        private readonly SetDataRepository _setDataRep;


        public EnterExitCostRepository(SqlSugarClient sqlSugar, IMapper mapper, SetDataRepository setDataRep)
            :base(sqlSugar) 
        {
            _setDataRep = setDataRep;
            _mapper = mapper;
        }

        /// <summary>
        /// 更新出入境费用汇率信息
        /// </summary>
        /// <returns></returns>
        public async Task<Result> SetEnterExitCostCurrencyChange()
        {
            Result result = new Result { Code = -1, Msg = "未知错误" };

            var enterExitList = await _sqlSugar.Queryable<Grp_EnterExitCost>().ToListAsync();

            foreach (var item in enterExitList)
            {
                string rateStr = string.Format(@"美元(USD):{0}|日元(JPY):{1}|欧元(EUR):{2}|英镑(GBP):{3}|港币(HKD):{4}", item.RateUSD,item.RateJPY,item.RateEUR,item.RateGBP,item.RateHKD);
                item.CurrencyRemark = rateStr;
            }

            var res = await _sqlSugar.Updateable(enterExitList)
                .WhereColumns(it => new { it.Id })
                .UpdateColumns(it => new { it.CurrencyRemark })
                .ExecuteCommandAsync();

            if (res > 0) 
            {
                result.Code = 0;
                result.Msg = res.ToString();
                return result;
            }

            return result;
        }

        
        /// <summary>
        /// 查询 根据 Diid 查询
        /// </summary>
        /// <returns></returns>
        public async Task<Result> GetEnterExitCostInfoByDiId(EnterExitCostInfobyDiIdDto dto)
        {
            Result result = new Result();

            var enterExitCostData = await _sqlSugar.Queryable<Grp_EnterExitCost>().FirstAsync(it => it.DiId == dto.DiId && it.IsDel == 0);

            //Sys_PageFunctionPermission Function = _mapper.Map<Sys_PageFunctionPermission>(dto);

            EnterExitCostInfoView enterExitCostInfoView = new EnterExitCostInfoView();

            if (dto.PortType == 1) // Web
            {
                if (enterExitCostData != null)
                {
                    enterExitCostInfoView = _mapper.Map<EnterExitCostInfoView>(enterExitCostData);

                    var dayAndCostSql = string.Format(@"Select ntf.Country,ntf.City,ssd.Name CurremcyCode,ssd.Remark CurrencyName,gdac.* From Grp_DayAndCost gdac
                                                        Left Join Grp_NationalTravelFee ntf On ntf.Id = gdac.NationalTravelFeeId
                                                        Left Join Sys_SetData ssd On ssd.STid = 66 And gdac.Currency = ssd.Id
                                                        Where gdac.Isdel = 0 And gdac.DiId = {0} Order By [Type] ASC,[Days] ASC", dto.DiId);
                    var dayAndCostData = await _sqlSugar.SqlQueryable<DayAndCostInfoView>(dayAndCostSql).ToListAsync();


                    enterExitCostInfoView.QuarterageData = dayAndCostData.Where(it => it.Type == 1).ToList(); //住宿费 1
                    enterExitCostInfoView.BoardWagesData = dayAndCostData.Where(it => it.Type == 2).ToList(); //伙食费 2
                    enterExitCostInfoView.MiscellaneousFeeData = dayAndCostData.Where(it => it.Type == 3).ToList();  //公杂费 3
                    enterExitCostInfoView.TrainingExpenseData = dayAndCostData.Where(it => it.Type == 4).ToList();  //培训费 4

                    enterExitCostInfoView.Currencys = (List<CurrencyInfo>?)CommonFun.GetCurrencyChinaToList(enterExitCostData.CurrencyRemark);

                    result.Msg = "查询成功";
                    result.Code = 0;
                }
                else
                {
                    result.Msg = "未查询出数据!!!";
                }

                result.Data = enterExitCostInfoView;
            }
            else result.Msg = ErrorMsg.Error_Port_Msg;

            

            return result;
        }

        /// <summary>
        /// Add Or Update
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Result> PostEnterExitCostOperate(EnterExitCostOperateDto dto)
        { 
            Result result = new Result() { Code =-1,Msg="操作失败!" };

            var enterExitCost = _mapper.Map<Grp_EnterExitCost>(dto);
            var quarterageData = _mapper.Map<List<Grp_DayAndCost>>(dto.QuarterageData);  //住宿费 1
            quarterageData = quarterageData.Select(it => { it.CreateUserId = dto.UserId; return it; }).ToList();

            var boardWagesData = _mapper.Map<List<Grp_DayAndCost>>(dto.BoardWagesData);  //伙食费 2
            boardWagesData = boardWagesData.Select(it => { it.CreateUserId = dto.UserId; return it; }).ToList();

            var miscellaneousFeeData = _mapper.Map<List<Grp_DayAndCost>>(dto.MiscellaneousFeeData);  //公杂费 3
            miscellaneousFeeData = miscellaneousFeeData.Select(it => { it.CreateUserId = dto.UserId; return it; }).ToList();

            var trainingExpenseData = _mapper.Map<List<Grp_DayAndCost>>(dto.TrainingExpenseData);    //培训费 4
            trainingExpenseData = trainingExpenseData.Select(it => { it.CreateUserId = dto.UserId; return it; }).ToList();


            //处理币种string
            enterExitCost.CurrencyRemark = CommonFun.GetCurrencyChinaToString(dto.Currencys);
            enterExitCost.CreateUserId = dto.UserId;

            _sqlSugar.BeginTran();

            if (dto.PortType == 1)
            {
                try
                {
                    var enterExit = _sqlSugar.Storageable<Grp_EnterExitCost>(enterExitCost).ToStorage();
                    enterExit.AsInsertable.ExecuteCommand();   //不存在插入
                    enterExit.AsUpdateable.IgnoreColumns(it => new { it.DiId, it.CreateUserId, it.CreateTime, it.IsDel }).ExecuteCommand();   //存在更新

                    var quarterage = _sqlSugar.Storageable<Grp_DayAndCost>(quarterageData).ToStorage();  //住宿费 1
                    quarterage.AsInsertable.ExecuteCommand();   //不存在插入                             
                    quarterage.AsUpdateable.IgnoreColumns(it => new { it.DiId, it.Type, it.CreateUserId, it.CreateTime, it.IsDel }).ExecuteCommand();   //存在更新

                    var boardWages = _sqlSugar.Storageable<Grp_DayAndCost>(boardWagesData).ToStorage();  //伙食费 2
                    boardWages.AsInsertable.ExecuteCommand();   //不存在插入
                    boardWages.AsUpdateable.IgnoreColumns(it => new { it.DiId, it.Type, it.CreateUserId, it.CreateTime, it.IsDel }).ExecuteCommand();   //存在更新

                    var miscellaneousFee = _sqlSugar.Storageable<Grp_DayAndCost>(miscellaneousFeeData).ToStorage(); //公杂费 3
                    miscellaneousFee.AsInsertable.ExecuteCommand();   //不存在插入
                    miscellaneousFee.AsUpdateable.IgnoreColumns(it => new { it.DiId, it.Type, it.CreateUserId, it.CreateTime, it.IsDel }).ExecuteCommand();   //存在更新

                    var trainingExpense = _sqlSugar.Storageable<Grp_DayAndCost>(trainingExpenseData).ToStorage();    //培训费 4
                    trainingExpense.AsInsertable.ExecuteCommand();   //不存在插入
                    trainingExpense.AsUpdateable.IgnoreColumns(it => new { it.DiId, it.Type, it.CreateUserId, it.CreateTime, it.IsDel }).ExecuteCommand();   //存在更新

                    _sqlSugar.CommitTran();
                    result.Code = 0;
                    result.Msg = "操作成功!";
                }
                catch (Exception ex)
                {
                    _sqlSugar.RollbackTran();
                    result.Msg = ex.Message;
                }
            }
            else result.Msg = ErrorMsg.Error_Port_Msg;

            return result;
        }

        /// <summary>
        /// Del
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Result> PostEnterExitCostSubItemDel(EnterExitCostSubItemDelDto dto)
        {
            Result result = new Result();


            var del = await _sqlSugar.Updateable<Grp_DayAndCost>()
                .SetColumns(it => new Grp_DayAndCost()
                {
                    IsDel = 1,
                    DeleteUserId = dto.DeleteUserId,
                    DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")
                })
                .Where(it => it.Id == dto.Id)
                .ExecuteCommandAsync();

            if (del > 0) result.Code = 0;
            else result.Msg = string.Format("删除失败!");

            return result;
        }

        /// <summary>
        /// 团组模块 - 出入境国家费用标准 - Add Or Update
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Result> PostNationalTravelFeeOperate(NationalTravelFeeOperateDto dto)
        {
            Result result = new Result();

            Grp_NationalTravelFee nationalTravelFee = _mapper.Map<Grp_NationalTravelFee>(dto);
            nationalTravelFee.LastUpdateUserId = dto.UserId;
            nationalTravelFee.CreateUserId = dto.UserId;

            if (dto.PortType == 1) //web
            {

                var _nationalTravelFee = _sqlSugar.Storageable<Grp_NationalTravelFee>(nationalTravelFee).ToStorage();
                if (dto.Id == 0) //新增
                {
                    string selectSql = string.Format(@"Select * From Grp_NationalTravelFee 
                                                   Where IsDel = 0 
                                                   And Continent = '{0}' 
                                                   And Country = '{1}'
                                                   And City = '{2}'", dto.Continent, dto.Country, dto.City);
                    Grp_NationalTravelFee nationalTravelFee1 = new Grp_NationalTravelFee();
                    nationalTravelFee1 = await _sqlSugar.SqlQueryable<Grp_NationalTravelFee>(selectSql).FirstAsync();
                    if (nationalTravelFee1 != null)
                    {
                        result.Msg = "该国家 城市已存在,请勿重复添加!";
                        return result;
                    }

                    _nationalTravelFee.AsInsertable.ExecuteCommand();   //不存在插入
                }
                else
                {
                    _nationalTravelFee.AsUpdateable
                    .IgnoreColumns(it => new { it.CreateUserId, it.CreateTime, it.IsDel })
                    .WhereColumns(it => it.Id)
                    .ExecuteCommand();   //存在更新
                }

                result.Code = 0;
            }
            else if (dto.PortType == 2) //Android
            {

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

            }
            else result.Msg = ErrorMsg.Error_Port_Msg;





            return result;
        }
    }
}
