using System.Data;
using System.Diagnostics;
using DocumentFormat.OpenXml.EMMA;
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Office2021.DocumentTasks;
using DocumentFormat.OpenXml.Spreadsheet;
using Infrastructure;
using Infrastructure.Extensions;
using JetBrains.Annotations;
using Microsoft.Extensions.Configuration;
using Moq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using NPOI.Util;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.BaseApp.WFTask.Response;
using OpenAuth.App.FormScheme;
using OpenAuth.App.FormScheme.Response;
using OpenAuth.App.Interface;
using OpenAuth.App.Request;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using Org.BouncyCastle.Ocsp;
using SqlSugar;
using static ICSharpCode.SharpZipLib.Zip.ExtendedUnixData;

namespace OpenAuth.App.BaseApp.WFTask
{
    public class WFTaskApp : SqlSugarBaseApp<Repository.Domain.WFTask, SugarDbContext>
    {
        ISqlSugarClient client;
        private readonly FormSchemeApp _formSchemeApp;
        private readonly WFProcessApp _processApp;
        private WFSchemeInfoApp _schemeInfoApp;
        private readonly IConfiguration _configuration;

        public WFTaskApp(ISugarUnitOfWork<SugarDbContext> unitWork, ISimpleClient<Repository.Domain.WFTask> repository,
            IAuth auth,
            FormSchemeApp formSchemeApp,
            WFProcessApp processApp,
            WFSchemeInfoApp schemeInfoAppApp,
            IConfiguration configuration
        ) :
            base(unitWork, repository, auth)
        {
            client = base.Repository.AsSugarClient();
            _formSchemeApp = formSchemeApp;
            _processApp = processApp;
            _schemeInfoApp = schemeInfoAppApp;
            _configuration = configuration;
        }

        #region 任务

        /// <summary>
        /// 获取我的代办任务列表
        /// </summary>
        /// <param name="pagination">分页参数</param>
        /// <param name="searchParams">查询参数</param>
        /// <param name="isBatchAudit">是否允许批量审核</param>
        /// <returns></returns>
        public async Task<PageInfo<List<Repository.Domain.WFTask>>> GetMyUncompletedPageList(PageReq pageReq,
            WFProcessSearchDto searchParams, string category, bool isBatchAudit = false)
        {
            RefAsync<int> totalCount = 0;
            var userId = _auth.GetUserId();

            var expression = Expressionable.Create<Repository.Domain.WFTask>()
                //.And(t => t.UserId == userId)
                .And(t => t.State == 1)
                .And(t => t.Type != 2)
                .AndIF(!string.IsNullOrEmpty(searchParams.Keyword),
                    t => t.ProcessTitle.Contains(searchParams.Keyword) || t.UnitName.Contains(searchParams.Keyword))
                .AndIF(!string.IsNullOrEmpty(searchParams.Code), t => t.ProcessCode == searchParams.Code)
                .AndIF(searchParams.StartDate != null && searchParams.EndDate != null,
                    t => t.CreateDate >= searchParams.StartDate && t.CreateDate <= searchParams.EndDate)
                .AndIF(isBatchAudit, t => t.IsBatchAudit == 1);

            var list = await client.Queryable<Repository.Domain.WFTask>()
                .Where(expression.ToExpression())
                .LeftJoin<WFTaskUser>((t, u) => t.Id == u.TaskId && u.UserId == userId)
                .Where((t, u) => u.UserId == userId || t.UserId == userId)
                .LeftJoin<WFProcess>((t, u, p) => t.ProcessId == p.Id)
                .LeftJoin<WFScheme>((t, u, p, s) => p.SchemeId == s.Id)
                .LeftJoin<WFSchemeInfo>((t, u, p, s, i) => s.SchemeInfoId == i.Id)
                .WhereIF(!string.IsNullOrEmpty(category), (t, u, p, s, i) => i.Category == category)
                .OrderByDescending((t, u, p, s, i) => t.CreateDate)
                .Select((t, u, p, s, i) => new Repository.Domain.WFTask()
                {
                    Id = t.Id.SelectAll(),
                    SchemeContent = s.Content,
                    InstanceInfo = p.InstanceInfo
                })
                .ToPageListAsync(pageReq.page, pageReq.limit, totalCount);
            // 遍历补充信息 
            foreach (var wfTask in list)
            {
                // 获取表单数据
                var unitId = wfTask.UnitId; // 当前节点id
                //var process = await _processApp.GetEntity(wfTask.ProcessId);
                //var scheme = await _schemeInfoApp.GetSchemeEntity(process.SchemeId);
                //var　content = (JObject)JsonConvert.DeserializeObject(scheme.Content);
                var content = (JObject)JsonConvert.DeserializeObject(wfTask.SchemeContent);

                var wfData = (JArray)content["wfData"];
                //
                var instanceInfo = wfTask.InstanceInfo;
                var processId = instanceInfo.pkeyValue;
                var pkey = instanceInfo.pkey;
                foreach (var jToken in wfData)
                {
                    var id = jToken["id"]?.ToString();
                    if (id != null && id.Equals(unitId))
                    {
                        var first = jToken;
                        // fromVersion 为 schemeId
                        var formVersion = first["formVerison"]?.ToString();
                        if (!string.IsNullOrEmpty(formVersion))
                        {
                            var authFields = (JArray)jToken["authFields"];
                            var showFields = new Dictionary<string, ExtendInfo>();
                            foreach (var authField in authFields)
                            {
                                var label = authField["label"].ToString();
                                var field = authField["field"].ToString();
                                var fieldName = authField["fieldName"]?.ToString();
                                if (authField["upShow"].ToBool().Equals(true))
                                {
                                    showFields.Add(field,
                                        new ExtendInfo() { Field = field, Label = label, FieldName = fieldName });
                                }
                            }

                            var sql = "select ";
                            var selectFields = "";
                            foreach (var showField in showFields)
                            {
                                selectFields += $"\"{showField.Value.FieldName}\"" + " as " + showField.Value.Field +
                                                ",";
                            }

                            selectFields = selectFields.TrimEnd(',');

                            var formScheme = await _formSchemeApp.GetScheme(formVersion);
                            FormSchemeNewModel formSchemeModel = formScheme.Scheme.ToObject<FormSchemeNewModel>();
                            FormDbTableInfo mainTable = formSchemeModel.Db.Find(t => t.Type == "main");
                            sql += selectFields + $" FROM \"{mainTable.Name}\" t where \"{pkey}\" = @Id";

                            var dataList = await client.Ado.GetDataTableAsync(sql, new { Id = processId });

                            //  实现一个新的查询方法
                            //   var dataList = await _formSchemeApp.GetFormDataNew(formVersion, "Id", processId);
                            // var data = dataList.FirstOrDefault().Value;
                            // 实际只有一行数据
                            foreach (DataRow dataRow in dataList.Rows)
                            {
                                foreach (var showField in showFields)
                                {
                                    var field = showField.Key;
                                    var value = dataRow[field];
                                    showField.Value.Value = value;
                                }
                            }

                            wfTask.ExtendInfo = showFields.Values;
                        }
                    }
                }

                wfTask.SchemeContent = null;
                wfTask.InstanceInfo = null;
            }

            return new PageInfo<List<Repository.Domain.WFTask>>
            {
                Items = list,
                Total = totalCount
            };
        }


