using DocumentFormat.OpenXml.Office2010.Excel;
using Infrastructure;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.Const;
using OpenAuth.App.Interface;
using OpenAuth.App.ServiceApp.FireManagement.Request;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using OpenAuth.Repository.Domain.FireManagement;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace OpenAuth.App.ServiceApp.FireManagement
{
    public class FireGridApp : SqlSugarBaseApp<FmCheckInPoint, SugarDbContext>
    {
        public FireGridApp(ISugarUnitOfWork<SugarDbContext> unitWork,
        ISimpleClient<FmCheckInPoint> repository, IAuth auth) : base(unitWork, repository, auth)
        {
            _auth = auth;
        }
        /// <summary>
        /// 添加打卡点
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<Response<bool>> AddCheckPoint(CheckPointReq info)
        {
            using (SugarDbContext db = base.UnitWork.CreateContext())
            {
                var checkPoint = info.MapTo<FmCheckInPoint>();
                checkPoint.Id = YitIdHelper.NextId();
                checkPoint.CreateTime = DateTime.Now;

                List<FmCheckPointUser> sflist = info.UserId
                    .Select(item => new FmCheckPointUser { PointId = checkPoint.Id, UserId = item }).ToList();

                List<FmCheckArea> fck = info.AreaId
                   .Select(item => new FmCheckArea { PointId = checkPoint.Id, AreaId = item }).ToList();

                ////判断是否在巡查范围之内
                //string sqlstr = "SELECT \"Id\" FROM fm_hulinyuanguanhufanwei WHERE ST_Contains(ST_SetSRID(geom, 4326), ST_GeomFromText('POINT(" + info.Lng + " " + info.Lat + ")', 4326)) =TRUE"; ;

                //var dt = await db.Db.Ado.GetDataTableAsync(sqlstr);
                //if (dt.Rows.Count < 1)
                //{
                //    throw new Exception("请在护林员巡查范围内设置打卡点");
                //}
                await db.FmCheckInPoint.InsertAsync(checkPoint);
                await db.FmCheckPointUser.InsertRangeAsync(sflist);
                await db.FmCheckArea.InsertRangeAsync(fck);
                if (db.Commit())
                {
                    return new Response<bool> { Result = true, Message = "操作成功" };
                }
                else
                {
                    return new Response<bool> { Result = false, Message = "操作失败" };
                }
            }
        }
        //查询打卡点
        public async Task<Response<PageInfo<List<dynamic>>>> GetCheckPointList(string pointName, int pageIndex, int pageSize)
        {
            using (SugarDbContext db = base.UnitWork.CreateContext())
            {
                RefAsync<int> totalNumber = 0;
                var query = await db.FmCheckInPoint.AsQueryable()
                    .LeftJoin<SysUser>((a, b) => a.CreateId == b.Id)
                    .WhereIF(!string.IsNullOrEmpty(pointName), (a, b) => a.PointName.Contains(pointName))
                    .Select<dynamic>((a, b) => new
                    {
                        a.Id,
                        a.PointName,
                        a.Lat,
                        a.Lng,
                        a.CreateTime,
                        CreateUserName = b.Name
                    }).ToPageListAsync(pageIndex, pageSize, totalNumber);
                return new Response<PageInfo<List<dynamic>>>
                {
                    Result = new PageInfo<List<dynamic>> { Items = query, Total = totalNumber }
                };
            }
        }
        /// <summary>
        /// 删除打卡点
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Response<bool>> DeleteCheckPoint(long id)
        {
            using (SugarDbContext db = base.UnitWork.CreateContext())
            {
                await db.FmCheckInPoint.UpdateAsync(r => new FmCheckInPoint { IsDelete = true }, r => r.Id == id);
                if (db.Commit())
                {
                    return new Response<bool> { Result = true, Message = "操作成功" };
                }
                else
                {
                    return new Response<bool> { Result = false, Message = "操作失败" };
                }
            }
        }
        //编辑打卡点
        public async Task<Response<bool>> EditCheckPoint(CheckPointReq info)
        {
            using (SugarDbContext db = base.UnitWork.CreateContext())
            {
                ////判断是否在巡查范围之内
                //string sqlstr = "SELECT \"Id\" FROM fm_hulinyuanguanhufanwei WHERE ST_Contains(ST_SetSRID(geom, 4326), ST_GeomFromText('POINT(" + info.Lng + " " + info.Lat + ")', 4326)) =TRUE"; ;

                //var dt = await db.Db.Ado.GetDataTableAsync(sqlstr);
                //if (dt.Rows.Count < 1)
                //{
                //    throw new Exception("请在护林员巡查范围内设置打卡点");
                //}
                await db.FmCheckInPoint.UpdateAsync(r => new FmCheckInPoint 
                {
                    PointName = info.PointName,
                    Lat = info.Lat,
                    Lng = info.Lng
                }, r => r.Id == info.Id);
                //添加人员打卡点中间表
                await db.FmCheckPointUser.DeleteAsync(r => r.PointId == info.Id);
                List<FmCheckPointUser> sflist = info.UserId
                    .Select(item => new FmCheckPointUser { PointId = info.Id, UserId = item }).ToList();
                await db.FmCheckPointUser.InsertRangeAsync(sflist);
                //添加打卡点区域中间表
                await db.FmCheckArea.DeleteAsync(r => r.PointId == info.Id);
                List<FmCheckArea> fck = info.AreaId
                   .Select(item => new FmCheckArea { PointId = info.Id, AreaId = item }).ToList();
                await db.FmCheckArea.InsertRangeAsync(fck);
                if (db.Commit())
                {
                    return new Response<bool> { Result = true, Message = "操作成功" };
                }
                else
                {
                    return new Response<bool> { Result = false, Message = "操作失败" };
                }

            }
        }
        //获取单条打卡点信息
        public async Task<Response<CheckPointReq>> GetCheckPointById(long id)
        {
            using (SugarDbContext db = base.UnitWork.CreateContext())
            {
                var query = await db.FmCheckInPoint.AsQueryable()
                    .Where(a => a.Id == id)
                    .Select(r => new CheckPointReq
                    {
                        Id = r.Id,
                        Lng = r.Lng,
                        Lat = r.Lat,
                        PointName = r.PointName,
                        UserId = SqlFunc.Subqueryable<FmCheckPointUser>().Where(a => a.PointId == id).ToList(a => a.UserId),
                        AreaId = SqlFunc.Subqueryable<FmCheckArea>().Where(a => a.PointId == id).ToList(a => a.AreaId),
                    })
                    .FirstAsync();
                return new Response<CheckPointReq>
                {
                    Result = query
                };
            }
        }

        /// <summary>
        /// 查询打卡记录
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<Response<PageInfo<List<dynamic>>>> GetClockOnList(long userId, DateTime beginTime, DateTime endTime, int pageIndex, int pageSize)
        {
            using (SugarDbContext db = base.UnitWork.CreateContext())
            {
                RefAsync<int> totalNumber = 0;
                var query = await db.FmCheckClockOn.AsQueryable()
                    .LeftJoin<FmCheckInPoint>((a, b) => a.PointId == b.Id)
                    .LeftJoin<SysUser>((a, b, c) => a.UserId == c.Id)
                    .WhereIF(userId != 0, (a, b, c) => a.UserId == userId)
                    .Where((a, b, c) => a.ClockonTime >= beginTime && a.ClockonTime <= endTime)
                    .Select<dynamic>((a, b, c) => new
                    {
                        a.Id,
                        a.ClockonTime,
                        a.Lat,
                        a.Lng,
                        b.PointName,
                        c.Name
                    }).ToPageListAsync(pageIndex, pageSize, totalNumber);
                return new Response<PageInfo<List<dynamic>>>
                {
                    Result = new PageInfo<List<dynamic>> { Items = query, Total = totalNumber }
                };
            }
        }

        //上传坐标
        //public async Task<Response<bool>> UploadLocation(FmUserPoint info)
        //{
        //    using (SugarDbContext db = base.UnitWork.CreateContext())
        //    {
        //        var userPoint = info.MapTo<FmUserPoint>();
        //        checkPoint.Id = YitIdHelper.NextId();
        //        checkPoint.ClockonTime = DateTime.Now;
        //        await db.FmCheckClockOn.InsertAsync(checkPoint);
        //        if (db.Commit())
        //        {
        //            return new Response<bool> { Result = true, Message = "操作成功" };
        //        }
        //        else
        //        {
        //            return new Response<bool> { Result = false, Message = "操作失败" };
        //        }
        //    }
        //}
    }
}
