using AutoMapper;
using MySqlX.XDevAPI.Common;
using OASystem.Domain;
using OASystem.Domain.Dtos.Groups;
using OASystem.Domain.Entities.Groups;
using OASystem.Domain.Entities.Resource;
using OASystem.Domain.ViewModels.Groups;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Result = OASystem.Domain.Result;

namespace OASystem.Infrastructure.Repositories.Groups
{
    /// <summary>
    /// 倒推表 仓储
    /// </summary>
    public class InvertedListRepository:BaseRepository<Grp_InvertedList,InvertedListView>
    {
        private readonly IMapper _mapper;
        private readonly Result _result;
        private readonly DelegationInfoRepository _delegationInfoRep;
        public InvertedListRepository(SqlSugarClient sqlSugar, IMapper mapper, DelegationInfoRepository delegationInfoRep)
            : base(sqlSugar)
        {
            _mapper = mapper;
            _result = new Result() { Code = -1, Msg = "系统错误！", Data = new List<object>() { } };
            _delegationInfoRep = delegationInfoRep;
        }

        /// <summary>
        /// 基础数据
        /// </summary>
        /// <returns></returns>
        public async Task<Result> _Init()
        {
            dynamic groupData = null;
            var groupData1 = await _delegationInfoRep.PostShareGroupInfos(1);
            if (groupData1.Code == 0)
            {
                groupData = groupData1.Data;
            }

            var setData  = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();

            var officialTypeData = setData.Where(it => it.STid  == 81).Select(it => new { it.Id,it.Name }).ToList();

            var visaTypeData = setData.Where(it => it.STid == 82).Select(it => new { it.Id, it.Name }).ToList();

            _result.Code = 0;
            _result.Msg = "操作成功!";
            _result.Data = new {
                groupData = groupData,
                officialTypeData = officialTypeData,
                visaTypeData = visaTypeData
            };

            return _result;
        }

        /// <summary>
        /// Info
        /// </summary>
        /// <returns></returns>
        public async Task<Result> _Info(int portTypeId,int diId)
        {
            #region 参数验证
            if (portTypeId < 1)
            {
                _result.Msg = "请输入有效的PortType参数值";
                return _result;
            }
            if (diId < 1)
            {
                _result.Msg = "请输入有效的DiId参数值";
                return _result;
            }

            #endregion
            string sql = string.Format(@$"Select * From Grp_InvertedList Where Isdel={0} And DiId = {diId}");
            var info = await _sqlSugar.SqlQueryable<InvertedListInfoView>(sql).FirstAsync();

            if (info == null) {

                info = new InvertedListInfoView();
                info.IsQuery = true;

                var groupInfo = await _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0 && it.Id == diId).FirstAsync();
                if (groupInfo == null)
                {
                    _result.Msg = @$"团组数据不存在!";
                    return _result;
                }

                List<string> visitCountry = new List<string>();

                string grpVisitCountry = groupInfo.VisitCountry;

                if (!string.IsNullOrEmpty(grpVisitCountry))
                {
                    grpVisitCountry = _delegationInfoRep.FormartTeamName(grpVisitCountry);

                    visitCountry = grpVisitCountry.Split("、").ToList();
                }

                string sqqzRemark = "";

                //签证费用标准
                var visaFeeDatas = await _sqlSugar.Queryable<Res_CountryFeeCost>().Where(it => it.IsDel == 0).ToListAsync();
                List<VisaCountryInfo> visaCountryInfos = new List<VisaCountryInfo>();

                string countryStr = "";
                string countryDesc = "";
                foreach (var item in visitCountry)
                {

                    int visaDays = Convert.ToInt32(visaFeeDatas.Find(it => it.VisaCountry.Equals(item.Trim()))?.VisaTime ?? "0");
                    visaCountryInfos.Add(new VisaCountryInfo()
                    {
                        Country = item,
                        OfficialTypeId = -1,
                        VisaTypeId = -1,
                        VisaDay = visaDays
                    });

                    countryStr += $"{item}、";
                    countryDesc += $"{item}签证{visaDays}个工作日,";
                }

                if (countryStr.Length > 0)
                {
                    countryStr = countryStr.Substring(0, countryStr.Length - 1);
                }

                if (countryDesc.Length > 0)
                {
                    countryDesc = countryDesc.Substring(0, countryDesc.Length - 1);
                }

                sqqzRemark = $"申请{countryStr}签证;{countryDesc}\r\n（签证周期仅供参考）";

                info.VisaCountryData = visaCountryInfos;
                info.SendVisaRemark = sqqzRemark;
                _result.Data = info;
                _result.Msg = "未查询到数据!";
                _result.Code = 0;
                return _result; 
            }

           