        /// <summary>
        /// 获取我的代办任务列表
        /// </summary>
        /// <param name="pagination">分页参数</param>
        /// <param name="searchParams">查询参数</param>
        /// <param name="isBatchAudit">是否允许批量审核</param>
        /// <returns></returns>
        [NotNull]
        public async Task<PageInfo<List<Repository.Domain.WFTask>>> GetMyUncompletedPageList1(PageReq pageReq,
            WFProcessSearchDto searchParams, string category, bool isBatchAudit = false)
        {
            RefAsync<int> totalCount = 0;
            var userId = _auth.GetUserId();
            var schemeCode = _configuration.GetSection("AppSetting:DroneCaseInfoSchemeCode").Value;
            var expression = Expressionable.Create<Repository.Domain.WFTask>()
                //.And(t => t.UserId == userId)
                .And(t => t.State == 1)
                .And(t => t.Type != 2)
                .AndIF(!string.IsNullOrEmpty(searchParams.Keyword),
                    t => t.ProcessTitle.Contains(searchParams.Keyword) || t.UnitName.Contains(searchParams.Keyword))
                .AndIF(!string.IsNullOrEmpty(searchParams.Code), t => t.ProcessCode == searchParams.Code)
                .AndIF(searchParams.StartDate != null && searchParams.EndDate != null,
                    t => t.CreateDate >= searchParams.StartDate && t.CreateDate <= searchParams.EndDate)
                .AndIF(isBatchAudit, t => t.IsBatchAudit == 1);


            var list = await client.Queryable<Repository.Domain.WFTask>()
                .Where(expression.ToExpression())
                .LeftJoin<WFTaskUser>((t, u) => t.Id == u.TaskId && u.UserId == userId)
                .Where((t, u) => u.UserId == userId || t.UserId == userId)
                .LeftJoin<WFProcess>((t, u, p) => t.ProcessId == p.Id)
                .LeftJoin<WFScheme>((t, u, p, s) => p.SchemeId == s.Id)
                .LeftJoin<WFSchemeInfo>((t, u, p, s, i) => s.SchemeInfoId == i.Id)
                .LeftJoin<DroneCaseInfoSingle>((t, u, p, s, i, d) =>
                    SqlFunc.JsonField(p.InstanceInfo, "pkeyValue") == d.Id)
                .Where((t, u, p, s, i, d) => p.SchemeCode.Equals(schemeCode))
                .WhereIF(!string.IsNullOrEmpty(searchParams.CaseNo),
                    (t, u, p, s, i, d) => d.case_no.Contains(searchParams.CaseNo))
                .WhereIF(!string.IsNullOrEmpty(searchParams.TypeId),
                    (t, u, p, s, i, d) => d.typeid.Equals(searchParams.TypeId))
                .WhereIF(searchParams.IsDrawback != null,
                    (t, u, p, s, i, d) => d.is_drawback.Equals(searchParams.IsDrawback))
                .WhereIF(searchParams.IsIllegal != null,
                    (t, u, p, s, i, d) => d.is_illegal.Equals(searchParams.IsIllegal))
                .WhereIF(searchParams.IsVerification != null,
                    "d.is_verification  ='" + searchParams.IsVerification + "'")
                .WhereIF(!string.IsNullOrEmpty(category), (t, u, p, s, i) => i.Category == category)
                .OrderByDescending((t, u, p, s, i) => t.CreateDate)
                .Select((t, u, p, s, i, d) => new Repository.Domain.WFTask()
                {
                    Id = t.Id.SelectAll(),
                    SchemeContent = s.Content,
                    InstanceInfo = p.InstanceInfo,
                    IsDrawback = d.is_drawback
                })
                .ToPageListAsync(pageReq.page, pageReq.limit, totalCount);
            // 遍历补充信息 
            foreach (var wfTask in list)
            {
                // 获取表单数据
                var unitId = wfTask.UnitId; // 当前节点id
                //var process = await _processApp.GetEntity(wfTask.ProcessId);
                //var scheme = await _schemeInfoApp.GetSchemeEntity(process.SchemeId);
                //var　content = (JObject)JsonConvert.DeserializeObject(scheme.Content);
                var content = (JObject)JsonConvert.DeserializeObject(wfTask.SchemeContent);

                var wfData = (JArray)content["wfData"];
                //
                var instanceInfo = wfTask.InstanceInfo;
                var processId = instanceInfo.pkeyValue; // 数据记录id
                var pkey = instanceInfo.pkey;
                foreach (var jToken in wfData)
                {
                    var id = jToken["id"]?.ToString();
                    if (id != null && id.Equals(unitId))
                    {
                        var first = jToken;
                        // fromVersion 为 schemeId
                        var formVersion = first["formVerison"]?.ToString();
                        if (!string.IsNullOrEmpty(formVersion))
                        {
                            var authFields = (JArray)jToken["authFields"];
                            var showFields = new Dictionary<string, ExtendInfo>();
                            foreach (var authField in authFields)
                            {
                                var label = authField["label"].ToString();
                                var field = authField["field"].ToString();
                                var fieldName = authField["fieldName"]?.ToString();
                                if (authField["upShow"].ToBool().Equals(true))
                                {
                                    showFields.Add(field,
                                        new ExtendInfo() { Field = field, Label = label, FieldName = fieldName });
                                }
                            }

                            var sql = "select ";
                            var selectFields = "";
                            foreach (var showField in showFields)
                            {
                                selectFields += $"\"{showField.Value.FieldName}\"" + " as " + showField.Value.Field +
                                                ",";
                            }

                            selectFields = selectFields.TrimEnd(',');

                            var formScheme = await _formSchemeApp.GetScheme(formVersion);
                            FormSchemeNewModel formSchemeModel = formScheme.Scheme.ToObject<FormSchemeNewModel>();
                            FormDbTableInfo mainTable = formSchemeModel.Db.Find(t => t.Type == "main");
                            sql += selectFields + $" FROM \"{mainTable.Name}\" t where \"{pkey}\" = @Id";

                            var dataList = await client.Ado.GetDataTableAsync(sql, new { Id = processId });

                            //  实现一个新的查询方法
                            //   var dataList = await _formSchemeApp.GetFormDataNew(formVersion, "Id", processId);
                            // var data = dataList.FirstOrDefault().Value;
                            // 实际只有一行数据
                            foreach (DataRow dataRow in dataList.Rows)
                            {
                                foreach (var showField in showFields)
                                {
                                    var field = showField.Key;
                                    var value = dataRow[field];
                                    showField.Value.Value = value;
                                }
                            }

                            wfTask.ExtendInfo = showFields.Values;
                        }
                    }
                }

                wfTask.SchemeContent = null;
                //wfTask.InstanceInfo = null;
            }

            return new PageInfo<List<Repository.Domain.WFTask>>
            {
                Items = list,
                Total = totalCount
            };
        }

