using OpenAuth.App.BaseApp.Base;
using OpenAuth.Repository.Domain;
using OpenAuth.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenAuth.App.BaseApp.Shape;
using OpenAuth.App.Interface;
using SqlSugar;
using Microsoft.Extensions.Configuration;
using Infrastructure;
using OpenAuth.App.Request;
using OpenAuth.App.ServiceApp.DroneCaseInfoDev.Request;
using Infrastructure.Extensions;
using Infrastructure.Helpers;
using Infrastructure.Utilities;
using System.DirectoryServices;
using DocumentFormat.OpenXml.Wordprocessing;
using OpenAuth.App.Response;

namespace OpenAuth.App.ServiceApp.DroneCaseInfoDev
{
    public class DroneCaseInfoDevApp : SqlSugarBaseApp<DroneCaseInfoSingle, SugarDbContext>
    {
        private ISqlSugarClient client;
        public DroneCaseInfoDevApp(ISugarUnitOfWork<SugarDbContext> unitWork, ISimpleClient<DroneCaseInfoSingle> repository, IAuth auth, ISqlSugarClient sqlSugarClient) : base(unitWork, repository, auth)
        {
            this.client = sqlSugarClient;
        }

        /// <summary>
        /// 获取案件列表信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<Response<PageInfo<List<DroneCaseInfoSingle>>>> LoadCaseInfoPageList(CaseInfoDev request)
        {
            RefAsync<int> totalNumber = 0;

            var table = await base.Repository.AsQueryable()
                     .WhereIF(!string.IsNullOrEmpty(request.tubanlaiyuan), r => r.tubanlaiyuan == request.tubanlaiyuan)
                     .WhereIF(!string.IsNullOrEmpty(request.typename), r => r.typename == request.typename)
                     .WhereIF(!string.IsNullOrEmpty(request.isBuildName), r => r.is_build_name == request.isBuildName)
                     .WhereIF(request.isIllegal != null, r => r.is_illegal == request.isIllegal)
                     .WhereIF(request.isIntact != null, r => r.is_intact == request.isIntact)
                     .WhereIF(!string.IsNullOrEmpty(request.nowStatus), r => r.handle_status_name == request.nowStatus)
                     .WhereIF(!string.IsNullOrEmpty(request.measureName), r => r.measure_name == request.measureName)
                     .WhereIF(!string.IsNullOrEmpty(request.countyid), r => r.countyid == request.countyid)
                     .WhereIF(!string.IsNullOrEmpty(request.streetid), r => r.streetid == request.streetid)
                     .WhereIF(!string.IsNullOrEmpty(request.caseNo), r => r.case_no == request.caseNo)
                     .WhereIF(!string.IsNullOrEmpty(request.originalcaseno), r => r.original_case_no == request.originalcaseno)
                     .WhereIF(request.synchronoustime != null, r => r.synchronoustime > request.synchronoustime)
                     .OrderByIF(request.synchronoustime != null, r => r.synchronoustime, OrderByType.Asc)
                     .OrderByIF(request.synchronoustime == null, r => r.createtime, OrderByType.Desc).ToPageListAsync(request.page, request.limit, totalNumber);

            return new Response<PageInfo<List<DroneCaseInfoSingle>>>()
            {
                Result = new PageInfo<List<DroneCaseInfoSingle>>
                {
                    Items = table,
                    Total = totalNumber
                }
            };
        }

        /// <summary>
        /// 添加模板信息
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public Response<bool> AddSchemeDev(WFScheme req)
        {
            var info = client.Queryable<WFScheme>().Where(r => r.Id == req.Id).ToList();
            if (info.Count > 0)
            {
                throw new Exception("模板已存在");
            }
            else
            {
                using (var uow = base.UnitWork.CreateContext())
                {
                    //添加模板版本信息
                    uow.WFScheme.Insert(req);
                    WFSchemeInfo wsc = client.Queryable<WFSchemeInfo>().Where(r => r.Id == req.SchemeInfoId).First();
                    if (wsc != null)
                    {
                        //更新模板信息
                        uow.WFSchemeInfo.Update(s => new WFSchemeInfo
                        {
                            SchemeId = req.Id
                        }, s => s.Id == wsc.Id);

                        //更新流程信息
                        uow.WFProcess.Update(r => new WFProcess
                        {
                            SchemeId = req.Id
                        }, r => r.SchemeCode == wsc.Code);
                    }

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

        /// <summary>
        /// 获取县区
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<List<SysOrg>> LoadChildren(long? parentId)
        {
            //List<dynamic> children = new List<dynamic>();
            //if (parentId != null)
            //{
            //    children = await base.Repository.ChangeRepository<SugarRepositiry<SysOrg>>()
            //      .AsQueryable().Where(r => r.ParentId == parentId).Select<dynamic>(r => new
            //      {
            //          Id = r.Id,
            //          Name = r.Name,
            //      }, true).ToListAsync();
            //}

            List<SysOrg> children = new List<SysOrg>();
            if (parentId != null)
            {
                children = await base.Repository.ChangeRepository<SugarRepositiry<SysOrg>>().AsQueryable()
                    .Where(r => r.ParentId == parentId).OrderBy(r => r.SortNo).ToListAsync();
            }
            return children;
        }

        public async Task<CaseInfoAbout> LoadCaseInfoAbout(string caseId)
        {
            var model = new CaseInfoAbout();
            model.CaseInfo = await client.Queryable<DroneCaseInfoSingle>().FirstAsync(a => a.Id == caseId);
            model.ProcessInfo = await client.Queryable<WFProcess>().FirstAsync(a => a.Id == caseId);
            model.Tasks = await client.Queryable<WFTask>()
                .Where(a => a.ProcessId == caseId).ToListAsync();
            model.TaskLogs = await client.Queryable<WFTaskLog>()
                .Where(a => a.ProcessId == caseId).ToListAsync();
            return model;
        }
    }
}
