
using AutoMapper.Execution;
using DocumentFormat.OpenXml.Office2010.Excel;
using Infrastructure;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.Interface;
using OpenAuth.App.Request;
using OpenAuth.App.Response;
using OpenAuth.App.ServiceApp.MiManager.Response;
using OpenAuth.App.ServiceApp.MiManager.Resquest;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using SqlSugar;

namespace OpenAuth.App
{
    public class MiPunchRecordApp : SqlSugarBaseApp<MiPunchRecord, SugarDbContext>
    {
        public MiPunchRecordApp(
            ISugarUnitOfWork<SugarDbContext> unitWork,
            ISimpleClient<MiPunchRecord> repository,
            IAuth auth
            ) : base(unitWork, repository, auth)
        {

        }

        #region 查询
        /// <summary>
        /// 分页
        /// </summary>
        public async Task<Response<PageInfo<List<dynamic>>>> LoadAllPage(MiPuchLoadreq req)
        {
            RefAsync<int> totalCount = 0;
            var list = await base.Repository.AsQueryable()
                .WhereIF(req.begintime!=null&&req.endtime!=null,r=>r.PunchTime>=req.begintime&&r.PunchTime<req.endtime)
                .WhereIF(req.status!=null,r=>r.PunchStatus==req.status)
                .LeftJoin<SysUser>((r,u)=>r.UserId==u.Id)
                .LeftJoin<MiMinePoint>((r,u,p)=>r.MinePointId==p.Id)
                .WhereIF(!string.IsNullOrEmpty(req.username),(r,u,p)=>u.Name.Contains(req.username))
                .WhereIF(!string.IsNullOrEmpty(req.key),(r,u,p)=>p.Name.Contains(req.key))
                .OrderByDescending((r, u, p) => r.PunchTime)
                .Select<dynamic>((r, u, p) => new
                {
                    Id = r.Id.SelectAll(),
                    Name=u.Name,
                    PointName=p.Name,
                    StatusName = SqlFunc.Subqueryable<SysDataItemDetail>().Where(a => a.ItemCode == "JGMinePointStatus" && a.ItemValue == r.PunchStatus.ToString()).Select(a => a.ItemName)
                })
                .ToPageListAsync(req.page, req.limit, totalCount);

            return new Response<PageInfo<List<dynamic>>>
            {
                Result = new PageInfo<List<dynamic>>
                {
                    Items = list,
                    Total = totalCount
                }
            };
        }
        #endregion

        /// <summary>
        /// 详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Response<MiPuchRecordRes>> Get(string id)
        {
            var data= await Repository.AsQueryable()
                .Where(r=>r.Id==id)
                .LeftJoin<SysUser>((r,u)=>r.UserId==u.Id)
                .LeftJoin<MiMinePoint>((r, u, p) => r.MinePointId == p.Id)
                .Select((r, u, p) => new MiPuchRecordRes
                {
                    Id = r.Id,
                    UserId = r.UserId,
                    UserName=u.Name,
                    Lat=r.Lat,
                    Lng=r.Lng,
                    MinePointId=r.MinePointId,
                    PunchStatus=r.PunchStatus,
                    PunchTime=r.PunchTime,
                    Remark=r.Remark,
                    Image=SqlFunc.Subqueryable<MiPunchImage>().Where(a=>a.PunchId==r.Id).ToList(),
                    PointName=p.Name,
                    StatusName = SqlFunc.Subqueryable<SysDataItemDetail>().Where(a => a.ItemCode == "JGMinePointStatus" && a.ItemValue == r.PunchStatus.ToString()).Select(a => a.ItemName)
                }).FirstAsync();
            return new Response<MiPuchRecordRes>()
            { 
                Result=data
            };
        }


        /// <summary>
        /// 添加
        /// </summary>
        public async Task<Response<bool>> Add(MiPuchRecordReq model)
        {
            if (string.IsNullOrEmpty(model.MinePointId))
            {
                throw new Exception("请输入监管盗采点");
            }
            var user = _auth.GetCurrentUser().User;
            MiPunchRecord record = model.MapTo<MiPunchRecord>();
            record.Id = Guid.NewGuid().ToString();
            record.PunchTime = DateTime.Now;
            record.UserId = user.Id;

            List<MiPunchImage> image = new List<MiPunchImage>();
            foreach (var item in model.Image)
            {
                var img = item.MapTo<MiPunchImage>();
                img.Id = Guid.NewGuid().ToString();
                img.MinePointId = model.MinePointId;
                img.PunchId = record.Id;
                img.CreateTime = DateTime.Now;
                image.Add(img);
            }

            using (var uow = base.UnitWork.CreateContext())
            {
                var flag1 = await uow.MiPunchRecord.InsertAsync(record);
                var flag2 = await uow.MiPunchImage.InsertRangeAsync(image);
                var flag = uow.Commit() && flag1 && flag2;
                return new Response<bool>
                {
                    Result = flag,
                    Message = flag == true ? "success" : "error"
                };
            }
        }


        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        public async Task<Response<bool>> Delete(List<string> ids )
        {
            using (var uow = base.UnitWork.CreateContext())
            {
                var flag1 = await uow.MiPunchRecord.DeleteAsync(r=>ids.Contains(r.Id));
                var flag2 = await uow.MiPunchImage.DeleteAsync(r=>ids.Contains(r.PunchId));
                var flag = uow.Commit() && flag1 && flag2;
                return new Response<bool>
                {
                    Result = flag,
                    Message = flag == true ? "success" : "error"
                };
            }
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="obj"></param>
        public async Task<Response<bool>> Update(MiPuchRecordReq model)
        {
            if (string.IsNullOrEmpty(model.MinePointId))
            {
                throw new Exception("请输入监管盗采点");
            }

            MiPunchRecord record = model.MapTo<MiPunchRecord>();

            List<MiPunchImage> image = new List<MiPunchImage>();
            foreach (var item in model.Image)
            {
                var img = item.MapTo<MiPunchImage>();
                img.Id = Guid.NewGuid().ToString();
                img.MinePointId = model.MinePointId;
                img.PunchId = record.Id;
                img.CreateTime = DateTime.Now;
                image.Add(img);
            }

            using (var uow = base.UnitWork.CreateContext())
            {
                await uow.MiPunchImage.DeleteAsync(r=>r.PunchId==model.Id);
                await uow.MiPunchRecord.UpdateAsync(record);
                await uow.MiPunchImage.InsertRangeAsync(image);
                var flag = uow.Commit();
                return new Response<bool>
                {
                    Result = flag,
                    Message = flag == true ? "success" : "error"
                };
            }
        }

        /// <summary>
        /// 事务示例
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<Response<bool>> AssignModule()
        {
            using (var uwo = UnitWork.CreateContext())
            {
                //await uwo.SysRoleElement.InsertRangeAsync(model.ElementIds.Select(a => new SysRoleElement { RoleId = model.RoleId, ElementId = a }).ToList());

                var flag = uwo.Commit();
                return new Response<bool>
                {
                    Result = flag,
                    Message = flag == true ? "success" : "error"
                };
            }
        }

    }
}