        /// <summary>
        /// 获取我的已办任务列表
        /// </summary>
        /// <param name="pagination">分页参数</param>
        /// <param name="searchParams">查询参数</param>
        /// <returns></returns>
        public async Task<PageInfo<List<Repository.Domain.WFTask>>> GetMyCompletedPageList(PageReq pageReq,
            WFProcessSearchDto searchParams, string category)
        {
            RefAsync<int> totalCount = 0;
            var userId = _auth.GetUserId();

            var queryable = client.Queryable<Repository.Domain.WFTask>()
                .LeftJoin<WFTaskLog>((t, t1) => t.Id == t1.TaskId)
                .LeftJoin<WFProcess>((t, t1, t2) => t.ProcessId == t2.Id)
                .LeftJoin<WFScheme>((t, t1, t2, t3) => t2.SchemeId == t3.Id)
                .LeftJoin<WFSchemeInfo>((t, t1, t2, t3, t4) => t3.SchemeInfoId == t4.Id);
            var exp = Expressionable.Create<Repository.Domain.WFTask, WFTaskLog>()
                .And((t, t1) => t1.IsLast == 1)
                .And((t, t1) => t.State == 3 || t.State == 5)
                .And((t, t1) => t.Type == 1 || t.Type == 3 || t.Type == 5 || t.Type == 6 || t.Type == 7)
                .And((t, t1) => t.UserId == userId || t1.UserId == userId)
                .AndIF(!string.IsNullOrEmpty(searchParams.Keyword),
                    (t, t1) => t.ProcessTitle.Contains(searchParams.Keyword) ||
                               t.UnitName.Contains(searchParams.Keyword))
                .AndIF(!string.IsNullOrEmpty(searchParams.Code), (t, t1) => t.ProcessCode == searchParams.Code)
                .AndIF(searchParams.StartDate != null && searchParams.EndDate != null,
                    (t, t1) => t.CreateDate >= searchParams.StartDate && t.CreateDate <= searchParams.EndDate)
                .ToExpression();
            var list = await queryable.Where(exp)
                .WhereIF(!string.IsNullOrEmpty(category), (t, t1, t2, t3, t4) => t4.Category == category).Select(
                    (t, t1, t2, t3, t4) => new Repository.Domain.WFTask()
                    {
                        Id = t.Id,
                        Type = t.Type,
                        ProcessTitle = t.ProcessTitle,
                        ProcessCode = t.ProcessCode,
                        ProcessId = t.ProcessId,
                        ChildProcessId = t.ChildProcessId,
                        ProcessUserId = t.ProcessUserId,
                        ProcessUserName = t.ProcessUserName,
                        Token = t.Token,
                        UnitId = t.UnitId,
                        UnitName = t.UnitName,
                        PrevUnitId = t.PrevUnitId,
                        PrevUnitName = t.PrevUnitName,
                        PrevToken = t.PrevToken,
                        UserId = t.UserId,
                        UserName = t.UserName,
                        UserDepartmentId = t.UserDepartmentId,
                        UserCompanyId = t.UserCompanyId,
                        State = t.State,
                        IsAgree = t.IsAgree,
                        IsLast = t.IsLast,
                        Sort = t.Sort,
                        TimeoutAction = t.TimeoutAction,
                        TimeoutNotice = t.TimeoutNotice,
                        TimeoutInterval = t.TimeoutInterval,
                        TimeoutStrategy = t.TimeoutStrategy,
                        CreateUserId = t.CreateUserId,
                        CreateUserName = t.CreateUserName,
                        IsUrge = t.IsUrge,
                        UrgeTime = t.UrgeTime,
                        FirstId = t.FirstId,
                        IsBatchAudit = t.IsBatchAudit,
                        IsReject = t.IsReject,
                        PrevTaskId = t.PrevTaskId,
                        UpdateTaskId = t.UpdateTaskId,

                        IsCancel = t1.IsCancel,
                        CreateDate = t1.CreateDate,
                        OperationName = t1.OperationName,
                        MakeUserId = t1.UserId,

                        IsFinished = t2.IsFinished
                    }).ToPageListAsync(pageReq.page, pageReq.limit, totalCount);

            return new PageInfo<List<Repository.Domain.WFTask>>
            {
                Items = list,
                Total = totalCount
            };
        }


        /// <summary>
        /// 获取可撤回的任务
        /// </summary>
        /// <param name="pagination">分页参数</param>
        /// <param name="searchParams">查询参数</param>
        /// <returns></returns>
        public PageInfo<List<dynamic>> GetRetractPageList(PageReq pageReq,
            WFProcessSearchDto searchParams, string category)
        {
            int totalCount = 0;
            var userId = _auth.GetUserId();

            var query = client.Queryable<Repository.Domain.WFTask>()
                .Where(t => t.IsLast == 1)
                .Where(t => t.State == 3 || t.State == 5)
                .Where(t => t.Type == 1 || t.Type == 3 || t.Type == 5 || t.Type == 6 || t.Type == 7)
                .Where(t => t.CreateDate != null)
                .WhereIF(!string.IsNullOrEmpty(searchParams.Keyword),
                    t => t.ProcessTitle.Contains(searchParams.Keyword) || t.UnitName.Contains(searchParams.Keyword))
                .WhereIF(!string.IsNullOrEmpty(searchParams.Code), t => t.ProcessCode == searchParams.Code)
                .WhereIF(searchParams.StartDate != null && searchParams.EndDate != null,
                    t => t.CreateDate >= searchParams.StartDate && t.CreateDate <= searchParams.EndDate)
                .Select(t => new
                {
                    index2 = SqlFunc.RowNumber($"{t.CreateDate} desc ", t.ProcessId),
                    ProcessTitle = t.ProcessTitle,
                    UnitId = t.UnitId,
                    Id = t.Id,
                    ProcessId = t.ProcessId,
                    UnitName = t.UnitName,
                    UserId = t.UserId,
                    UserName = t.UserName,
                    State = t.State,
                    CreateDate = t.CreateDate,
                    Type = t.Type,
                    ProcessCode = t.ProcessCode
                })
                .MergeTable()
                .Where(it => it.index2 == 1)
                .LeftJoin<ViewDroneCaseinfoTotal>((r, v) => r.ProcessId == v.Id)
                .Where((r, v) => r.UserId == userId)
                .WhereIF(!string.IsNullOrEmpty(searchParams.CaseNo), (r, v) => v.case_no.Contains(searchParams.CaseNo))
                .OrderByDescending((r, v) => r.CreateDate)
                .Select<dynamic>((r, v) => new
                {
                    r.Id,
                    r.ProcessTitle,
                    r.ProcessId,
                    r.UnitId,
                    r.UnitName,
                    r.UserId,
                    r.UserName,
                    r.State,
                    r.CreateDate,
                    r.Type,
                    r.ProcessCode,
                    v.case_no,
                    v.typename,
                    v.streetname,
                    v.countyname,
                    v.communityname,
                    v.laiyuan,
                    v.handle_status_id,
                    v.handle_status_name
                });
            var result = query.ToPageList(pageReq.page, pageReq.limit);
            totalCount = query.Count();

            return new PageInfo<List<dynamic>>
            {
                Items = result,
                Total = totalCount
            };
        }

