using DocumentFormat.OpenXml.EMMA;
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Wordprocessing;
using Infrastructure;
using NetTaste;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.Config;
using OpenAuth.App.Interface;
using OpenAuth.App.Response;
using OpenAuth.App.ServiceApp.FireManagement.Response;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain.FireManagement;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OpenAuth.App.ServiceApp.FireManagement
{
    public class FirePatrolApp : SqlSugarBaseApp<FmUserTimeSlot, SugarDbContext>
    {
        public FirePatrolApp(ISugarUnitOfWork<SugarDbContext> unitWork,
        ISimpleClient<FmUserTimeSlot> repository, IAuth auth) : base(unitWork, repository, auth)
        {
            _auth = auth;
        }
        /// <summary>
        /// 巡查轨迹
        /// </summary>
        /// <param name="id"></param>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public async Task<Response<List<UserPatrolInfoResp>>> GetPatrolInfoByUserId(long id, DateTime beginTime, DateTime endTime)
        {
            using (SugarDbContext db = base.UnitWork.CreateContext())
            {
                var usertime = await db.FmUserTimeSlot.AsQueryable().Where(a => a.CreateId == id).ToListAsync();
                var user = await db.User.GetFirstAsync(r => r.Id == id);

                if (user != null)
                {
                    TimeSpan timeSpan = endTime.AddDays(1).Subtract(beginTime);
                    int days = (int)timeSpan.TotalDays;
                    List<UserPatrolInfoResp> upinfo = new List<UserPatrolInfoResp>();
                    var userpoint = await db.FmUserPointHistory.AsQueryable().Where(a => a.CreateTime >= beginTime && a.CreateTime <= endTime && a.CreateId == id)
                                .SplitTable(beginTime, endTime).ToListAsync();
                    var list = db.SysFrontendSettingConfig.AsQueryable().Where(r => r.Code == "TimeSlot").ToList();
                    for (int i = 0; i < days; i++)
                    {
                        if (usertime.Count > 0)
                        {
                            foreach (var item in usertime)
                            {
                                var begslot = item.TimeSlot.Split('-');
                                UserPatrolInfoResp resin = new UserPatrolInfoResp
                                {
                                    CreateId = id,
                                    Name = user.Name,
                                    StartTime = beginTime.ToString("yyyy-MM-dd ") + begslot[0],
                                    EndTime = beginTime.ToString("yyyy-MM-dd ") + begslot[1],
                                };

                                if (userpoint.Where(a => a.CreateTime >= DateTime.Parse(resin.StartTime) && a.CreateTime <= DateTime.Parse(resin.EndTime)).Count() > 0)
                                {
                                    upinfo.Add(resin);
                                }
                            }
                            beginTime = beginTime.AddDays(1);
                        }
                        else
                        {
                            foreach (var item in list)
                            {
                                var begslot = item.CodeValue.Split('-');
                                UserPatrolInfoResp resin = new UserPatrolInfoResp
                                {
                                    CreateId = id,
                                    Name = user.Name,
                                    StartTime = beginTime.ToString("yyyy-MM-dd ") + begslot[0],
                                    EndTime = beginTime.ToString("yyyy-MM-dd ") + begslot[1],
                                };
                                if (userpoint.Where(a => a.CreateTime >= DateTime.Parse(resin.StartTime) && a.CreateTime <= DateTime.Parse(resin.EndTime)).Count() > 0)
                                {
                                    upinfo.Add(resin);
                                }
                            }
                            beginTime = beginTime.AddDays(1);
                        }
                    }
                    upinfo = upinfo.OrderByDescending(r => r.StartTime).ToList();
                    return new Response<List<UserPatrolInfoResp>> { Result = upinfo, Message = "操作成功" };
                }
                else
                {
                    throw new Exception("用户不存在");
                }


            }
        }
        /// <summary>
        /// 巡查坐标 
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public async Task<Response<List<FmUserPointHistory>>> LoadPatrolPointByTime(long userId, DateTime beginTime, DateTime endTime)
        {
            using (SugarDbContext db = base.UnitWork.CreateContext())
            {
                var userpoint = await db.FmUserPointHistory.AsQueryable().Where(a => a.CreateTime >= beginTime && a.CreateTime <= endTime && a.CreateId == userId)
                            .SplitTable(beginTime, endTime).ToListAsync();
                return new Response<List<FmUserPointHistory>> { Result = userpoint, Message = "操作成功" };
            }
        }
        /// <summary>
        /// 获取护林员巡查范围
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public async Task<Response<dynamic>> GetUserRange(string phone)
        {
            using (SugarDbContext db = base.UnitWork.CreateContext())
            {
                string sql = "select \"Id\",\"Hulinyuan\",\"Lianxifang\",st_astext(ST_Boundary(geom))  as geom   FROM fm_hulinyuanguanhufanwei  WHERE \"Lianxifang\" like '%" + phone + "%'";
                var dt = await db.Db.Ado.GetDataTableAsync(sql);

                var user = await db.User.GetFirstAsync(r => r.Account == phone);

                var query = await db.FmCheckInPoint.AsQueryable()
                .LeftJoin<FmCheckPointUser>((a, b) => a.Id == b.PointId)
                    .Where((a, b) => b.UserId == user.Id)
                    .Select<dynamic>((a, b) => new
                    {
                        a.Id,
                        a.Lng,
                        a.Lat,
                        a.PointName,
                    }).ToListAsync();
                var obj = new
                {
                    UserRange = dt,
                    CheckPoint = query
                };
                if (dt.Rows.Count > 0)
                    return new Response<dynamic> { Result = obj, Message = "操作成功" };
                else
                    return new Response<dynamic> { Result = null, Message = "暂无数据" };
            }
        }
        //查询单条巡检记录
        public async Task<Response<List<FmUserPointHistory>>> LoadPatrolPointByTimeSubsection(long id, DateTime beginTime, DateTime endTime)
        {
            using (SugarDbContext db = base.UnitWork.CreateContext())
            {
                var check = await db.FmUserPointHistory.AsQueryable()
                    .Where(a => a.CreateTime >= beginTime && a.CreateTime <= endTime && a.CreateId == id) 
                    .SplitTable(beginTime, endTime).Take(10000)
                    .OrderBy(a => a.CreateTime, OrderByType.Asc).ToListAsync();
                return new Response<List<FmUserPointHistory>> { Result = check, Message = "操作成功" };
            }
        }

        public async Task<Response<List<PatrolinfoResp>>> LoadPatrolInfoByUserIdNew(long userId, DateTime beginTime, DateTime endTime)
        {
            using (SugarDbContext db = base.UnitWork.CreateContext())
            {
                var usertime = db.FmUserTimeSlot.AsQueryable().Where(r => r.CreateId == userId).ToList();
                var userinfo = db.User.AsQueryable().First(r => r.Id == userId);
                TimeSpan timeSpan = endTime.AddDays(1).Subtract(beginTime);
                int days = (int)timeSpan.TotalDays;
                List<PatrolinfoResp> reslist = new List<PatrolinfoResp>();
                var info = await db.FmUserPointHistory.AsQueryable()
                           .Where(a => a.CreateTime >= beginTime && a.CreateTime <= endTime && a.CreateId == userId)
                            .SplitTable(beginTime, endTime).ToListAsync();
                for (int i = 0; i < days; i++)
                {
                    if (usertime.Count > 0)
                    {
                        foreach (var item in usertime)
                        {
                            var begslot = item.TimeSlot.Split('-');
                            PatrolinfoResp resin = new PatrolinfoResp();
                            resin.CreateId = userId;
                            resin.Name = userinfo.Name;
                            resin.StartTime = beginTime.ToString("yyyy-MM-dd ") + begslot[0];
                            resin.EndTime = beginTime.ToString("yyyy-MM-dd ") + begslot[1];
                            if (info.Where(a => a.CreateTime >= DateTime.Parse(resin.StartTime) && a.CreateTime <= DateTime.Parse(resin.EndTime)).Count() > 0)
                            {
                                reslist.Add(resin);
                            }

                        }
                        beginTime = beginTime.AddDays(1);
                    }
                    else
                    {
                        var list = db.SysFrontendSettingConfig.AsQueryable().Where(r => r.Code == "TimeSlot").ToList();
                        foreach (var item in list)
                        {
                            var begslot = item.CodeValue.Split('-');
                            PatrolinfoResp resin = new PatrolinfoResp();
                            resin.CreateId = userId;
                            resin.Name = userinfo.Name;
                            resin.StartTime = beginTime.ToString("yyyy-MM-dd ") + begslot[0];
                            resin.EndTime = beginTime.ToString("yyyy-MM-dd ") + begslot[1];
                            if (info.Where(a => a.CreateTime >= DateTime.Parse(resin.StartTime) && a.CreateTime <= DateTime.Parse(resin.EndTime)).Count() > 0)
                            {
                                reslist.Add(resin);
                            }
                        }
                        beginTime = beginTime.AddDays(1);
                    }

                }
                return new Response<List<PatrolinfoResp>> { Result = reslist, Message = "操作成功" };
            }
        }


    } 
}
