using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using wispro.sp.entity;

namespace wispro.sp.api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class OrganizationController : ControllerBase
    {
        spDbContext Context;

        public OrganizationController(spDbContext context)
        {
            Context = context;
        }
        #region 部门API
        [HttpPost]
        public Department SaveDept(Department dept)
        {
            if(dept.Id > 0)
            {
                var inDbObj = Context.Departments.FirstOrDefault<Department>(d=>d.Id == dept.Id);

                inDbObj.Name = dept.Name;
                inDbObj.Memo = dept.Memo;

                if(dept.order_num != inDbObj.order_num)
                {
                    inDbObj.order_num = dept.order_num;
                }

                if(dept.parentId != inDbObj.parentId)
                {
                    inDbObj.parentId = dept.parentId;
                    Department parentDept = null;
                    if (dept.parentId != null)
                    {
                        parentDept = Context.Departments.FirstOrDefault<Department>(d => d.Id == dept.parentId);
                    }
                    
                    if (parentDept != null || !string.IsNullOrEmpty(parentDept.ancestors))
                    {

                        inDbObj.ancestors = $"{parentDept.ancestors},{parentDept.Id}";
                    }
                    else
                    {
                        inDbObj.ancestors = parentDept.Id.ToString();
                    }

                    if (dept.order_num == null)
                    {
                        var temOrderNum = Context.Departments.Where<Department>(d => d.parentId == parentDept.parentId).Max(d => d.order_num);
                        if (temOrderNum == null)
                        {
                            inDbObj.order_num = temOrderNum + 1;
                        }
                        else
                        {
                            inDbObj.order_num = 1;
                        }
                    }
                    else
                    {
                        inDbObj.order_num = dept.order_num;
                    }
                }


                Context.SaveChanges();

                return inDbObj;
                
            }
            else
            {
                Department parentDept = null;
                if (dept.parentId != null)
                {
                    parentDept = Context.Departments.FirstOrDefault<Department>(d => d.Id == dept.parentId);
                }
                

                if (dept.order_num == null)
                {
                    if(parentDept == null)
                    {
                        var temOrderNum = Context.Departments.Where<Department>(d => d.parentId == null).Max(d => d.order_num);
                        if (temOrderNum != null)
                        {
                            dept.order_num = temOrderNum + 1;
                        }
                        else
                        {
                            dept.order_num = 1;
                        }
                    }
                    else
                    {
                        var temOrderNum = Context.Departments.Where<Department>(d => d.parentId == parentDept.Id ).Max(d => d.order_num);
                        if (temOrderNum != null)
                        {
                            dept.order_num = temOrderNum + 1;
                        }
                        else
                        {
                            dept.order_num = 1;
                        }
                    }
                    
                    
                }

                if(parentDept != null && !string.IsNullOrEmpty(parentDept.ancestors ))
                {

                    dept.ancestors = $"{parentDept.ancestors},{parentDept.Id}";
                }
                else
                {
                    if (parentDept != null)
                    {
                        dept.ancestors = parentDept.Id.ToString();
                    }
                }

                Context.Departments.Add(dept);
                Context.SaveChanges();
                return dept;


            }
        }


        public List<Department> GetDepartments()
        {
            return Context.Departments.ToList();
        }
        

        public bool DeleteDept(int Id)
        {
            try
            {
                var delObj = Context.Departments.FirstOrDefault<Department>(d => d.Id == Id);
                Context.Departments.Remove(delObj);
                Context.SaveChanges();
                return true;
            }
            catch(Exception ex)
            {
                return false;
            }

        }

        public List<Position> GetPositions(int? deptId)
        {
            if (deptId == null)
            {
                return Context.Positions.ToList();
            }
            else
            {
                var retList = Context.DepartmentPositions
                    .Where<DepartmentPosition>(p => p.departmentId == deptId)
                    .Select(p => p.Position).Distinct<Position>().ToList();
                return retList;
            }
        }

        public Position GetPosition(int deptId,int staffId)
        {
            var data = Context.DepartmentPositions.Include(pi => pi.Position).FirstOrDefault<DepartmentPosition>(s => s.StaffId == staffId);
            if(data != null)
            {
                return data.Position;
            }
            else
            {
                return null;
            }
        }
        #endregion

        public List<Customer> GetCustomers()
        {
            return Context.Customers.ToList();
        }

        public void InitUserDepartment()
        {
            Position ptPosition = Context.Positions.FirstOrDefault(s => s.Name == "普通员工");

            if(ptPosition == null)
            {
                ptPosition = new Position() { Name = "普通员工" };
                Context.Positions.Add(ptPosition);
                Context.SaveChanges();
            }
            var lstStaff = Context.Staffs.ToList();

            foreach(var sf in lstStaff)
            {
                if (!string.IsNullOrEmpty(sf.Department))
                {
                    string[] deptStrings = sf.Department.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    if (deptStrings.Length > 0)
                    {
                        System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("\\((.+?)\\)");
                        System.Text.RegularExpressions.Match m = r.Match(deptStrings[0]);

                        Department pDept;
                        if (m.Success)
                        {
                            string firstName = deptStrings[0].Substring(0, m.Index).Trim();
                            string secondName = m.Groups[1].Value.Trim();
                            pDept = Context.Departments.First<Department>(s=>s.Name == firstName);
                            if(pDept == null)
                            {
                                pDept = new Department() { Name = firstName };
                                Context.Departments.Add(pDept);
                                Context.SaveChanges();

                                Department secondDept = Context.Departments.FirstOrDefault<Department>(d => d.parentId == pDept.Id && d.Name == secondName);
                                if (secondDept == null)
                                {
                                    secondDept = new Department() { Name = secondName, parentId = pDept.Id, ancestors = pDept.Id.ToString() };
                                    Context.Departments.Add(secondDept);
                                    Context.SaveChanges();
                                }

                                pDept = secondDept;
                            }
                            else
                            {
                                Department secondDept = Context.Departments.FirstOrDefault<Department>(d => d.parentId == pDept.Id && d.Name == secondName);
                                if (secondDept == null)
                                {
                                    secondDept = new Department() { Name = secondName, parentId = pDept.Id, ancestors = pDept.Id.ToString() };
                                    Context.Departments.Add(secondDept);
                                    Context.SaveChanges();
                                }

                                pDept = secondDept;
                            }
                        }
                        else
                        {
                            pDept = Context.Departments.FirstOrDefault<Department>(s => s.Name == deptStrings[0].Trim());
                            if (pDept == null)
                            {
                                pDept = new Department() { Name = deptStrings[0].Trim() };
                                Context.Departments.Add(pDept);
                                Context.SaveChanges();
                            }
                        }

                        for(int i = 1; i < deptStrings.Length; i++)
                        {
                            Department curDept = Context.Departments.FirstOrDefault<Department>(d=>d.parentId == pDept.Id && d.Name == deptStrings[i].Trim());
                            if(curDept == null)
                            {
                                curDept = new Department()
                                {
                                    Name = deptStrings[i].Trim(),
                                    parentId = pDept.Id,
                                    ancestors = (pDept.parentId == null) ? pDept.parentId.ToString() : $"{pDept.ancestors},{pDept.Id}"
                                };

                                Context.Departments.Add(curDept);
                                Context.SaveChanges();

                                
                            }

                            pDept = curDept;
                        }

                        if(pDept != null)
                        {

                            DepartmentPosition dp = Context.DepartmentPositions.FirstOrDefault(p => p.StaffId == sf.Id && p.departmentId == pDept.Id && p.PositionId == ptPosition.Id);
                            if (dp == null)
                            {

                                dp = new DepartmentPosition();
                                dp.StaffId = sf.Id;
                                dp.departmentId = pDept.Id;
                                dp.PositionId = ptPosition.Id;

                                Context.DepartmentPositions.Add(dp);
                                Context.SaveChanges();
                            }
                        }
                        
                    }
                }
            }
        }
        
    }
}