        /// <summary>
        /// 获取我的传阅任务列表
        /// </summary>
        /// <param name="pagination">分页参数</param>
        /// <param name="searchParams">查询参数</param>
        /// <returns></returns>
        public async Task<PageInfo<List<Repository.Domain.WFTask>>> GetMyReadPageList(PageReq pageReq,
            WFProcessSearchDto searchParams,
            string category)
        {
            RefAsync<int> totalCount = 0;
            var userId = _auth.GetUserId();

            var expression = Expressionable.Create<Repository.Domain.WFTask>()
                .And(t => t.UserId == userId)
                .And(t => t.Type == 2)
                .AndIF(!string.IsNullOrEmpty(searchParams.Keyword),
                    t => t.ProcessTitle.Contains(searchParams.Keyword) || t.UnitName.Contains(searchParams.Keyword))
                .AndIF(!string.IsNullOrEmpty(searchParams.Code), t => t.ProcessCode == searchParams.Code)
                .AndIF(searchParams.StartDate != null && searchParams.EndDate != null,
                    t => t.CreateDate >= searchParams.StartDate && t.CreateDate <= searchParams.EndDate);


            var list = await client.Queryable<Repository.Domain.WFTask>()
                .Where(expression.ToExpression())
                .LeftJoin<WFProcess>((t, p) => t.ProcessId == p.Id)
                .LeftJoin<WFScheme>((t, p, s) => p.SchemeId == s.Id)
                .LeftJoin<WFSchemeInfo>((t, p, s, i) => s.SchemeInfoId == i.Id)
                .WhereIF(!string.IsNullOrEmpty(category), (t, p, s, i) => i.Category == category)
                .OrderByDescending((t, p, s, i) => t.CreateDate)
                .ToPageListAsync(pageReq.page, pageReq.limit, totalCount);

            return new PageInfo<List<Repository.Domain.WFTask>>
            {
                Items = list,
                Total = totalCount
            };
        }

        /// <summary>
        /// 获取我的委托任务列表
        /// </summary>
        /// <param name="pagination">分页参数</param>
        /// <param name="searchParams">查询参数</param>
        /// <returns></returns>
        public async Task<PageInfo<List<Repository.Domain.WFTask>>> GetMyDelegatePageList(PageReq pageReq,
            WFProcessSearchDto searchParams, string category)
        {
            RefAsync<int> totalCount = 0;

            var pageInfo = new PageInfo<List<Repository.Domain.WFTask>>();

            string userId = _auth.GetUserId();
            DateTime datetime = DateTime.Now;

            var expression = Expressionable.Create<Repository.Domain.WFTask>();
            var delegateList = await client.Queryable<WFDelegateRule>()
                .Where(t => t.ToUserId == userId && t.BeginDate >= datetime && t.EndDate <= datetime && t.Type == 0)
                .ToListAsync();

            if (delegateList.Count == 0)
            {
                pageInfo.Total = 0;
                return pageInfo;
            }


            foreach (var item in delegateList)
            {
                var relationList = await client.Queryable<WFDelegateRelation>()
                    .Where(a => a.DelegateRuleId == item.Id).ToListAsync();
                string relation = "";
                foreach (var relationItem in relationList)
                {
                    relation += $"'{relationItem.SchemeInfoId}'";
                }

                expression = expression.Or(t =>
                    t.UserId == item.CreateUserId && relation.Contains("'" + t.ProcessCode + "'"));
            }

            var exp = Expressionable.Create<Repository.Domain.WFTask>()
                .And(t => t.UserId != userId)
                .And(t => t.State == 1)
                .And(t => t.Type != 2)
                .AndIF(!string.IsNullOrEmpty(searchParams.Keyword),
                    t => t.ProcessTitle.Contains(searchParams.Keyword) || t.UnitName.Contains(searchParams.Keyword))
                .AndIF(!string.IsNullOrEmpty(searchParams.Code), t => t.ProcessCode == searchParams.Code)
                .AndIF(searchParams.StartDate != null && searchParams.EndDate != null,
                    t => t.CreateDate >= searchParams.StartDate && t.CreateDate <= searchParams.EndDate);

            exp = exp.And(expression.ToExpression());

            var list = await client.Queryable<Repository.Domain.WFTask>()
                .Where(expression.ToExpression())
                .LeftJoin<WFProcess>((t, p) => t.ProcessId == p.Id)
                .LeftJoin<WFScheme>((t, p, s) => p.SchemeId == s.Id)
                .LeftJoin<WFSchemeInfo>((t, p, s, i) => s.SchemeInfoId == i.Id)
                .WhereIF(!string.IsNullOrEmpty(category), (t, p, s, i) => i.Category == category)
                .OrderByDescending((t, p, s, i) => t.CreateDate)
                .ToPageListAsync(pageReq.page, pageReq.limit, totalCount);

            return new PageInfo<List<Repository.Domain.WFTask>>
            {
                Items = list,
                Total = totalCount
            };
        }


        /// <summary>
        /// 获取流程任务实体
        /// </summary>
        /// <param name="token">密钥</param>
        /// <param name="userId">用户id</param>
        /// <returns></returns>
        public async Task<Repository.Domain.WFTask> GetEntityByToken(string token, string userId)
        {
            return await base.Repository.GetFirstAsync(t => t.Token == token && t.UserId == userId && t.State == 1);
        }

