using AutoMapper;
using EnumsNET;
using Microsoft.VisualBasic;
using NPOI.SS.Formula.Functions;
using OASystem.Domain;
using OASystem.Domain.Dtos.PersonnelModule;
using OASystem.Domain.Entities.Groups;
using OASystem.Domain.Entities.PersonnelModule;
using OASystem.Domain.Entities.System;
using OASystem.Domain.ViewModels.PersonnelModule;
using Org.BouncyCastle.Ocsp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OASystem.Infrastructure.Repositories.PersonnelModule
{
    /// <summary>
    /// 任务分配
    /// 仓库
    /// </summary>
    public class TaskAllocationRepository : BaseRepository<Pm_TaskAllocation, TaskAllocationView>
    {
        private readonly IMapper _mapper;
        private Result _result;

        public TaskAllocationRepository(SqlSugarClient sqlSugar, IMapper mapper)
            : base(sqlSugar)
        {
            _mapper = mapper;
            _result = new Result() { Code = -1, Msg = "操作失败!" };
        }

        /// <summary>
        /// 任务操作权限(任务创建人才可以进行操作)
        /// </summary>
        /// <param name="taskAllocation"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public TaskOperationAudit _TaskOperationAudit(Pm_TaskAllocation taskAllocation, int userId)
        {
            TaskOperationAudit taskOperationAudit = new TaskOperationAudit();
            if (taskAllocation.CreateUserId == userId)
            {
                taskOperationAudit.TaskAddAudit = 1;
                taskOperationAudit.TaskDelAudit = 1;
                taskOperationAudit.TasStopAudit = 1;
                taskOperationAudit.TaskComfirmAudit = 1;
                taskOperationAudit.TaskScoreAudit = 1;
            }

            return taskOperationAudit;
        }

        /// <summary>
        /// 基础数据源
        /// </summary>
        /// <returns></returns>
        public async Task<Result> _Init(int portType, int userId)
        {
            if (portType == 1 || portType == 2 || portType == 3)
            {
                if (userId < 1)
                {
                    _result.Msg = string.Format("请传入有效的UserId参数!");
                    return _result;
                }

                //任务名称
                List<string> _TaskNameInfos = new List<string>();
                _TaskNameInfos = _sqlSugar.Queryable<Pm_TaskAllocation, Pm_TaskRelevanceUser>((ta, tau) => new JoinQueryInfos(JoinType.Left, ta.Id == tau.TAId))
                                          .Where((ta, tau) => ta.IsDel == 0 && tau.IsDel == 0)
                                          .Where((ta, tau) => ta.CreateUserId == userId || tau.UserId == userId)
                                          .Select(ta => ta.TaskName).ToList()
                                          .Distinct().ToList();

                //团组名称
                List<ValueInfo> _GroupNameInfos = new List<ValueInfo>();
                _GroupNameInfos = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0)
                                                                           .OrderByDescending(it => it.CreateTime)
                                                                           .Select(it => new ValueInfo { Id = it.Id, Name = it.TeamName })
                                                                           .ToList();
                _GroupNameInfos.Insert(0, new ValueInfo() { Id = -1, Name = "未选择" });
                //部门名称
                ValueInfo _DepartmentNameInfos = new ValueInfo();
                _DepartmentNameInfos = _sqlSugar.Queryable<Sys_Users, Sys_Department>((u, d) => new JoinQueryInfos(JoinType.Left, u.DepId == d.Id))
                                                .Select((u, d) => new ValueInfo() { Id = d.Id, Name = d.DepName })
                                                .First();

                //执行任务人员信息 1 公司总经理/副总 可分配 所有人的任务 2 公司 部门经理/主管 可分配 部门下的人员的任务
                List<ExecuteTaskUserInfo> _ExecuteTaskUserInfos = new List<ExecuteTaskUserInfo>();
                TaskOperationAudit _TaskOpertionAudit = new TaskOperationAudit();
                List<Pm_TaskJobRelevancy> taskAudits = new List<Pm_TaskJobRelevancy>();
                taskAudits = _sqlSugar.Queryable<Pm_TaskJobRelevancy>().Where(it => it.IsDel == 0 && it.PrimaryUserId == userId).ToList();

                if (taskAudits.Count > 0)
                {
                    //任务权限
                    _TaskOpertionAudit.TaskAddAudit = 1;
                    _TaskOpertionAudit.TaskDelAudit = 1;
                    _TaskOpertionAudit.TasStopAudit = 1;

                    List<int> userIds = taskAudits.Select(it => it.SubUserId).ToList();
                    string userSql = string.Format(@"Select u.Id,u.CnName As Name,c.CompanyName,
                                                         d.DepName As DepartmentName,jp.JobName
                                                         From Sys_Users u
                                                         Left Join Sys_Company c On u.CompanyId = c.Id
                                                         Left Join Sys_Department d On u.DepId = d.Id
                                                         Left Join Sys_JobPost jp On u.JobPostId = jp.Id
                                                         Where u.IsDel = 0 ");
                    _ExecuteTaskUserInfos = _sqlSugar.SqlQueryable<ExecuteTaskUserInfo>(userSql).Where(it => userIds.Contains(it.Id)).ToList();

                }

                InitView _view = new InitView()
                {
                    TaskOperationAudit = _TaskOpertionAudit,
                    TaskNameInfos = _TaskNameInfos,
                    ExecuteTaskUserInfos = _ExecuteTaskUserInfos,
                    GroupNameInfos = _GroupNameInfos,
                    DepartmentNameInfo = _DepartmentNameInfos
                };
                _result.Code = 0;
                _result.Data = _view;
            }
            else
            {
                _result.Msg = string.Format("请传入有效的PortType参数!");
            }

            return _result;
        }

        /// <summary>
        /// 任务指派
        /// 详情
        /// </summary>
        /// <param name="portType"></param>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<Result> _Details(int portType, int Id)
        {
            if (Id < 1)
            {
                _result.Msg = string.Format("请传入有效的Id参数!");
                return _result;
            }

            if (portType == 1 || portType == 2 || portType == 3)
            {
                //团组名称
                List<ValueInfo> _GroupNameInfos = new List<ValueInfo>();
                _GroupNameInfos = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0)
                                                                           .OrderByDescending(it => it.CreateTime)
                                                                           .Select(it => new ValueInfo { Id = it.Id, Name = it.TeamName })
                                                                           .ToList();
                _GroupNameInfos.Insert(0, new ValueInfo() { Id = -1, Name = "未选择" });
                //部门名称
                List<ValueInfo> _DepartmentNameInfos = new List<ValueInfo>();
                _DepartmentNameInfos = _sqlSugar.Queryable<Sys_Department>()
                                                .Select(d => new ValueInfo() { Id = d.Id, Name = d.DepName })
                                                .ToList();
                //用户名称
                List<ValueInfo> _UserNameInfos = new List<ValueInfo>();
                _UserNameInfos = _sqlSugar.Queryable<Sys_Users>()
                                                .Select(d => new ValueInfo() { Id = d.Id, Name = d.CnName })
                                                .ToList();

                TaskDetailsView _view = _sqlSugar.Queryable<Pm_TaskAllocation>()
                                                 .Where(it => it.IsDel == 0 && it.Id == Id)
                                                 .Select(it => new TaskDetailsView
                                                 {
                                                     Id = it.Id,
                                                     DiId = it.DiId,
                                                     DepId = it.DepId,
                                                     CreateUserId = it.CreateUserId,
                                                     CreateTime = it.CreateTime,
                                                     TaskName = it.TaskName,
                                                     TaskContent = it.TaskContent,
                                                     TaskPriority = it.TaskPriority,
                                                     PredictBeginTime = it.PredictBeginTime,
                                                     PredictEndTime = it.PredictEndTime,
                                                     IsIntoPerformance = it.IsIntoPerformance,
                                                     Remark = it.Remark,
                                                 })
                                                 .First();
                if (_view != null)      
                {
                    List<TaskUserDetailsView> taskUserDetailsViews = new List<TaskUserDetailsView>();

                    taskUserDetailsViews = _sqlSugar.Queryable<Pm_TaskRelevanceUser>()
                                                    .Where(it => it.IsDel == 0 && it.TAId == _view.Id)
                                                    .Select(it => new TaskUserDetailsView
                                                    {
                                                        Id = it.Id,
                                                        TAId = it.TAId,
                                                        UserId = it.UserId,
                                                        BeginTime = it.BeginTime,
                                                        OverTime = it.OverTime,
                                                        TaskStatus = it.TaskStatus,
                                                        Cause = it.Cause,
                                                        Remark = it.Remark
                                                    })
                                                    .ToList();
                    _view.UserTaskInfos = taskUserDetailsViews;

                    _result.Data = _view;
                    _result.Code = 0;
                    _result.Msg = "查询成功!";
                }
            }
            else
            {
                _result.Msg = string.Format("请传入有效的PortType参数!");
            }
            return _result;
        }

        /// <summary>
        /// Add Or Edit
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Result> _AddOrEdit(TaskAllocationAddOrEditDto dto)
        {
            if (dto.PortType == 1 || dto.PortType == 2 || dto.PortType == 3)
            {
                if (dto.UserIds.Count < 1)
                {
                    _result.Msg = string.Format("指派人员不能为空!");
                    return _result;
                }

                #region 参数处理
                Pm_TaskAllocation _TaskAllocation = new Pm_TaskAllocation();
                List<Pm_TaskRelevanceUser> _TaskRelevanceUsers = new List<Pm_TaskRelevanceUser>();
                _TaskAllocation = _mapper.Map<Pm_TaskAllocation>(dto);
                _TaskAllocation.CreateUserId = dto.UserId;
                _TaskAllocation.Status = TaskEnum.NotStarted;
                foreach (var item in dto.UserIds)
                {
                    _TaskRelevanceUsers.Add(new Pm_TaskRelevanceUser() {
                        TAId = dto.Id,
                        UserId = item,
                        TaskStatus = TaskerEnum.NotStarted,
                        CreateUserId = dto.UserId,
                    });
                }

                #endregion

                if (dto.Id == 0) //添加
                {
                    // 1 按 任务名称 查询重
                    Pm_TaskAllocation taskAllocation1 = await _sqlSugar.Queryable<Pm_TaskAllocation>().Where(it => it.IsDel == 0 && it.TaskName.Equals(_TaskAllocation.TaskName)).FirstAsync();
                    if (taskAllocation1 != null)
                    {
                        _result.Msg = string.Format("任务名称重复,请重命名!");
                        return _result;
                    }

                    _sqlSugar.BeginTran();

                    int addId = await _sqlSugar.Insertable<Pm_TaskAllocation>(_TaskAllocation).ExecuteReturnIdentityAsync();
                    if (addId < 1)
                    {
                        _sqlSugar.RollbackTran();
                        _result.Msg = string.Format("任务发布失败!");
                        return _result;
                    }

                    foreach (var item in _TaskRelevanceUsers)
                    {
                        item.TAId = addId;
                    }

                    int addSub = await _sqlSugar.Insertable<Pm_TaskRelevanceUser>(_TaskRelevanceUsers).ExecuteCommandAsync();

                    if (addSub < 1)
                    {
                        _sqlSugar.RollbackTran();
                        _result.Msg = string.Format("任务发布失败!");
                        return _result;
                    }

                    _result.Code = 0;
                    _result.Msg = "添加成功!";
                    _sqlSugar.CommitTran();
                }
                else if (dto.Id > 0) //修改
                {
                    _sqlSugar.BeginTran();

                    int updateStatus1 = await _sqlSugar.Updateable<Pm_TaskAllocation>(_TaskAllocation)
                                                       .UpdateColumns(it => new
                                                       {
                                                           it.DepId,
                                                           it.DiId,
                                                           it.TaskPriority,
                                                           it.TaskName,
                                                           it.TaskContent,
                                                           it.PredictBeginTime,
                                                           it.PredictEndTime,
                                                           it.IsIntoPerformance,
                                                       })
                                                       .Where(it => it.Id == _TaskAllocation.Id)
                                                       .ExecuteCommandAsync();
                    if (updateStatus1 < 1)
                    {
                        _sqlSugar.RollbackTran();
                        _result.Msg = string.Format("任务编辑失败!");
                        return _result;
                    }

                    List<int> selectUserId = new List<int>();
                    selectUserId = await _sqlSugar.Queryable<Pm_TaskRelevanceUser>()
                                                  .Where(it => it.IsDel == 0 && it.TAId == _TaskAllocation.Id)
                                                  .Select(it => it.UserId)
                                                  .ToListAsync();

                    if (selectUserId.Count < 1)
                    {
                        int addSub1 = await _sqlSugar.Insertable<Pm_TaskRelevanceUser>(_TaskRelevanceUsers).ExecuteCommandAsync();
                        if (addSub1 < 1)
                        {
                            _sqlSugar.RollbackTran();
                            _result.Msg = string.Format("任务编辑失败!");
                            return _result;
                        }
                    }
                    else
                    {
                        List<int> SelectUserIdDiff = new List<int>(); //select 差集
                        SelectUserIdDiff = selectUserId.Except(dto.UserIds).ToList();
                        if (SelectUserIdDiff.Count > 0) //删除
                        {
                            List<Pm_TaskRelevanceUser> _TaskRelevanceUsers1 = new List<Pm_TaskRelevanceUser>();

                            _TaskRelevanceUsers1 = await _sqlSugar.Queryable<Pm_TaskRelevanceUser>()
                                                                  .Where(it => it.IsDel == 0 &&
                                                                               it.TAId == _TaskAllocation.Id &&
                                                                               SelectUserIdDiff.Contains(it.UserId))
                                                                  .ToListAsync();
                            if (_TaskRelevanceUsers1.Count > 0)
                            {
                                foreach (var item in _TaskRelevanceUsers1)
                                {
                                    item.IsDel = 1;
                                }

                                var updateIsDel = await _sqlSugar.Updateable(_TaskRelevanceUsers1)
                                                                 .UpdateColumns(it => it.IsDel)
                                                                 .WhereColumns(it => new { it.Id, it.TAId })
                                                                 .ExecuteCommandAsync();
                                if (updateIsDel < 1)
                                {
                                    _sqlSugar.RollbackTran();
                                    _result.Msg = string.Format("任务编辑失败!");
                                    return _result;
                                }
                            }
                        }

                        List<int> ParaUserIdDiff = new List<int>(); //para 差集
                        ParaUserIdDiff = dto.UserIds.Except(selectUserId).ToList();

                        if (ParaUserIdDiff.Count > 0)
                        {
                            List<Pm_TaskRelevanceUser> _TaskRelevanceUsers1 = new List<Pm_TaskRelevanceUser>();
                            _TaskRelevanceUsers1 = _TaskRelevanceUsers.Where(it => ParaUserIdDiff.Contains(it.UserId)).ToList();
                            if (_TaskRelevanceUsers1.Count > 0)
                            {
                                int addSub1 = await _sqlSugar.Insertable<Pm_TaskRelevanceUser>(_TaskRelevanceUsers1).ExecuteCommandAsync();
                                if (addSub1 < 1)
                                {
                                    _sqlSugar.RollbackTran();
                                    _result.Msg = string.Format("任务编辑失败!");
                                    return _result;
                                }
                            }
                        }
                    }

                    /*
                     * 发送消息
                     */
                    _result.Code = 0;
                    _result.Msg = "编辑成功!";
                    _sqlSugar.CommitTran();
                }
                else
                {
                    _result.Msg = string.Format("请传入有效的Id参数!");
                    return _result;
                }



            }
            else
            {
                _result.Msg = string.Format("请传入有效的PortType参数!");
            }
            return _result;
        }

        /// <summary>
        /// 任务归属人状态 Items
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Result> _TaskerDetails(int id)
        {
            if (id < 1)
            {
                _result.Msg = string.Format("请传入有效的Id参数!");
                return _result;
            }

            string sql = string.Format(@"Select tau.Id,u.CnName As UserName,tau.BeginTime,tau.OverTime,tau.TaskStatus,
												 tau.Cause,tau.Score,tau.Remark As ScoreRemark,tau.CreateUserId As TaskCreateUserId
												 From Pm_TaskRelevanceUser tau 
												 Left Join Sys_Users u On tau.UserId = u.Id
												 Where tau.IsDel = 0 And  tau.TAId = {0}", id);

            var data = await _sqlSugar.SqlQueryable<TaskerDetailsView>(sql).ToListAsync();

            _result.Data = data;
            _result.Msg = string.Format("操作成功!");
            _result.Code = 0;

            return _result;
        }

        /// <summary>
        /// 任务归属人状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Result> _TaskerStatus(int id)
        {
            if (id < 1)
            {
                _result.Msg = string.Format("请传入有效的Id参数!");
                return _result;
            }

            var data1 = await _sqlSugar.Queryable<Pm_TaskRelevanceUser>().Where(it => it.IsDel == 0 && it.Id == id).FirstAsync();
            if (data1 == null)
            {
                _result.Msg = string.Format("该任务不存在!");
                return _result;
            }
            var data2 = await _sqlSugar.Queryable<Pm_TaskAllocation>().Where(it => it.IsDel == 0 && it.Id == data1.TAId).FirstAsync();

            _sqlSugar.BeginTran();

            var update1 = await _sqlSugar.Updateable<Pm_TaskRelevanceUser>()
                                         .SetColumns(it => it.TaskStatus == TaskerEnum.HaveKnown)
                                         .ExecuteCommandAsync();
            if (update1 < 1)
            {
                _result.Msg = string.Format("操作失败!");
                return _result;
            }
            _result.Msg = string.Format("操作成功!");
            _result.Code = 0;
            _sqlSugar.CommitTran();


            return _result;
        }

        /// <summary>
        /// 任务归属人设置开始状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Result> _TaskerSetStartStatus(int userId, int id)
        {
            if (id < 1)
            {
                _result.Msg = string.Format("请传入有效的Id参数!");
                return _result;
            }
            //状态限制
            var selectData = await _sqlSugar.Queryable<Pm_TaskRelevanceUser>().Where(it => it.IsDel == 0 && it.UserId == userId && it.TAId == id).FirstAsync();
            if (selectData == null)
            {
                _result.Msg = string.Format("该任务不在!");
                return _result;
            }
            if (selectData.TaskStatus >= TaskerEnum.UnderWay)
            {
                _result.Msg = string.Format("该任务已知晓，不可重复设置!");
                return _result;
            }

            _sqlSugar.BeginTran();
            var update1 = await _sqlSugar.Updateable<Pm_TaskRelevanceUser>()
                                         .SetColumns(it => it.TaskStatus == TaskerEnum.UnderWay)
                                         .SetColumns(it => it.BeginTime == DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
                                         .Where(it => it.TAId == id)
                                         .Where(it => it.UserId == userId )
                                         .ExecuteCommandAsync();
            if (update1 < 1)
            {
                _result.Msg = string.Format("操作失败!");
                _sqlSugar.RollbackTran();
                return _result;
            }
            var update2 = await _sqlSugar.Updateable<Pm_TaskAllocation>()
                                        .SetColumns(it => it.Status == TaskEnum.UnderWay)
                                        .Where(it => it.Id == id)
                                        .ExecuteCommandAsync();
            if (update2 < 1)
            {
                _result.Msg = string.Format("操作失败!");
                _sqlSugar.RollbackTran();
                return _result;
            }

            _sqlSugar.CommitTran();
            _result.Msg = string.Format("操作成功!");
            _result.Code = 0;

            return _result;
        }


        /// <summary>
        /// 任务归属人设置完成状态
        /// 1.待审核
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Result> _TaskerSetOverStatus(int userId, int id)
        {
            if (id < 1)
            {
                _result.Msg = string.Format("请传入有效的Id参数!");
                return _result;
            }

            //状态限制
            var selectData = await _sqlSugar.Queryable<Pm_TaskRelevanceUser>().Where(it => it.IsDel == 0 && it.UserId == userId && it.TAId == id).FirstAsync();
            if (selectData == null)
            {
                _result.Msg = string.Format("该任务不在!");
                return _result;
            }
            if (selectData.TaskStatus != TaskerEnum.UnderWay)
            {
                _result.Msg = string.Format("该任务已提交待审核状态,不可重复提交!");
                return _result;
            }
            _sqlSugar.BeginTran();
            var update1 = await _sqlSugar.Updateable<Pm_TaskRelevanceUser>()
                                         .SetColumns(it => it.TaskStatus == TaskerEnum.WaitConfirm)
                                         .SetColumns(it => it.OverTime == DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
                                         .Where(it => it.TAId == id)
                                         .Where(it => it.UserId == userId)
                                         .ExecuteCommandAsync();
            if (update1 < 1)
            {
                _result.Msg = string.Format("操作失败!");
                _sqlSugar.RollbackTran();
                return _result;
            }
            var update2 = await _sqlSugar.Updateable<Pm_TaskAllocation>()
                                        .SetColumns(it => it.Status == TaskEnum.UnderWay)
                                        .Where(it => it.Id == id)
                                        .ExecuteCommandAsync();
            if (update2 < 1)
            {
                _result.Msg = string.Format("操作失败!");
                _sqlSugar.RollbackTran();
                return _result;
            }

            _sqlSugar.CommitTran();
            _result.Msg = string.Format("操作成功!");
            _result.Code = 0;

            return _result;
        }

        /// <summary>
        /// 设置任务知晓
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Result> _TaskSetHaveStatus(int id)
        {
            if (id < 1)
            {
                _result.Msg = string.Format("请传入有效的Id参数!");
                return _result;
            }

            var data1 = await _sqlSugar.Queryable<Pm_TaskRelevanceUser>().Where(it => it.IsDel == 0 && it.Id == id).FirstAsync();
            if (data1 == null)
            {
                _result.Msg = string.Format("该任务不存在!");
                return _result;
            }
            var data2 = await _sqlSugar.Queryable<Pm_TaskAllocation>().Where(it => it.IsDel == 0 && it.Id == data1.TAId).FirstAsync();

            var update1 = await _sqlSugar.Updateable<Pm_TaskRelevanceUser>()
                                         .SetColumns(it => it.TaskStatus == TaskerEnum.HaveKnown)
                                         .ExecuteCommandAsync();
            if (update1 < 1)
            {
                _result.Msg = string.Format("操作失败!");
                return _result;
            }
            _result.Msg = string.Format("操作成功!");
            _result.Code = 0;
            _sqlSugar.CommitTran();


            return _result;
        }
        

        /// <summary>
        /// 设置任务审批状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Result> _TaskSetAuditStatus(int id)
        {
            if (id < 1)
            {
                _result.Msg = string.Format("请传入有效的Id参数!");
                return _result;
            }

            var data1 = _sqlSugar.Queryable<Pm_TaskRelevanceUser>().Where(it => it.IsDel == 0 && it.Id == id).First();
            if (data1 == null)
            {
                _result.Msg = string.Format("该任务不存在或者该任务未分配给你!");
                return _result;
            }
            int _taId = data1.TAId;

            _sqlSugar.BeginTran();
            var update1 = _sqlSugar.Updateable<Pm_TaskRelevanceUser>()
                                         .SetColumns(it => it.TaskStatus == TaskerEnum.Finished)
                                         .Where(it => it.Id == id)
                                         .ExecuteCommand();
            if (update1 < 1)
            {
                _result.Msg = string.Format("操作失败!");
                _sqlSugar.RollbackTran();
                return _result;
            }
            //设置任务状态
            TaskEnum taskStatus = TaskEnum.Finished;
            var data2 = _sqlSugar.Queryable<Pm_TaskRelevanceUser>().Where(it => it.IsDel == 0 && it.TAId == _taId).ToList();
            var data3 = data2.Where(it => it.TaskStatus == TaskerEnum.Finished && it.Id != id).ToList();
            var data4 = data2.Where(it => it.TaskStatus == TaskerEnum.UnFinished && it.Id != id).ToList();

            if (data4.Count > 0) taskStatus = TaskEnum.UnFinished;

            if ((data2.Count - 1) == (data3.Count + data4.Count))
            {
                var update2 = _sqlSugar.Updateable<Pm_TaskAllocation>()
                                         .SetColumns(it => it.Status == taskStatus)
                                         .Where(it => it.Id == _taId)
                                         .ExecuteCommand();
                if (update2 < 1)
                {
                    _result.Msg = string.Format("操作失败!");
                    _sqlSugar.RollbackTran();
                    return _result;
                }
            }

            _result.Msg = string.Format("操作成功!");
            _result.Code = 0;
            _sqlSugar.CommitTran();

            return _result;
        }

        /// <summary>
        /// 设置任务未完成状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Result> _TaskSetUnFinishedStatus(int id, string cause)
        {
            if (id < 1)
            {
                _result.Msg = string.Format("请传入有效的Id参数!");
                return _result;
            }

            var data1 = await _sqlSugar.Queryable<Pm_TaskRelevanceUser>().Where(it => it.IsDel == 0 && it.Id == id).FirstAsync();
            if (data1 == null)
            {
                _result.Msg = string.Format("该任务不存在或者该任务未分配给你!");
                return _result;
            }
            int _taId = data1.TAId;

            _sqlSugar.BeginTran();
            var update1 = await _sqlSugar.Updateable<Pm_TaskRelevanceUser>()
                                         .SetColumns(it => it.TaskStatus == TaskerEnum.UnFinished)
                                         .SetColumns(it => it.Cause == cause)
                                         .Where(it => it.Id == id)
                                         .ExecuteCommandAsync();
            if (update1 < 1)
            {
                _result.Msg = string.Format("操作失败!");
                _sqlSugar.RollbackTran();
                return _result;
            }

            //设置任务状态
            var data2 = _sqlSugar.Queryable<Pm_TaskRelevanceUser>().Where(it => it.IsDel == 0 && it.TAId == _taId).ToList();
            var data3 = data2.Where(it => it.TaskStatus == TaskerEnum.Finished && it.Id != id).ToList();
            var data4 = data2.Where(it => it.TaskStatus == TaskerEnum.UnFinished && it.Id != id).ToList();
           
            if ((data2.Count - 1) == (data3.Count + data4.Count))
            {
                var update2 = _sqlSugar.Updateable<Pm_TaskAllocation>()
                                         .SetColumns(it => it.Status == TaskEnum.UnFinished)
                                         .Where(it => it.Id == _taId)
                                         .ExecuteCommand();
                if (update2 < 1)
                {
                    _result.Msg = string.Format("操作失败!");
                    _sqlSugar.RollbackTran();
                    return _result;
                }
            }

            _result.Msg = string.Format("操作成功!");
            _result.Code = 0;
            _sqlSugar.CommitTran();

            return _result;
        }


        /// <summary>
        /// 任务确认完成
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Result> _TaskConfirmCompletion(int portType,int id)
        {
            if (portType == 1 || portType == 2 || portType == 3)
            {
                if (id < 1)
                {
                    _result.Msg = string.Format("请传入有效的Id参数!");
                    return _result;
                }

                var data = await _sqlSugar.Queryable<Pm_TaskRelevanceUser>()
                                          .Where(it => it.IsDel == 0 && it.Id == id && it.TaskStatus <= TaskerEnum.UnFinished)
                                          .ToListAsync();
                if (data.Count > 0)
                {
                    _result.Msg = string.Format("本任务参与人员并未全部完成,不可确认任务完成!");
                    return _result;
                }


                var update = await _sqlSugar.Updateable<Pm_TaskAllocation>()
                                            .SetColumns(it => it.IsComplete == 1)
                                            .SetColumns(it => it.Status == TaskEnum.Finished)
                                            .Where(it => it.Id == id)
                                            .ExecuteCommandAsync();
                if (update > 0)
                {
                    _result.Code = 0;
                    return _result;
                }
                else _result.Msg = "确认完成失败!";


            }
            else
            {
                _result.Msg = string.Format("请传入有效的PortType参数!");
            }
            return _result;
        }

        /// <summary>
        /// 任务评分
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Result> _TaskScore(TaskAllocationScoreDto dto)
        {
            int portType = dto.PortType;
            if (portType == 1 || portType == 2 || portType == 3)
            {
                if (dto.SubId < 1)
                {
                    _result.Msg = string.Format("请传入有效的SubId参数!");
                    return _result;
                }

                //var data = await _sqlSugar.Queryable<Pm_TaskAllocation>()
                //                          .Where(it => it.IsDel == 0 )
                //                          .FirstAsync();
                //if (data == null)
                //{
                //    _result.Msg = string.Format("本任务尚未由发布人确认任务完成,不可评分!");
                //    return _result;
                //}

                var data = _sqlSugar.Queryable<Pm_TaskRelevanceUser>()
                                          .Where(it => it.IsDel == 0 && it.Id == dto.SubId)
                                          .First();
                if (data == null)
                {
                    _result.Msg = string.Format("本任务尚未由发布人确认任务完成,不可评分!");
                    return _result;
                }

                if (data.TaskStatus != TaskerEnum.Finished)
                {
                    _result.Msg = string.Format("本任务尚未由发布人确认任务完成,不可评分!");
                    return _result;
                }


                Pm_TaskRelevanceUser _TaskRelevanceUser = new Pm_TaskRelevanceUser() {
                    Id = dto.SubId,
                    Score = dto.Score,
                    Remark = dto.ScoreRemark
                };

                var update = await _sqlSugar.Updateable<Pm_TaskRelevanceUser>(_TaskRelevanceUser)
                                            .UpdateColumns(it => new { it.Score, it.Remark })
                                            .WhereColumns(it => it.Id)
                                            .ExecuteCommandAsync();
                if (update > 0)
                {
                    _result.Code = 0;
                    return _result;
                }
                else _result.Msg = "评分失败!";

            }
            else
            {
                _result.Msg = string.Format("请传入有效的PortType参数!");
            }
            return _result;
        }

        /// <summary>
        /// 任务终止
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Result> _TaskTermination(int taskId)
        {

            if (taskId < 1)
            {
                _result.Msg = string.Format("请传入有效的taskId参数!");
                return _result;
            }
            _sqlSugar.BeginTran();
            var taskUpdate = _sqlSugar.Updateable<Pm_TaskAllocation>()
                                      .SetColumns(it => it.Status == TaskEnum.TaskStop)
                                      .Where(it => it.Id == taskId)
                                      .ExecuteCommand();
            if (taskUpdate < 1)
            {
                _result.Msg = "任务终止失败!";
                _sqlSugar.RollbackTran();
                return _result;
            }
            var subTaskUpdate = _sqlSugar.Updateable<Pm_TaskRelevanceUser>()
                
                                      .SetColumns(it => it.TaskStatus == TaskerEnum.TaskStop)
                                      .Where(it => it.TAId == taskId)
                                      .ExecuteCommand();

            if (taskUpdate < 1)
            {
                _result.Msg = "任务终止失败!";
                _sqlSugar.RollbackTran();
                return _result;
            }
            _result.Msg = "操作成功!";
            _result.Code = 0;
            _sqlSugar.CommitTran();
            return _result;
        }

        /// <summary>
        /// 任务删除
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Result> _TaskDel(int taskId)
        {

            if (taskId < 1)
            {
                _result.Msg = string.Format("请传入有效的taskId参数!");
                return _result;
            }
            _sqlSugar.BeginTran();
            var taskUpdate = _sqlSugar.Updateable<Pm_TaskAllocation>()
                                      .SetColumns(it => it.IsDel == 1)
                                      .Where(it => it.Id == taskId)
                                      .ExecuteCommand();
            if (taskUpdate < 1)
            {
                _result.Msg = "任务删除失败!";
                _sqlSugar.RollbackTran();
                return _result;
            }
            var subTaskUpdate = _sqlSugar.Updateable<Pm_TaskRelevanceUser>()
                                      .SetColumns(it => it.IsDel == 1)
                                      .Where(it => it.TAId == taskId)
                                      .ExecuteCommand();

            if (taskUpdate < 1)
            {
                _result.Msg = "任务删除失败!";
                _sqlSugar.RollbackTran();
                return _result;
            }
            _result.Msg = "操作成功!";
            _result.Code = 0;
            _sqlSugar.CommitTran();
            return _result;
        }
    }
}
