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

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

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

        
        public List<StaffGrade> GetAll()
        {
            var result= Context.StaffGrades.Where<StaffGrade>(x=>x.Id >0);
            return result.ToList<StaffGrade>();
            
        }

        [HttpPost]
        public ApiSaveResponse Save(StaffGrade staffGrade)
        {
            ApiSaveResponse ret = new ApiSaveResponse();
            try
            {
                if (staffGrade.Id == 0)
                {
                    List<StaffGrade> grades = Context.StaffGrades.Where<StaffGrade>(x => x.Grade == staffGrade.Grade).ToList();

                    if (grades.Count > 0)
                    {
                        ret.Success = false;
                        ret.ErrorMessage = "该等级系数已设定！";
                    }
                    else
                    {
                        Context.StaffGrades.Add(staffGrade);
                    }
                }
                else
                {
                    List<StaffGrade> grades = Context.StaffGrades.Where<StaffGrade>(x => x.Id == staffGrade.Id).ToList();
                    grades[0].Grade = staffGrade.Grade;
                    grades[0].Coefficient = staffGrade.Coefficient;
                }

                Context.SaveChanges();

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

            return ret;
        }
    }
}