        /// <summary>
        /// 获取流程任务实体
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <returns></returns>
        public Repository.Domain.WFTask GetEntity(string keyValue)
        {
            return base.Repository.GetFirst(a => a.Id == keyValue);
        }

        /// <summary>
        /// 获取任务关联的用户
        /// </summary>
        /// <param name="keyValue">主键</param> 
        /// <returns></returns>
        public List<string> GetUsers(string keyValue)
        {
            List<string> users = new List<string>();
            var us = client.Queryable<WFTaskUser>().Where(r => r.TaskId == keyValue).ToList();
            if (us.Count > 0)
            {
                users = us.Select(r => r.UserId).ToList();
            }

            return users;
        }

        /// <summary>
        /// 获取任务列表
        /// </summary>
        /// <param name="processId">流程实例主键</param>
        /// <param name="type">任务类型</param>
        /// <param name="prevTaskId">上一个任务Id值</param>
        /// <returns></returns>
        public async Task<IEnumerable<Repository.Domain.WFTask>> GetList(string processId, int type, string prevTaskId)
        {
            return await base.Repository.GetListAsync(t =>
                t.ProcessId == processId && t.Type == type && t.PrevTaskId == prevTaskId);
        }

        /// <summary>
        /// 获取任务列表
        /// </summary>
        /// <param name="processId">流程实例主键</param>
        /// <param name="prevToken">上一个任务token值</param>
        /// <returns></returns>
        public async Task<IEnumerable<Repository.Domain.WFTask>> GetList(string processId, string prevToken)
        {
            return await base.Repository.GetListAsync(t => t.ProcessId == processId && t.PrevToken == prevToken);
        }

        /// <summary>
        /// 获取未完成的任务
        /// </summary>
        /// <param name="processId">流程进程主键</param>
        /// <returns></returns>
        public async Task<IEnumerable<Repository.Domain.WFTask>> GetUnFinishTaskList(string processId)
        {
            return await base.Repository.GetListAsync(t =>
                t.ProcessId == processId && t.State == 1 && (t.Type == 1 || t.Type == 2 || t.Type == 3 || t.Type == 4 ||
                                                             t.Type == 5 || t.Type == 6 || t.Type == 7));
        }

        /// <summary>
        /// 获取等待任务列表（用于网关判断是否所有支路都执行完毕）
        /// </summary>
        /// <param name="processId">流程实例Id</param>
        /// <param name="unitId">流程单元节点Id</param>
        /// <returns></returns>
        public async Task<IEnumerable<Repository.Domain.WFTask>> GetAwaitTaskList(string processId, string unitId)
        {
            return await base.Repository.GetListAsync(t =>
                t.ProcessId == processId && t.UnitId == unitId && t.Type == 21 && t.State == 1);
        }

        /// <summary>
        /// 获取最近的任务
        /// </summary>
        /// <param name="processId">流程实例Id</param>
        /// <param name="unitId">流程单元节点Id</param>
        /// <returns></returns>
        public async Task<IEnumerable<Repository.Domain.WFTask>> GetLastTaskList(string processId, string unitId)
        {
            return await client.Queryable<Repository.Domain.WFTask>()
                .Where(t => t.ProcessId == processId && t.UnitId == unitId && t.IsLast == 1 &&
                            (t.Type == 1 || t.Type == 3 || t.Type == 4 || t.Type == 5 || t.Type == 7))
                .OrderBy(t => t.Sort)
                .ToListAsync();
        }

        /// <summary>
        /// 获取最近的不是驳回产生的任务
        /// </summary>
        /// <param name="processId">流程实例Id</param>
        /// <param name="unitId">流程单元节点Id</param>
        /// <returns></returns>
        public Task<Repository.Domain.WFTask> GetLastNotRejectTask(string processId, string unitId)
        {
            return null;
        }

        /// <summary>
        /// 获取最近的完成任务
        /// </summary>
        /// <param name="processId">流程实例Id</param>
        /// <param name="unitId">流程单元节点Id</param>
        /// <returns></returns>
        public async Task<IEnumerable<Repository.Domain.WFTask>> GetLastFinishTaskList(string processId, string unitId)
        {
            return await base.Repository.GetListAsync(t =>
                t.ProcessId == processId && t.UnitId == unitId && (t.Type == 1 || t.Type == 7) && t.IsLast == 1 &&
                t.State == 3);
        }

        /// <summary>
        /// 获取完成任务
        /// </summary>
        /// <param name="processId">流程实例Id</param>
        /// <returns></returns>
        public async Task<IEnumerable<Repository.Domain.WFTask>> GetFinishTaskList(string processId, List<string> ids)
        {
            return await base.Repository.GetListAsync(t => t.ProcessId == processId && !ids.Contains(t.Id));
        }

        /// <summary>
        /// 获取节点任务的最大人数
        /// </summary>
        /// <param name="processId">流程实例Id</param>
        /// <param name="unitId">流程单元节点Id</param>
        /// <returns></returns>
        public Task<int> GetTaskUserMaxNum(string processId, string unitId)
        {
            return null;
        }

        /// <summary>
        /// 保存任务
        /// </summary>
        /// <param name="wfTaskEntity">任务日志</param>
        public async Task<Response<bool>> Add(Repository.Domain.WFTask wfTaskEntity)
        {
            wfTaskEntity.CreateDate = DateTime.Now;
            wfTaskEntity.CreateUserId = _auth.GetUserId();
            wfTaskEntity.CreateUserName = _auth.GetUserName();
            wfTaskEntity.Id = Guid.NewGuid().ToString();
            wfTaskEntity.IsLast = 1;

            var flag = await base.Repository.InsertAsync(wfTaskEntity);

            return new Response<bool>
            {
                Result = flag,
                Message = flag == true ? "success" : "error"
            };
        }

        /// <summary>
        /// 更新任务状态
        /// </summary>
        /// <param name="processId"></param>
        /// <param name="unitId"></param>
        /// <returns></returns>
        public async Task<Response<bool>> Update(string processId, string unitId)
        {
            var flag = await base.Repository.UpdateSetColumnsTrueAsync(a => new Repository.Domain.WFTask { IsLast = 0 },
                a => a.ProcessId == processId && a.UnitId == unitId);
            return new Response<bool>
            {
                Result = flag,
                Message = flag == true ? "success" : "error"
            };
        }

        /// <summary>
        /// 更新任务
        /// </summary>
        /// <param name="wfTaskEntity">任务日志</param>
        public Response<bool> Update(Repository.Domain.WFTask wfTaskEntity)
        {
            var flag = base.Repository.Update(wfTaskEntity);

            return new Response<bool>
            {
                Result = flag,
                Message = flag == true ? "success" : "error"
            };
        }

