using OpenAuth.App.BaseApp.Base;
using OpenAuth.Repository.Domain.FireManagement;
using OpenAuth.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenAuth.Repository.Domain;
using Microsoft.Extensions.Options;
using OpenAuth.App.Common;
using OpenAuth.App.Interface;
using SqlSugar;
using System.Net.WebSockets;
using Microsoft.Extensions.Configuration;
using Infrastructure;
using OpenAuth.App.ServiceApp.FireManagement.Request;
using OpenAuth.App.ServiceApp.FmPreventionPlanManage.Request;
using Yitter.IdGenerator;
using OpenAuth.App.Const;

namespace OpenAuth.App.ServiceApp.FmPreventionPlanManage
{
    public class FmPreventionPlanApp : SqlSugarBaseApp<FmPreventionplan, SugarDbContext>
    {

        private ClientWebSocket _socket;
        private IConfiguration _configuration;

        public FmPreventionPlanApp(IConfiguration configuration,  ISugarUnitOfWork<SugarDbContext> unitWork,ISimpleClient<FmPreventionplan> repository, IAuth auth) : base(unitWork, repository, auth)
        {
            _auth = auth;
            _configuration = configuration;
        }

        /// <summary>
        /// 分页查询预案列表
        /// </summary>
        /// <returns></returns>
        public async Task<Response<PageInfo<List<FmPreventionplan>>>> GetPreventionplanPageList(FmPreventionplanReq req)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                RefAsync<int> totalNumber = 0;
                var infos = await db.FmPreventionplan.AsQueryable()
                    .Where(r=>r.IsDelete==false)
                    .WhereIF(req.state != null, r => r.Status == req.state)
                    .WhereIF(req.plancategory != null, r => r.PlanCategory == req.plancategory)
                    .WhereIF(req.createtimebegin != null && req.createtimeend != null, r => r.CreateTime >= req.createtimebegin && r.CreateTime <= req.createtimeend)
                    .WhereIF(!string.IsNullOrEmpty(req.name), r => r.PlanName.Contains(req.name))
                    .WhereIF(!string.IsNullOrEmpty(req.code), r => r.PlanCode.Contains(req.code))
                    .ToPageListAsync(req.page, req.limit, totalNumber);
                return new Response<PageInfo<List<FmPreventionplan>>>
                {
                    Result = new PageInfo<List<FmPreventionplan>> { Items = infos, Total = totalNumber }
                };
            }
        }


        /// <summary>
        /// 查询应急预案详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Response<FmPreventionplan>> LoadClueInfoById(string id)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                var info = await db.FmPreventionplan.AsQueryable()
                    .FirstAsync(r => r.Id == id);
                return new Response<FmPreventionplan> { Result = info };
            }
        }


        //删除应急预案
        public async Task<Response<bool>> DeletePreventionplan(string id)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                var taskinfo = await db.FmPreventionplan.AsQueryable().FirstAsync(r => r.Id == id);
                if (taskinfo != null) 
                {
                    var flag=await db.FmPreventionplan.UpdateAsync(r => new FmPreventionplan
                    {
                        IsDelete = true
                    }, r => r.Id == id);
                    if (db.Commit()&&flag)
                    {
                        return new Response<bool> { Result = true, Message = "操作成功" };
                    }
                    else
                    {
                        return new Response<bool> { Result = false, Message = "操作失败" };
                    }
                }
                else
                {
                    return new Response<bool> { Result = false, Message = "预案不存在" };
                }
            }
        }

        //添加预案
        public async Task<Response<bool>> AddPreventionplan(FmPreventionplan info)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                var user = _auth.GetCurrentUser().User;
                info.Id = Guid.NewGuid().ToString();
                info.CreateTime = DateTime.Now;
                info.CreateUser = user.Name;
                info.IsDelete = false;
                if (string.IsNullOrEmpty(info.PlanCode))
                {
                    throw new Exception("请输入预案编号");
                }
                
                var exitinfo = db.FmPreventionplan
                    .AsQueryable()
                    .Count(a => a.PlanCode==info.PlanCode);
                if (exitinfo > 0)
                {
                    throw new Exception("预案编号已存在，请重新输入");
                }

                var flag=await db.FmPreventionplan.InsertAsync(info);

                if (db.Commit()&&flag)
                {
                    return new Response<bool> { Result = true, Message = "操作成功" };
                }
                else
                {
                    return new Response<bool> { Result = false, Message = "操作失败" };
                }
            }
        }
    }
}