            int ilId = info.Id;

            string visaSql = string.Format(@$"Select * From Grp_InvertedListVisaCountry Where Isdel={0} And ILId = {ilId}");
            var visaCountryInfo = await _sqlSugar.SqlQueryable<VisaCountryInfo>(visaSql).ToListAsync();

            info.VisaCountryData = visaCountryInfo;
            _result.Data = info;
            _result.Code = 0;

            return _result;
        }

        /// <summary>
        /// Create
        /// </summary>
        /// <param name="diId"></param>
        /// <returns></returns>
        public async Task<Result> _Create(int userId,int diId)
        {
            #region 参数验证
            if (diId < 1)
            {
                _result.Msg = $@"请输入有效的DiId参数值!";
                return _result;
            }
            if (userId < 1)
            {
                _result.Msg = $@"请输入有效的UserId参数值!";
                return _result;
            }
            #endregion

            var selectInfo = await _sqlSugar.Queryable<Grp_InvertedList>().Where(it => it.IsDel == 0 && it.DiId == diId).FirstAsync();
            if (selectInfo != null)
            {
                _result.Msg = @$"该数据已存在，不可重复创建!";
                return _result;
            }

            var groupInfo = await _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0 && it.Id == diId).FirstAsync();
            if (groupInfo == null)
            {
                _result.Msg = @$"团组数据不存在，不可创建!";
                return _result;
            }

            if (string.IsNullOrEmpty( groupInfo.VisitDate.ToString()))
            {
                _result.Msg = @$"团组出访时间未填写，不可创建!";
                return _result;
            }

            DateTime visitDt = groupInfo.VisitDate;

            List<string> visitCountry = new List<string>();

            string grpVisitCountry  = groupInfo.VisitCountry;

            if (!string.IsNullOrEmpty(grpVisitCountry))
            {
                grpVisitCountry = _delegationInfoRep.FormartTeamName(grpVisitCountry);

                visitCountry = grpVisitCountry.Split("、").ToList();
            }

            //签证费用标准
            var visaFeeDatas = await _sqlSugar.Queryable<Res_CountryFeeCost>().Where(it => it.IsDel == 0).ToListAsync();

            string sqqzRemark = "";

            List<VisaCountryInfo> visaCountryInfos = new List<VisaCountryInfo>();

            string countryStr = "";
            string countryDesc = "";
            foreach (var item in visitCountry)
            {

                int visaDays = Convert.ToInt32(visaFeeDatas.Find(it => it.VisaCountry.Equals(item.Trim()))?.VisaTime ?? "0");
                visaCountryInfos.Add(new VisaCountryInfo()
                {
                    Country = item,
                    OfficialTypeId = -1,
                    VisaTypeId = -1,
                    VisaDay = visaDays
                });

                countryStr += $"{item}、";
                countryDesc += $"{item}签证{visaDays}个工作日,";
            }

            if (countryStr.Length > 0)
            {
                countryStr = countryStr.Substring(0, countryStr.Length - 1);
            }

            if (countryDesc.Length > 0)
            {
                countryDesc = countryDesc.Substring(0, countryDesc.Length - 1);
            }

            sqqzRemark = $"申请{countryStr}签证;{countryDesc}\r\n（签证周期仅供参考）";


            /*
             * 默认步骤所需提前天数
             * A 自然日 B 工作日
             */
            int approvalData_advanceDays = -60,     //报批资料准备
                approval_advanceDays = -45,         //报批
                IssueApproval_advanceDays = -33,    //出批件、办护照
                                                    //ApplyPassport_advanceDays = -30,    //办护照
                VisaInformation_advanceDays = -16,  //签证资料准备
                sendVisa_advanceDays = -12,         //送签
                issueVisa_advanceDays = -5,         //出签
                preTripMeeting_advanceDays = -3,    //行前会
                airportdDropOff_advanceDays = 0;   //送机