        /// <summary>
        /// 关闭任务
        /// </summary>
        /// <param name="processId">流程主键</param>
        /// <param name="token">任务令牌</param>
        /// <param name="taskId">任务id（除去该任务不关闭）</param>
        /// <returns></returns>
        public async Task<Response<bool>> CloseTask(string processId, string token, string taskId = "")
        {
            var expression = Expressionable.Create<Repository.Domain.WFTask>()
                .And(t => t.ProcessId == processId && t.Token == token)
                .AndIF(!string.IsNullOrEmpty(taskId), t => t.Id != taskId).ToExpression();

            var flag = await base.Repository.UpdateSetColumnsTrueAsync(t => new Repository.Domain.WFTask { State = 4 },
                expression);
            return new Response<bool>
            {
                Result = flag,
                Message = flag == true ? "success" : "error"
            };
        }

        /// <summary>
        /// 关闭任务
        /// </summary>
        /// <param name="processId">流程进程</param>
        /// <param name="unitId">单元节点id</param>
        /// <param name="type">任务类型</param>
        /// <param name="taskId">任务id</param>
        /// <returns></returns>
        public async Task<Response<bool>> CloseTask(string processId, string unitId, int type, string taskId)
        {
            var flag = await base.Repository.UpdateSetColumnsTrueAsync(
                t => new Repository.Domain.WFTask { State = 4, UpdateTaskId = taskId },
                t => t.ProcessId == processId && t.UnitId == unitId && t.Type == type);
            return new Response<bool>
            {
                Result = flag,
                Message = flag == true ? "success" : "error"
            };
        }

        /// <summary>
        /// 打开任务
        /// </summary>
        /// <param name="processId">流程进程</param>
        /// <param name="unitId">单元节点id</param>
        /// <param name="type">任务类型</param>
        /// <param name="taskId">任务id</param>
        /// <returns></returns>
        public async Task<Response<bool>> OpenTask(string processId, string unitId, int type, string taskId)
        {
            var flag = await base.Repository.UpdateSetColumnsTrueAsync(
                t => new Repository.Domain.WFTask { State = 1, UpdateTaskId = taskId },
                t => t.ProcessId == processId && t.UnitId == unitId && t.Type == type);
            return new Response<bool>
            {
                Result = flag,
                Message = flag == true ? "success" : "error"
            };
        }

        /// <summary>
        /// 删除任务
        /// </summary>
        /// <param name="processId">流程进程</param>
        /// <returns></returns>
        public async Task<Response<bool>> Delete(string processId)
        {
            var flag = await base.Repository.DeleteAsync(t => t.ProcessId == processId);
            return new Response<bool>
            {
                Result = flag,
                Message = flag == true ? "success" : "error"
            };
        }

        /// <summary>
        /// 删除任务
        /// </summary>
        /// <param name="processId">流程进程</param>
        /// <param name="prevTaskId">来源任务ID</param>
        /// <returns></returns>
        public async Task<Response<bool>> Delete(string processId, string prevTaskId)
        {
            var flag = await base.Repository.DeleteAsync(t => t.ProcessId == processId && t.PrevTaskId == prevTaskId);
            return new Response<bool>
            {
                Result = flag,
                Message = flag == true ? "success" : "error"
            };
        }

        /// <summary>
        /// 删除任务
        /// </summary>
        /// <param name="id">任务主键</param>
        /// <returns></returns>
        public async Task<Response<bool>> DeleteByFirstId(string id)
        {
            var flag = await base.Repository.DeleteAsync(t => t.FirstId == id);
            return new Response<bool>
            {
                Result = flag,
                Message = flag == true ? "success" : "error"
            };
        }

        /// <summary>
        /// 作废任务
        /// </summary>
        /// <param name="processId">流程进程</param>
        /// <returns></returns>
        public async Task<Response<bool>> VirtualDelete(string processId)
        {
            var flag = await base.Repository.UpdateSetColumnsTrueAsync(t => new Repository.Domain.WFTask { State = 7 },
                t => t.ProcessId == processId && t.State == 1);
            return new Response<bool>
            {
                Result = flag,
                Message = flag == true ? "success" : "error"
            };
        }

        #endregion

        #region 日志

        /// <summary>
        /// 获取流程进程的任务处理日志
        /// </summary>
        /// <param name="processId">流程进程主键</param>
        /// <returns></returns>
        public async Task<List<WFTaskLog>> GetLogList(string processId)
        {
            return await client.Queryable<WFTaskLog>().Where(a => a.ProcessId == processId).OrderBy(r => r.CreateDate)
                .ToListAsync();
        }

        /// <summary>
        /// 获取任务日志列表
        /// </summary>
        /// <param name="processId">流程实例Id</param>
        /// <param name="unitId">流程单元节点Id</param>
        /// <returns></returns>
        public async Task<IEnumerable<WFTaskLog>> GetLogList(string processId, string unitId)
        {
            return await client.Queryable<WFTaskLog>().Where(a => a.ProcessId == processId && a.UnitId == unitId)
                .OrderByDescending(t => t.CreateDate).ToListAsync();
        }

        /// <summary>
        /// 获取任务日志列表
        /// </summary>
        /// <param name="taskId">任务Id</param>
        /// <returns></returns>
        public async Task<WFTaskLog> GetLogEntity(string taskId)
        {
            return await client.Queryable<WFTaskLog>().Where(t => t.TaskId == taskId).FirstAsync();
        }

        /// <summary>
        /// 更新任务日志状态为不是最近处理的
        /// </summary>
        /// <param name="processId"></param>
        /// <param name="unitId"></param>
        /// <returns></returns>
        public async Task<Response<bool>> UpdateLog(string processId, string unitId)
        {
            var userId = _auth.GetUserId();
            var count = await client.Updateable<WFTaskLog>()
                .SetColumns(a => new WFTaskLog() { IsLast = 0 })
                .Where(a => a.ProcessId == processId && a.UnitId == unitId && a.IsLast == 1 && a.UserId == userId)
                .ExecuteCommandAsync();
            return new Response<bool>
            {
                Result = count > 0,
                Message = count > 0 ? "success" : "error"
            };
        }


        /// <summary>
        /// 关闭任务日志撤销
        /// </summary>
        /// <param name="processId">流程主键</param>
        /// <param name="taskId">任务主键</param>
        /// <returns></returns>
        public async Task<Response<bool>> CloseTaskLogCancel(string processId, string taskId)
        {
            var count = await client.Updateable<WFTaskLog>()
                .SetColumns(a => new WFTaskLog() { IsCancel = 0 })
                .Where(a => a.ProcessId == processId && a.TaskId == taskId)
                .ExecuteCommandAsync();
            return new Response<bool>
            {
                Result = count > 0,
                Message = count > 0 ? "success" : "error"
            };
        }

