using AutoMapper;
using MySqlX.XDevAPI.Relational;
using OASystem.Domain;
using OASystem.Domain.Dtos.Groups;
using OASystem.Domain.Entities.Groups;
using OASystem.Domain.Entities.Resource;
using OASystem.Domain.ViewModels.Groups;
using Org.BouncyCastle.Utilities.Collections;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OASystem.Infrastructure.Repositories.Groups
{
    public class TaskAssignmentRepository : BaseRepository<Grp_GroupsTaskAssignment, Grp_GroupsTaskAssignment>
    {
        private readonly IMapper _mapper;
        public TaskAssignmentRepository(SqlSugarClient sqlSugar, IMapper mapper) :
            base(sqlSugar)
        {
            this._mapper = mapper;
        }

        public async Task<Result> GetTaskAssignmen()
        {
            Result result = new Result() { Code = -2, Msg = "未知错误" };
            try
            {
                //团组下拉框
                List<dynamic> _DelegationInfos = new List<dynamic>();
                List<Grp_DelegationInfo> grp_DelegationInfos = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(a => a.IsDel == 0 && a.TourCode != "" && a.IsState == 0).ToList();
                foreach (var Item in grp_DelegationInfos)
                {
                    var data = new
                    {
                        Id = Item.Id,
                        Name = Item.TeamName
                    };
                    _DelegationInfos.Add(data);
                }
                //任务下拉框
                List<dynamic> _SetData = new List<dynamic>();
                List<Sys_SetData> sys_SetData = _sqlSugar.Queryable<Sys_SetData>().Where(a => a.IsDel == 0 && a.Name != "其他款项" && a.STid == 16).ToList();
                foreach (var Item in sys_SetData)
                {
                    var data = new
                    {
                        Id = Item.Id,
                        Name = Item.Name
                    };
                    _SetData.Add(data);
                }
                //人员安排列表
                List<dynamic> _User = new List<dynamic>();
                List<Sys_Users> sys_User = _sqlSugar.Queryable<Sys_Users>().Where(a => a.IsDel == 0 && a.Id != 4).ToList();
                foreach (var Item in sys_User)
                {
                    var data = new
                    {
                        Id = Item.Id,
                        Name = Item.CnName
                    };
                    _User.Add(data);
                }
                var dataList = new
                {
                    DelegationInfos = _DelegationInfos,
                    SetData = _SetData,
                    User = _User
                };
                result = new Result() { Code = 0, Msg = "成功", Data = dataList };
            }
            catch (Exception)
            {
                result = new Result() { Code = -2, Msg = "未知错误" };
            }
            return result;
        }

        public async Task<Result> GetTaskAssignmenOp(TaskAssignmenDto dto)
        {
            Result result = new Result() { Code = -2, Msg = "未知错误" };
            try
            {
                List<int> id = new List<int>();
                List<Grp_GroupsTaskAssignment> _GroupsTaskAssignments = _sqlSugar.Queryable<Grp_GroupsTaskAssignment>().Where(a => a.DIId == dto.DIId && a.CTId == dto.CTId && a.IsDel == 0).ToList();
                foreach (var Group in _GroupsTaskAssignments)
                {
                    id.Add(Group.UId);
                }

                List<int> intersection = id.Intersect(dto.UIdStr).ToList();//交集
                List<int> del = id.Except(dto.UIdStr).ToList();//差集
                List<int> union = id.Union(dto.UIdStr).ToList();//并集
                for (int i = 0; i < del.Count; i++)
                {
                    await _sqlSugar.Updateable<Grp_GroupsTaskAssignment>().Where(a => a.UId == del[i] && a.DIId == dto.DIId && a.CTId == dto.CTId).SetColumns(a => new Grp_GroupsTaskAssignment()
                    {
                        IsDel = 1,
                        DeleteUserId = dto.CreateUserId,
                        DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                    }).ExecuteCommandAsync();
                }

                //去掉交集
                foreach (var item in intersection)
                {
                    union.Remove(item);
                }
                //去掉差集
                foreach (var item in del)
                {
                    union.Remove(item);
                }
                //需添加的
                foreach (var item in union)
                {
                    Grp_GroupsTaskAssignment AddData = _mapper.Map<Grp_GroupsTaskAssignment>(dto);
                    AddData.UId = item;

                    Grp_GroupsTaskAssignment addQuery = _sqlSugar.Queryable<Grp_GroupsTaskAssignment>().First(a => a.DIId == AddData.DIId && a.UId == AddData.UId && a.CTId == AddData.CTId);
                    if (addQuery != null)
                    {
                        await _sqlSugar.Updateable<Grp_GroupsTaskAssignment>().Where(a => a.Id == addQuery.Id).SetColumns(a => new Grp_GroupsTaskAssignment()
                        {
                            IsDel = 0,
                            DeleteUserId = 0,
                            CreateUserId = AddData.CreateUserId,
                            CreateTime = DateTime.Now
                        }).ExecuteCommandAsync();
                    }
                    else
                    {
                        int AddId = await AddAsyncReturnId(AddData);
                    }

                }

                result = new Result() { Code = 0, Msg = "保存成功！" };
            }
            catch (Exception)
            {
                result = new Result() { Code = -2, Msg = "保存失败,未知错误" };
            }
            return result;

        }

        public async Task<Result> TaskAssignmenQuery(TaskAssignmenQueryDto dto)
        {
            Result result = new Result() { Code = -2, Msg = "未知错误" };
            try
            {
                string sqlWhere = string.Empty;
                if (dto.DIId != 0)
                {
                    sqlWhere += string.Format(@" And DIId ={0}", dto.DIId);
                }
                else
                {
                    return result = new Result() { Code = -1, Msg = "暂无数据" };
                }
                if (dto.CTId != 0)
                {
                    sqlWhere += string.Format(@" And CTId ={0}", dto.CTId);
                }
                

                sqlWhere += string.Format(@" And IsDel={0} ", 0);
                if (!string.IsNullOrEmpty(sqlWhere.Trim()))
                {
                    Regex r = new Regex("And");
                    sqlWhere = r.Replace(sqlWhere, "Where", 1);
                }
                string sql = string.Format(@"select * from Grp_GroupsTaskAssignment {0}", sqlWhere);
                List<Grp_GroupsTaskAssignment> GroupsTaskAssignment = await _sqlSugar.SqlQueryable<Grp_GroupsTaskAssignment>(sql).ToListAsync();
                Grp_DelegationInfo grp_DelegationInfo = new Grp_DelegationInfo();
                grp_DelegationInfo = _sqlSugar.Queryable<Grp_DelegationInfo>().First(a => a.Id == dto.DIId && a.IsDel == 0);


                if (GroupsTaskAssignment.Count != 0)
                {
                    List<int> UserId = new List<int>();
                    foreach (var item in GroupsTaskAssignment)
                    {
                        UserId.Add(item.UId);
                    }
                    var data = new
                    {
                        TaskAssignment = GroupsTaskAssignment[0],
                        UserStr = UserId,
                        DelegationInfo = grp_DelegationInfo
                    };
                    result = new Result()
                    {
                        Code = 0,
                        Msg = "查询成功！",
                        Data = data
                    };
                }
                else
                {
                    var data = new
                    {
                        TaskAssignment = new List<Grp_GroupsTaskAssignment>(),
                        UserStr = new List<int>(),
                        DelegationInfo = grp_DelegationInfo
                    };
                    result = new Result()
                    {
                        Code = 0,
                        Msg = "查询成功！",
                        Data = data
                    };
                }


            }
            catch (Exception)
            {
                result = new Result() { Code = -2, Msg = "未知错误" };
                throw;
            }
            return result;
        }

        /// <summary>
        /// 查询配置任务
        /// 条件：根据 任务用户Id查询
        /// </summary>
        /// <param name="UserTaskId"></param>
        /// <returns></returns>
        public async Task<Result> TaskAssignmenQueryByUserTaskId(int UserTaskId)
        {
            Result result = new Result() { Code = -2, Msg = "未知错误" };


            var data = await _sqlSugar.Queryable<Grp_GroupsTaskAssignment>()
                .Where(gta => gta.IsDel == 0 && gta.IsEnable == 1 && gta.CreateUserId == UserTaskId)
                .ToListAsync();


            result = new Result() { Code = 0, Msg = "查询成功！" };

            return result;
        }
    }
}