            var info = new Grp_InvertedList() { 
                DiId = diId,
                ApprovalDataDt = visitDt.AddDays(approvalData_advanceDays).ToString("yyyy-MM-dd"),
                ApprovalDt = visitDt.AddDays(approval_advanceDays).ToString("yyyy-MM-dd"),
                ApprovalType = -1,
                IssueApprovalDt = visitDt.AddDays(IssueApproval_advanceDays).ToString("yyyy-MM-dd"),
                //ApplyPassportDt = visitDt.AddDays(ApplyPassport_advanceDays).ToString("yyyy-MM-dd"),
                VisaInformationDt = visitDt.AddDays(VisaInformation_advanceDays).ToString("yyyy-MM-dd"),
                SendVisaDt = visitDt.AddDays(sendVisa_advanceDays).ToString("yyyy-MM-dd"),
                IssueVisaDt = visitDt.AddDays(issueVisa_advanceDays).ToString("yyyy-MM-dd"),
                PreTripMeetingDt = visitDt.AddDays(preTripMeeting_advanceDays).ToString("yyyy-MM-dd"),
                AirportdDropOffDt = visitDt.AddDays(airportdDropOff_advanceDays).ToString("yyyy-MM-dd"),
                CreateUserId = userId,
            };

            if (!string.IsNullOrEmpty(sqqzRemark)) info.SendVisaRemark = sqqzRemark;

            _sqlSugar.BeginTran();

            int add1 = await _sqlSugar.Insertable<Grp_InvertedList>(info).ExecuteReturnIdentityAsync();
            if (add1<1)
            {
                _result.Msg = $@"倒推表添加失败!";
                _sqlSugar.RollbackTran();
                return _result;
            }

            List<Grp_InvertedListVisaCountry> _InvertedListVisaCountries = new List<Grp_InvertedListVisaCountry>();
            foreach (var item in visitCountry)
            {
                int days = Convert.ToInt32(visaFeeDatas.Find(x => x.VisaCountry.Equals(item.Trim()))?.VisaTime ?? "0");
                
                _InvertedListVisaCountries.Add(new Grp_InvertedListVisaCountry()
                {
                    ILId = add1,
                    Country = item,
                    OfficialTypeId = -1,
                    VisaTypeId = -1,
                    VisaDay = days,
                });
            }

            int add2 = await _sqlSugar.Insertable<Grp_InvertedListVisaCountry>(_InvertedListVisaCountries).ExecuteReturnIdentityAsync();

            _sqlSugar.CommitTran();
            _result.Code = 0;
            _result.Msg = @$"操作成功!";
            return _result;
        }

        /// <summary>
        /// Update
        /// </summary>
        /// <param name="diId"></param>
        /// <returns></returns>
        public async Task<Result> _Update(InvertedListUpdateDto dto)
        {
            #region 参数验证
            if (dto.DiId < 1)
            {
                _result.Msg = $@"请输入有效的DiId参数值!";
                return _result;
            }
            if (dto.Id < 1)
            {
                _result.Msg = $@"请输入有效的Id参数值!";
                return _result;
            }
            #endregion

            Grp_InvertedList _InvertedList = _mapper.Map<Grp_InvertedList>(dto);
            List<Grp_InvertedListVisaCountry> _InvertedListVisaCountries = new List<Grp_InvertedListVisaCountry>();
            if (dto.VisaCountryData.Count > 0)
            {
                _InvertedListVisaCountries = _mapper.Map<List<Grp_InvertedListVisaCountry>>(dto.VisaCountryData);
            }
            _sqlSugar.BeginTran();

            int update1 = await _sqlSugar.Updateable(_InvertedList)
                                         .IgnoreColumns(it => new { it.CreateTime,it.IsDel })
                                         .ExecuteCommandAsync();
            if (update1 < 1) 
            {
                _sqlSugar.RollbackTran();
                _result.Msg = @$"修改失败!";
                return _result;

            }

            if (_InvertedListVisaCountries.Count > 0)
            {
                int update2 = await _sqlSugar.Updateable(_InvertedListVisaCountries)
                                         .IgnoreColumns(it => new { it.CreateTime, it.IsDel })
                                         .ExecuteCommandAsync();

                if (update2 < 1)
                {
                    _sqlSugar.RollbackTran();
                    _result.Msg = @$"修改失败!";
                    return _result;
                }
            }

            _sqlSugar.CommitTran();
            _result.Code = 0;
            _result.Msg = @$"操作成功!";
            return _result;
        }
    
    
    }
}