        /// <summary>
        /// 关闭任务日志撤销
        /// </summary>
        /// <param name="taskId">流程任务Id</param>
        /// <returns></returns>
        public async Task<Response<bool>> CloseTaskLogCancel(string taskId)
        {
            var count = await client.Updateable<WFTaskLog>()
                .SetColumns(a => new WFTaskLog() { IsCancel = 0 })
                .Where(a => a.TaskId == taskId)
                .ExecuteCommandAsync();
            return new Response<bool>
            {
                Result = count > 0,
                Message = count > 0 ? "success" : "error"
            };
        }


        /// <summary>
        /// 保存任务日志
        /// </summary>
        /// <param name="wfTaskLogEntity">任务日志</param>
        public async Task<Response<bool>> AddLog(WFTaskLog wfTaskLogEntity)
        {
            wfTaskLogEntity.CreateDate = DateTime.Now;
            wfTaskLogEntity.UserId = _auth.GetUserId();
            wfTaskLogEntity.UserName = _auth.GetUserNickName();
            wfTaskLogEntity.Id = Guid.NewGuid().ToString();
            var count = await client.Insertable(wfTaskLogEntity).ExecuteCommandAsync();
            return new Response<bool>
            {
                Result = count > 0,
                Message = count > 0 ? "success" : "error"
            };
        }

        /// <summary>
        /// 删除任务日志
        /// </summary>
        /// <param name="processId">流程进程</param>
        /// <returns></returns>
        public async Task<Response<bool>> DeleteLog(string processId)
        {
            var count = await client.Deleteable<WFTaskLog>()
                .Where(a => a.ProcessId == processId)
                .ExecuteCommandAsync();
            return new Response<bool>
            {
                Result = count > 0,
                Message = count > 0 ? "success" : "error"
            };
        }

        /// <summary>
        /// 删除任务日志
        /// </summary>
        /// <param name="processId">流程进程</param>
        /// <param name="token">来源任务密钥</param>
        /// <returns></returns>
        public async Task<Response<bool>> DeleteLog(string processId, string taskId)
        {
            var count = await client.Deleteable<WFTaskLog>()
                .Where(a => a.ProcessId == processId && a.TaskId == taskId && a.IsLast == 1)
                .ExecuteCommandAsync();
            return new Response<bool>
            {
                Result = count > 0,
                Message = count > 0 ? "success" : "error"
            };
        }

        /// <summary>
        /// 删除任务日志
        /// </summary>
        /// <param name="taskId">任务主键</param>
        /// <returns></returns>
        public async Task<Response<bool>> DeleteLogByTaskId(string taskId)
        {
            var count = await client.Deleteable<WFTaskLog>()
                .Where(a => a.TaskId == taskId)
                .ExecuteCommandAsync();
            return new Response<bool>
            {
                Result = count > 0,
                Message = count > 0 ? "success" : "error"
            };
        }

        #endregion

        #region 根据案件id，查询当前应该执行的任务

        public async Task<dynamic> GetTaskByCaseId(string caseid)
        {
            var x = await client.Queryable<Repository.Domain.WFTask>().Where(t => t.ProcessId == caseid && t.Type == 7).FirstAsync();
            var code = x.ProcessCode;
            if (code.Equals("0000001")) // 违法用地
            {
                var info = await client.Queryable<Repository.Domain.WFTask>()
                    .Where(t => t.ProcessId == caseid &&
                                (t.Type == 1 || t.Type == 3 || t.Type == 4 || t.Type == 5 || t.Type == 7))
                    .LeftJoin<DroneCaseInfoSingle>((t, r) => t.ProcessId == r.Id)
                    .OrderByDescending((t, r) => t.CreateDate)
                    .Select<dynamic>((t, r) => new
                    {
                        taskid = t.Id,
                        handle_status_id = r.handle_status_id,
                        handle_status_name = r.handle_status_name
                    })
                    .FirstAsync();
                return info;
            }
            else  // 0000004 // 耕地非粮
            {
                var info = await client.Queryable<Repository.Domain.WFTask>()
                    .Where(t => t.ProcessId == caseid &&
                                (t.Type == 1 || t.Type == 3 || t.Type == 4 || t.Type == 5 || t.Type == 7))
                    .LeftJoin<DroneCaseInfoFLH>((t, r) => t.ProcessId == r.Id)
                    .OrderByDescending((t, r) => t.CreateDate)
                    .Select<dynamic>((t, r) => new
                    {
                        taskid = t.Id,
                        handle_status_id = r.handle_status_id,
                        handle_status_name = r.handle_status_name
                    })
                    .FirstAsync();
                return info;
            }
        }

        #endregion

        public Repository.Domain.WFTask GetNodeByProcessId(string id)
        {
            return Repository.GetFirst(a => a.ProcessId == id);
        }

        public void OriginalAdd(Repository.Domain.WFTask node)
        {
            Repository.AsInsertable(node).IgnoreColumnsNull().ExecuteCommand();
        }

        #region 地类类型修改

        /// <summary>
        /// 修改地类类型（仅限农用地到建设用地，待接收状态）
        /// </summary>
        /// <param name="caseno">案件编号</param>
        /// <returns></returns>
        public async Task<Response<bool>> UpdateCaseinfoTypeKC(string caseno)
        {
            var _user = _auth.GetCurrentUser().User;
            //查询案件信息，Log备份用
            var info = client.Queryable<DroneCaseInfoSingle>()
                .Where(t => t.case_no == caseno && t.is_closed != 1 && t.is_intact != 99).First();
            string id = info.Id;
            var task = base.Repository.GetList(t => t.ProcessId == id);
            var tasklog = client.Queryable<WFTaskLog>().Where(t => t.ProcessId == id).ToList();
            var data = new ChangeType
            {
                info = info,
                task = task,
                tasklog = tasklog
            };

            //修改相关信息
            using (var uow = base.UnitWork.CreateContext())
            {
                //删除任务和日志
                await uow.WFTask.DeleteAsync(r =>
                    r.ProcessId == id && (r.PrevToken != "create" || r.PrevToken == null));
                await uow.WFTaskLog.DeleteAsync(r =>
                    r.ProcessId == id && (r.OperationCode != "create" || r.OperationCode == null));
                //修改任务和日志信息
                await uow.WFTask.UpdateAsync(r => new Repository.Domain.WFTask
                {
                    UnitId = "Activity_0xf785z",
                    UnitName = "待接收",
                    State = 1
                }, r => r.ProcessId == id && r.PrevToken == "create");
                await uow.WFTaskLog.UpdateAsync(r => new WFTaskLog
                {
                    UnitId = "Event_0li55cb",
                    UnitName = "开始节点"
                }, r => r.ProcessId == id && r.OperationCode == "create");
                //修改图斑信息
                await uow.DroneCaseInfoSingle.UpdateAsync(r => new DroneCaseInfoSingle
                {
                    typeid = "1ca0f898-a4c5-4e45-9505-46160a16dfbf",
                    typename = "建设用地",
                    handle_status_id = 0,
                    handle_status_name = "待接收",
                    is_illegal = 1
                }, r => r.Id == id);
                var flag = uow.Commit();

                //添加日志
                if (flag)
                {
                    AddDroneCaseLog(new DroneCaseOperationLog
                    {
                        request_data = Json.ToJson(data), description = "UpdateCaseinfoTypeKC", caseid = id,
                        createuserid = _user.Id.ToString(), createusername = _user.Name
                    });
                }

                //返回结果
                return new Response<bool>
                {
                    Result = flag,
                    Message = flag == true ? "success" : "error"
                };
            }
        }

