using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Data;
using wispro.sp.entity;
using wispro.sp.share;
using System.Linq;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;

namespace wispro.sp.api.Controllers
{
    //[Authorize]
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class StaffController : ControllerBase
    {
        private static List<Staff> CacheList = new List<Staff>();
        spDbContext Context;

        public StaffController(spDbContext context)
        {
            Context = context;
        }
        

        public List<Staff> GetAll()
        {
            return Context.Staffs.ToList<Staff>();
        }
        
        
        public ListApiResponse<Staff> Query(int pageIndex,int pageSize)
        {
            ListApiResponse<Staff> ret = new ListApiResponse<Staff>();
            ret.TotalCount = Context.Staffs.Count<Staff>();

            List<Staff> retList = Context.Staffs.Skip<Staff>((pageIndex - 1) * pageSize).Take(pageSize).ToList<Staff>();
            
            ret.Results = retList;

            return ret;
        }

        public ListApiResponse<Staff> QueryInDepartment(int deptId,int pageIndex,int pageSize)
        {
            ListApiResponse<Staff> ret = new ListApiResponse<Staff>();
            var dept = Context.Departments.FirstOrDefault<Department>(d=>d.Id == deptId);
            string strancestors = $"{dept.ancestors},{deptId}";

            if (dept != null)
            {
                var retList = Context.Staffs.Where<Staff>(s => 
                    s.Positions.Where<DepartmentPosition>(dp => dp.department.ancestors.StartsWith(strancestors) || dp.department.Id  == deptId).Count() > 0 );
                ret.TotalCount = retList.Count();
                ret.Results = retList.Skip<Staff>((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                ret.Results = new List<Staff>();
            }

            return ret;
        }

        public ApiSaveResponse Init()
        {
            using (var t = Context.Database.BeginTransaction())
            {
                try
                {
                    Position p = Context.Positions.FirstOrDefault<Position>(p=>p.Name == "普通成员");

                    if (p == null)
                    {
                        p = new Position() { Name = "普通成员" };
                        Context.Positions.Add(p);
                        Context.SaveChanges();
                    }

                    foreach (var staff in Context.Staffs.ToList())
                    {
                        string[] temStrs = staff.Department.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                        Department dept = null;
                        foreach (string depName in temStrs)
                        {
                            if (dept == null)
                            {
                                System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("\\((.+?)\\)");
                                System.Text.RegularExpressions.Match m = r.Match(depName);

                                if (m.Success)
                                {
                                    var Name1 = depName.Substring(0, m.Index);
                                    dept = Context.Departments.FirstOrDefault<Department>(d => d.Name == Name1.Trim());

                                    var Name2 = m.Groups[1].Value;
                                    dept = Context.Departments.FirstOrDefault<Department>(d => d.Name == Name2.Trim() && d.parentId == dept.Id);
                                }
                                else
                                {
                                    dept = Context.Departments.FirstOrDefault<Department>(d => d.Name == depName.Trim());
                                }
                                
                            }
                            else
                            {
                                dept = Context.Departments.FirstOrDefault<Department>(d => d.Name == depName.Trim() && d.parentId == dept.Id);
                            }
                        }

                        if (dept != null)
                        {
                            DepartmentPosition dp = new DepartmentPosition();
                            dp.StaffId = staff.Id;
                            dp.PositionId = p.Id;
                            dp.departmentId = dept.Id;

                            Context.DepartmentPositions.Add(dp);

                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine($"{staff.Name}\t{staff.Department}");
                        }
                    }
                    Context.SaveChanges();

                    t.Commit();
                }
                catch(Exception ex)
                {
                    t.Rollback();
                }

            }

            return new ApiSaveResponse() { Success = true };
        }

        public ApiSaveResponse SaveUser(SaveUserObject saveUser)
        {
            ApiSaveResponse ret = new ApiSaveResponse();
            using (var t = Context.Database.BeginTransaction())
            {
                try
                {

                    Staff staff = saveUser.staff;

                    if (staff.Id == 0)
                    {

                        Staff temStaff = Context.Staffs.Where<Staff>(x => x.Name == staff.Name).FirstOrDefault();

                        if (temStaff != null)
                        {
                            ret.Success = false;
                            ret.ErrorMessage = $"用户【{staff.Name}】已存在！";
                        }
                        else
                        {
                            Context.Staffs.Add(staff);
                            Context.SaveChanges();

                            DepartmentPosition dp = new DepartmentPosition();
                            dp.departmentId = saveUser.deptId;
                            dp.PositionId = saveUser.deptId;
                            dp.StaffId = temStaff.Id;
                            Context.DepartmentPositions.Add(dp);
                        }
                    }
                    else
                    {
                        Staff editObject = Context.Staffs.Where<Staff>(x => x.Id == staff.Id).FirstOrDefault();

                        if (editObject != null)
                        {
                            editObject.Account = staff.Account;
                            editObject.Department = staff.Department;
                            editObject.EntyDate = staff.EntyDate;
                            editObject.IsCalPerformsnce = staff.IsCalPerformsnce;
                            editObject.IsOnJob = staff.IsOnJob;
                            editObject.Mail = staff.Mail;
                            editObject.Memo = staff.Memo;
                            editObject.Mobile = staff.Mobile;
                            editObject.Name = staff.Name;
                            editObject.Password = staff.Password;
                            editObject.Sex = staff.Sex;
                            editObject.StaffGradeId = staff.StaffGradeId;
                            editObject.Status = staff.Status;
                            editObject.Tel = staff.Tel;
                            editObject.WorkPlace = staff.WorkPlace;
                            Context.SaveChanges();

                            var temDP = Context.DepartmentPositions
                                .Where<DepartmentPosition>(d =>
                                    d.departmentId == saveUser.deptId &&
                                    d.StaffId == editObject.Id).ToList<DepartmentPosition>();

                            foreach (var depPosition in temDP)
                            {
                                Context.DepartmentPositions.Remove(depPosition);
                            }
                            Context.SaveChanges();

                            DepartmentPosition dp = new DepartmentPosition();
                            dp.departmentId = saveUser.deptId;
                            dp.PositionId = saveUser.positionId;
                            dp.StaffId = editObject.Id;
                            Context.DepartmentPositions.Add(dp);
                            Context.SaveChanges();

                        }
                        else
                        {
                            ret.Success = false;
                            ret.ErrorMessage = $"编号为【{staff.Id}】的用户不存在！";
                        }

                    }

                    
                    t.Commit();
                    ret.Success = true;

                }
                catch (Exception ex)
                {
                    t.Rollback();
                    ret.Success = false;
                    ret.ErrorMessage = ex.Message;
                }
            }

            return ret;
        }

        [HttpPost]
        public ApiSaveResponse Save(Staff staff)
        {
            ApiSaveResponse ret = new ApiSaveResponse();
            try
            {
                if (staff.Id == 0)
                {
                    
                    Staff temStaff = Context.Staffs.Where<Staff>(x => x.Name == staff.Name).FirstOrDefault();

                    if (temStaff != null)
                    {
                        temStaff.Account = staff.Account;
                        temStaff.Department = staff.Department;
                        temStaff.EntyDate = staff.EntyDate;
                        temStaff.IsCalPerformsnce = staff.IsCalPerformsnce;
                        temStaff.IsOnJob = staff.IsOnJob;
                        temStaff.Mail = staff.Mail;
                        temStaff.Memo = staff.Memo;
                        temStaff.Mobile = staff.Mobile;
                        temStaff.Name = staff.Name;
                        temStaff.Password = staff.Password;
                        temStaff.Sex = staff.Sex;
                        temStaff.StaffGradeId = staff.StaffGradeId;
                        temStaff.Status = staff.Status;
                        temStaff.Tel = staff.Tel;
                        temStaff.WorkPlace = staff.WorkPlace;

                        Context.SaveChanges();

                        ret.Success = false;
                        ret.ErrorMessage = $"用户【{staff.Name}】已存在！";
                    }
                    else
                    {
                        Context.Staffs.Add(staff);
                    }
                }
                else
                {
                    Staff editObject = Context.Staffs.Where<Staff>(x => x.Id == staff.Id).FirstOrDefault();

                    if (editObject != null)
                    {
                        editObject.Account = staff.Account;
                        editObject.Department = staff.Department;
                        editObject.EntyDate = staff.EntyDate;
                        editObject.IsCalPerformsnce = staff.IsCalPerformsnce;
                        editObject.IsOnJob = staff.IsOnJob;
                        editObject.Mail = staff.Mail;
                        editObject.Memo = staff.Memo;
                        editObject.Mobile = staff.Mobile;
                        editObject.Name = staff.Name;
                        editObject.Password = staff.Password;
                        editObject.Sex = staff.Sex;
                        editObject.StaffGradeId = staff.StaffGradeId;
                        editObject.Status = staff.Status;
                        editObject.Tel = staff.Tel;
                        editObject.WorkPlace = staff.WorkPlace;
                    }
                    else
                    {
                        ret.Success = false;
                        ret.ErrorMessage = $"编号为【{staff.Id}】的用户不存在！";
                    }
                    
                }

                Context.SaveChanges();

                ret.Success = true;
            }
            catch (Exception ex)
            {
                ret.Success = false;
                ret.ErrorMessage = ex.Message;
            }

            return ret;
        }
    }
}
