using OASystem.Domain;
using OASystem.Domain.Entities.Groups;
using OASystem.Domain.Entities.Resource;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OASystem.Infrastructure.Repositories.Groups
{
    public class GroupCostRepository:BaseRepository<Grp_GroupCost, GroupCostView>
    {
        public GroupCostRepository(SqlSugarClient sqlSugar) : base(sqlSugar)
        {}

        public List<Grp_GroupCost> GetAllByDiid(int diid)
        {
            return Query(x => x.Diid == diid).ToList();
        }

        public List<Grp_GroupCost> GetAll()
        {
            return Query(x=> x.IsDel < 1).ToList();
        }

        public async Task<bool> SaveGroupCostList(List<Grp_GroupCost> costList,int diid, int userid)
        {
            BeginTran();
            //注释删除
            //bool isTrue = await DeleteGroupCostList(diid);
            bool isTrue = await UpdateAsync(x => x.Diid == diid && x.IsDel == 0, x => new Grp_GroupCost
            {
                IsDel = 1,
                DeleteUserId = userid,
                DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            }) ;
            if (costList.Count > 0)
            {
                isTrue = Adds(costList) > 0;
            }
            if (isTrue)
            {
                CommitTran();
            }
            else
            {
                RollbackTran();
            }

            return isTrue; 
        }


        public Task<bool> DeleteGroupCostList(int diid)
        {
            return  DeleteAsync(x => x.Diid == diid);
        }

        public Result CreateGroupCostByBlackCode(int diid)
        {
            Result rt = new Result();
            List<Grp_GroupCost> returnArr = new List<Grp_GroupCost>();
            DataTable resultTable = null;
            try
            {
                resultTable = GetTableByBlackCode(diid);
                if (resultTable.Rows.Count == 0 || string.IsNullOrWhiteSpace(resultTable.Rows[0][1].ToString()))
                {
                    string msg = string.Empty;
                    if (resultTable.Rows.Count > 0)
                    {
                        msg = resultTable.Rows[0]["Error"].ToString();
                    }

                    rt.Msg = "黑屏代码有误! " + msg;
                    rt.Data = returnArr;
                    rt.Code = -1;
                }
                else
                {
                    var timeArr = GetTimeListByDataTable(resultTable);
                    var dayIndex = 1;
                    var stopCity = string.Empty;
                    foreach (var item in timeArr)
                    {
                        var tabSelect = resultTable.Select(string.Format("Day = '{0}'", item));
                        var itin = string.Empty;
                        if (tabSelect.Length > 0)
                        {
                            var threeCodeValue = new List<string>(4);
                            foreach (var tabRow in tabSelect)
                            {
                                var threeCode = tabRow["Three"].ToString();
                                var start = threeCode.Substring(0, 3);
                                var end = threeCode.Substring(3, 3);
                                stopCity = end;
                                if (start == stopCity)
                                {
                                    threeCodeValue.Add(end);
                                }
                                else
                                {
                                    threeCodeValue.Add(start);
                                    threeCodeValue.Add(end);
                                }

                                itin = $@"{threeCodeValue[0]}/{threeCodeValue[threeCodeValue.Count - 1]}
{tabRow["Fliagtcode"].ToString()}
{tabRow["StartTime"].ToString()}/{tabRow["EndTime"].ToString()}";


                            }
                        }
                        else
                        {
                            itin = stopCity;
                        }

                        Grp_GroupCost ggc = new Grp_GroupCost();
                        ggc.DAY = dayIndex.ToString();
                        ggc.Date = item;
                        ggc.ITIN = itin;
                        ggc.Diid = diid;
                        returnArr.Add(ggc);

                        dayIndex++;
                    }

                    rt.Data = returnArr;
                    if (returnArr.Count > 0)
                    {
                        rt.Code = 0;
                        rt.Msg = "生成成功！";
                    }
                    else
                    {
                        rt.Code = -1;
                        rt.Msg = "生成失败！" + "请检查机票黑屏代码！";
                    }
                }
            }
            catch (Exception ex)
            {
                rt.Code = -1;
                rt.Msg = ex.Message;
                rt.Data = ex.StackTrace;
            }

            return rt;
        }


        /// <summary>
        ///根据机票黑屏代码整理DataTable
        /// </summary>
        /// <param name="diid"></param>
        /// <returns></returns>
        public DataTable GetTableByBlackCode(int diid)
        {
            string[] excludeArr = new string[] { "[中转]", "[转机]" };
            //黑屏代码信息
            List<Air_TicketBlackCode> listcode = _sqlSugar.Queryable<Air_TicketBlackCode>().Where(x => x.DiId == diid && x.IsDel == 0).ToList();

            //测试数据为序号,航班号,起飞日期,三字码,起飞时刻,到达时刻,出发航站楼,到达航站楼,机型,飞行时间
            //1.3U8391   TU17NOV CTUCAI  0220 0715   T1 T2  330  10H55M
            DataTable dt = new DataTable();
            dt.Columns.Add("Fliagtcode", typeof(string)); //航班号
            dt.Columns.Add("Date", typeof(string));//起飞日期
            dt.Columns.Add("Three", typeof(string));//三字码
            dt.Columns.Add("StartTime", typeof(string));//起飞时刻
            dt.Columns.Add("EndTime", typeof(string));//到达时刻
            dt.Columns.Add("StartBuilding", typeof(string));//出发航站楼
            dt.Columns.Add("EndBuilding", typeof(string));//到达航站楼
            dt.Columns.Add("AirModel", typeof(string)); //机型
            dt.Columns.Add("FlightTime", typeof(string));//飞行时间
            dt.Columns.Add("Day", typeof(string));//整理的起飞日期;作为排序依据 
            dt.Columns.Add("ArrivedDate", typeof(string));//整理的到达日期
            dt.Columns.Add("Error", typeof(string));//整理的到达日期
            dt.Columns.Add("Sign", typeof(string));//标识：0表示为原生黑屏代码、1表示“+1”新增的黑屏代码

            //添加转机标识
            dt.Columns.Add("isTransitShipment", typeof(bool));

            //判断是否录入黑屏代码
            if (listcode.Count() == 0 || listcode == null)
            {
                dt.Rows.Add(null, null, null, null, null, null, null, null, null, null, null, "黑屏代码未录入!", null, false);
            }
            else
            {
                //读取单段黑屏代码
                for (int i = 0; i < listcode.Count; i++)
                {
                    //去除序号
                    string[] CodeList = Regex.Split(listcode[i].BlackCode, "\\d+\\.", RegexOptions.IgnoreCase);
                    //去除多余空格，方法一Linq扩展方法
                    CodeList = CodeList.Where(str => !string.IsNullOrWhiteSpace(str)).ToArray();

                    //读取单条黑屏代码
                    for (int j = 0; j < CodeList.Count(); j++)
                    {
                        //去除多余空格，方法二使用Split()方法进行分割,分割有一个选项是RemoveEmptyEntries
                        CodeList[j] = CodeList[j].Replace("\r\n", string.Empty).Replace("\\r\\n", string.Empty).TrimStart().TrimEnd();
                        string[] Info = CodeList[j].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                        //去除多余空格
                        Info = Info.Where(str => !string.IsNullOrWhiteSpace(str)).ToArray();

                        //判断黑屏代码是否正确拆分; 理应拆成9段
                        if (Info.TakeWhile((x) =>
                        {
                            return !excludeArr.Contains(x);
                        }).Count() != 9)
                        {
                            dt.Rows.Add(null, null, null, null, null, null, null, null, null, null, null, "本团组第" + (i + 1) + "段黑屏代码中第" + (j + 1) + " 条有误,请联系机票同事核对", null, false);
                            //MessageBoxEx.Show("第" + (i + 1) + "段黑屏代码中第" + (j + 1) + " 条有误, 请联系机票同事核对");
                            return dt;
                        }
                        else
                        {
                            try
                            {
                                var monthEn = Info[1].Substring(4, 3);

                                //月                  
                                int month = Convert.ToInt32(GetLonger(monthEn));
                                //日
                                int day = Convert.ToInt32(Info[1].Substring(2, 2));

                                var time = new DateTime(DateTime.Now.Year, month, day); //

                                var isExist = Info.Contains("[中转]");
                                if (!isExist)
                                {
                                    isExist = Info.Contains("[转机]");
                                }

                                //dt.Columns.Add("Fliagtcode", typeof(string)); //航班号
                                //dt.Columns.Add("Date", typeof(string));//起飞日期
                                //dt.Columns.Add("Three", typeof(string));//三字码
                                //dt.Columns.Add("StartTime", typeof(string));//起飞时刻
                                //dt.Columns.Add("EndTime", typeof(string));//到达时刻
                                //dt.Columns.Add("StartBuilding", typeof(string));//出发航站楼
                                //dt.Columns.Add("EndBuilding", typeof(string));//到达航站楼
                                //dt.Columns.Add("AirModel", typeof(string)); //机型
                                //dt.Columns.Add("FlightTime", typeof(string));//飞行时间
                                //dt.Columns.Add("Day", typeof(string));//整理的起飞日期;作为排序依据 
                                //dt.Columns.Add("ArrivedDate", typeof(string));//整理的到达日期
                                //dt.Columns.Add("Error", typeof(string));//整理的到达日期
                                //dt.Columns.Add("Sign", typeof(string));//标识：0表示为原生黑屏代码、1表示“+1”新增的黑屏代码
                                dt.Rows.Add(Info[0],
                                       Info[1],
                                       Info[2],
                                       Info[3],
                                       Info[4],
                                       Info[5],
                                       Info[6],
                                       Info[7],
                                       Info[8],
                                       time.ToString("yyyy-MM-dd"),
                                       time.ToString("yyyy-MM-dd"),
                                       "",
                                       "0",
                                       isExist
                                       );

                            }
                            catch (Exception ex)
                            {
                                string exstr = ex.Message.ToString();
                            }
                        }

                    }

                    //排序
                    dt.DefaultView.Sort = "Day asc";
                    dt = dt.DefaultView.ToTable();
                }
            }

            return dt;
        }

        public string GetLonger(string temp)
        {
            string str = "";
            switch (temp.ToUpper())
            {
                case "美元":
                    str = "USD";
                    break;
                case "日元":
                    str = "JPY";
                    break;
                case "英镑":
                    str = "GBP";
                    break;
                case "欧元":
                    str = "EUR";
                    break;
                case "港币":
                    str = "HKD";
                    break;
                case "MO":
                    str = "星期一";
                    break;
                case "TU":
                    str = "星期二";
                    break;
                case "WE":
                    str = "星期三";
                    break;
                case "TH":
                    str = "星期四";
                    break;
                case "FR":
                    str = "星期五";
                    break;
                case "SA":
                    str = "星期六";
                    break;
                case "SU":
                    str = "星期天";
                    break;
                case "JAN":
                    str = "01";
                    break;
                case "FEB":
                    str = "02";
                    break;
                case "MAR":
                    str = "03";
                    break;
                case "APR":
                    str = "04";
                    break;
                case "MAY":
                    str = "05";
                    break;
                case "JUN":
                    str = "06";
                    break;
                case "JUL":
                    str = "07";
                    break;
                case "AUG":
                    str = "08";
                    break;
                case "SEP":
                    str = "09";
                    break;
                case "OCT":
                    str = "10";
                    break;
                case "NOV":
                    str = "11";
                    break;
                case "DEC":
                    str = "12";
                    break;
                case "MONDAY":
                    str = "星期一";
                    break;
                case "TUESDAY":
                    str = "星期二";
                    break;
                case "WEDNESDAY":
                    str = "星期三";
                    break;
                case "THURSDAY":
                    str = "星期四";
                    break;
                case "FRIDAY":
                    str = "星期五";
                    break;
                case "SATURDAY":
                    str = "星期六";
                    break;
                case "SUNDAY":
                    str = "星期日";
                    break;
                case "01":
                    str = "JAN";
                    break;
                case "02":
                    str = "FEB";
                    break;
                case "03":
                    str = "MAR";
                    break;
                case "04":
                    str = "APR";
                    break;
                case "05":
                    str = "MAY";
                    break;
                case "06":
                    str = "JUN";
                    break;
                case "07":
                    str = "JUL";
                    break;
                case "08":
                    str = "AUG";
                    break;
                case "09":
                    str = "SEP";
                    break;
                case "10":
                    str = "OCT";
                    break;
                case "11":
                    str = "NOV";
                    break;
                case "12":
                    str = "DEC";
                    break;
                case "2":
                    str = "空客A";
                    break;
                case "3":
                    str = "空客A";
                    break;
                case "7":
                    str = "波音";
                    break;
            }

            return str;
        }

        public List<string> GetTimeListByDataTable(DataTable dt)
        {
            DateTime datestart = Convert.ToDateTime(dt.Rows[0]["Day"].ToString());
            DateTime dateend = Convert.ToDateTime(dt.Rows[dt.Rows.Count - 1]["ArrivedDate"].ToString());

            List<string> timeList = new List<string>();
            while (datestart <= dateend)
            {
                timeList.Add(datestart.ToString("yyyy-MM-dd"));
                datestart = datestart.AddDays(1);
            }
            return timeList;
        }
    }
}