        /// <summary>
        /// 添加操作案件日志
        /// </summary>
        /// <param name="db"></param>
        /// <param name="model"></param>
        public void AddDroneCaseLog(DroneCaseOperationLog model)
        {
            model.Id = SqlSugar.SnowFlakeSingle.instance.getID().ToString();
            model.createtime = DateTime.Now;
            client.Insertable(model).ExecuteCommand();
        }

        /// <summary>
        /// 获取任务列表--地类类型修改
        /// </summary>
        /// <param name="processId">流程实例主键</param>
        /// <returns></returns>
        public async Task<List<Repository.Domain.WFTask>> GetTaskList(string processId)
        {
            return await client.Queryable<Repository.Domain.WFTask>().Where(t => t.ProcessId == processId)
                .OrderByDescending(r => r.CreateDate).ToListAsync();
        }

        /// <summary>
        /// 删除任务--地类类型修改
        /// </summary>
        /// <param name="processId">流程进程</param>
        /// <returns></returns>
        public async Task<Response<bool>> DeleteTaskByIds(string ids)
        {
            var _user = _auth.GetCurrentUser().User;
            string[] taskIds = ids.Split(',');
            var data = await base.Repository.GetListAsync(t => taskIds.Contains(t.Id));
            var flag = await base.Repository.DeleteAsync(t => taskIds.Contains(t.Id));
            if (flag == true)
            {
                AddDroneCaseLog(new DroneCaseOperationLog
                {
                    request_data = Json.ToJson(data), description = "UpdateCaseinfoType--DeleteTaskByIds",
                    caseid = data[0].ProcessId, createuserid = _user.Id.ToString(), createusername = _user.Name
                });
            }

            return new Response<bool>
            {
                Result = flag,
                Message = flag == true ? "success" : "error"
            };
        }

        /// <summary>
        /// 获取任务日志列表--地类类型修改使用
        /// </summary>
        /// <param name="processId">流程实例主键</param>
        /// <returns></returns>
        public async Task<List<WFTaskLog>> GetTaskLogList(string processId)
        {
            return await client.Queryable<WFTaskLog>().Where(t => t.ProcessId == processId)
                .OrderByDescending(r => r.CreateDate).ToListAsync();
        }

        /// <summary>
        /// 删除任务--地类类型修改
        /// </summary>
        /// <param name="processId">流程进程</param>
        /// <returns></returns>
        public async Task<Response<bool>> DeleteTaskLogByIds(string ids)
        {
            var _user = _auth.GetCurrentUser().User;
            string[] taskIds = ids.Split(',');
            using (var uow = base.UnitWork.CreateContext())
            {
                var data = uow.WFTaskLog.AsQueryable().Where(r => taskIds.Contains(r.Id)).ToList();
                await uow.WFTaskLog.DeleteAsync(r => taskIds.Contains(r.Id));
                var flag = uow.Commit();
                if (flag)
                {
                    AddDroneCaseLog(new DroneCaseOperationLog
                    {
                        request_data = Json.ToJson(data), description = "UpdateCaseinfoType--DeleteTaskLogByIds",
                        caseid = data[0].ProcessId, createuserid = _user.Id.ToString(), createusername = _user.Name
                    });
                }

                return new Response<bool>
                {
                    Result = flag,
                    Message = flag == true ? "success" : "error"
                };
            }
        }

        /// <summary>
        /// 更新任务
        /// </summary>
        /// <param name="wfTaskEntity">任务</param>
        public async Task<Response<bool>> UpdateTask(Repository.Domain.WFTask wfTaskEntity)
        {
            var _user = _auth.GetCurrentUser().User;

            //获取数据 
            using (var uow = base.UnitWork.CreateContext())
            {
                var data = uow.WFTask.AsQueryable().Where(r => r.Id == wfTaskEntity.Id).ToList();
                await uow.WFTask.UpdateAsync(wfTaskEntity);
                var flag = uow.Commit();
                if (flag)
                {
                    AddDroneCaseLog(new DroneCaseOperationLog
                    {
                        request_data = Json.ToJson(data), description = "UpdateCaseinfoType--UpdateTask",
                        caseid = wfTaskEntity.ProcessId, createuserid = _user.Id.ToString(), createusername = _user.Name
                    });
                }

                return new Response<bool>
                {
                    Result = flag,
                    Message = flag == true ? "success" : "error"
                };
            }
        }

        /// <summary>
        /// 更新任务日志
        /// </summary>
        /// <param name="wfTaskEntity">任务日志</param>
        public async Task<Response<bool>> UpdateTaskLog(WFTaskLog wfTasklogEntity)
        {
            var _user = _auth.GetCurrentUser().User;
            //获取数据 
            using (var uow = base.UnitWork.CreateContext())
            {
                var data = uow.WFTaskLog.AsQueryable().Where(r => r.Id == wfTasklogEntity.Id).ToList();
                await uow.WFTaskLog.UpdateAsync(wfTasklogEntity);
                var flag = uow.Commit();
                if (flag)
                {
                    AddDroneCaseLog(new DroneCaseOperationLog
                    {
                        request_data = Json.ToJson(data), description = "UpdateCaseinfoType--UpdateTaskLog",
                        caseid = wfTasklogEntity.ProcessId, createuserid = _user.Id.ToString(),
                        createusername = _user.Name
                    });
                }

                return new Response<bool>
                {
                    Result = flag,
                    Message = flag == true ? "success" : "error"
                };
            }
        }

        #endregion
    }
}