using System;
using System.Collections.Generic;
using System.Common;
using System.Common.Helpers;
using System.IRepositories;
using System.Linq;
using System.Linq.Expressions;
using System.Model;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Utility;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using SqlSugar;
using TVShoppingCallCenter_ZLJ.Models.Inputs;

namespace TVShoppingCallCenter_ZLJ.Controllers.CallCenter
{
    /// <summary>
    /// 绩效报表
    /// </summary>
    [Authorize]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class GradeController : BaseController
    {
        private readonly IConfiguration config;
        private readonly ISysUser_GradeRepository busGradeRepository;
        private readonly ISys_UserAccountRepository busUserAccountRepository;
        private readonly IBus_AfterSaleRepository busAfterSaleRepository;
        private readonly ISys_DeptTeamRepository busDeptTeamRepository;
        private readonly ISys_DepartmentRepository busDepartmentRepository;
        private readonly IBus_OrderRepository bus_OrderRepository;
        private readonly ICall_CallRecordsRepository busCallRecordsRepository;
        public GradeController(ICall_CallRecordsRepository _busCallRecordsRepository,IBus_OrderRepository _bus_OrderRepository,ISys_DepartmentRepository _busDepartmentRepository,ISys_DeptTeamRepository _busDeptTeamRepository,IBus_AfterSaleRepository _busAfterSaleRepository,ISys_UserAccountRepository _busUserAccountRepository,ISysUser_GradeRepository _busGradeRepository, IConfiguration _configuration)
        {
            busCallRecordsRepository = _busCallRecordsRepository;
            bus_OrderRepository = _bus_OrderRepository;
            busDepartmentRepository = _busDepartmentRepository;
            busDeptTeamRepository = _busDeptTeamRepository;
            busAfterSaleRepository = _busAfterSaleRepository;
            busUserAccountRepository = _busUserAccountRepository;
            busGradeRepository = _busGradeRepository;
            config = _configuration;
        }


        /// <summary>
        /// 生成个人绩效列表
        /// </summary>
        /// <param name="date"></param>
        /// <param name="usercode"></param>
        /// <param name="teamid"></param>
        /// <param name="deptid"></param>
        /// <param name="isstrong">1强制更新</param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> Add(string date = "", string usercode = "", int teamid = 0, int deptid = 0, int isstrong = 0)
        {
            string str = await UpdateGrade(date, usercode, teamid, deptid, isstrong);
            return Success("成功", str);

        }


        /// <summary>
        ///  获取个人绩效列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("getlistbypage")]
        public async Task<IActionResult> GetListByPage(SysUser_GradeInput input)
        {
            if (UserLogin.RoleCode == "XS")
            {
                input.F_UserCode = UserLogin.UserCode;
            }
            List<IConditionalModel> ConditionalModels = new List<IConditionalModel>();
            #region 筛选条件
            if (input.SearchStartTime != null)
            {
                ConditionalModels.Add(new ConditionalModel { FieldName = "F_Month", ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = input.SearchStartTime.GetValueOrDefault().ToString("yyyyMM") });
            }
            if (input.SearchEndTime != null)
            {
                ConditionalModels.Add(new ConditionalModel { FieldName = "F_Month", ConditionalType = ConditionalType.LessThanOrEqual, FieldValue = input.SearchEndTime.GetValueOrDefault().ToString("yyyyMM") });
            }
            if (!string.IsNullOrEmpty(input.F_UserCode))
            {
                ConditionalModels.Add(new ConditionalModel { FieldName = "F_UserCode", ConditionalType = ConditionalType.Equal, FieldValue = input.F_UserCode });
            }
            if (input.F_DeptId > 0)
            {
                ConditionalModels.Add(new ConditionalModel { FieldName = "F_DeptId", ConditionalType = ConditionalType.Equal, FieldValue = input.F_DeptId.ToString() });
            }
            if (input.F_TeamId > 0)
            {
                ConditionalModels.Add(new ConditionalModel { FieldName = "F_TeamId", ConditionalType = ConditionalType.Equal, FieldValue = input.F_TeamId.ToString() });
            }
            #endregion

            int count = 0;
            PageData<T_SysUser_Grade> pagelist = await busGradeRepository.GetListByPage(ConditionalModels, new MyPageModel { PageCount = count, PageIndex = input.pageindex, PageSize = input.pagesize }, " F_Month DESC, F_TotleMoney DESC");
            return Success("成功", pagelist);

        }



        /// <summary>
        /// 获取单个信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("getdetail")]
        public async Task<IActionResult> GetDetail(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return Error("id不能为空");
            }
           T_SysUser_Grade model = await busGradeRepository.GetSingle(q=>q.F_Id== id);
            if(model==null)
            {
                return Error("找不到数据");
            }
            return Success("成功", model);

        }



        /// <summary>
        /// 获取单个信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> Delete(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return Error("id不能为空");
            }
            if (await busGradeRepository.Delete(q => q.F_Id == id))
            {
                return Success("成功");
            }
            return Error("失败");
        }



        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("update")]
        public async Task<IActionResult> Update([FromBody]SysUser_GradeInput input)
        {
            if (UserLogin.RoleCode == "XS" || UserLogin.RoleCode == "SH" || UserLogin.RoleCode == "KG")
            {
                return Error("没有权限");
            }
            T_SysUser_Grade model  = await busGradeRepository.GetSingle(q => q.F_Id == input.F_Id);
            if (model.F_State != 1)
            {
                return Error("只有有异议绩效才可以编辑修改");
            }
            ModelConvertHelper<T_SysUser_Grade,SysUser_GradeInput>.ModeToModel(model, input);
            model.F_State = 0;
            if (await busGradeRepository.Update(model))
            {
                return Success("成功");
            }
            return Error("失败");
        }



        /// <summary>
        /// 申诉/确认
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("updatestate")]
        public async Task<IActionResult> UpdateState(string id, int state,string remark)
        {
            if (UserLogin.RoleCode != "XS")
            {
                    return Error("没有权限");
            }
            T_SysUser_Grade model = await busGradeRepository.GetSingle(q => q.F_Id == id);
            if (model.F_State == 5)
            { return Error("绩效已锁定"); }
            if (UserLogin.UserCode == model.F_UserCode)
            {
                if(state==1)
                    model.F_StateReamrk += $"【{remark}】";
                model.F_State = state;
                model.F_SureTime = DateTime.Now;
            }
            else
            {
                return Error("只能自己确认绩效状态"); 
            }

            if (await busGradeRepository.Update(model))
            {
                return Success("成功");
            }
            return Error("失败");
        }

        #region 方法
        /// <summary>
        /// 更新员工绩效
        /// </summary>
        /// <returns></returns>
        [NonAction]
        internal async Task<string> UpdateGrade(string date = "", string usercode = "", int teamid = 0, int deptid = 0, int isstrong = 0)
        {
            int n = 0;
            int ntotle = 0;


            string YearMonth = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
            if (!string.IsNullOrEmpty(date) && date.Length == 6)
            {
                YearMonth = date;
            }
            string year = YearMonth.Substring(0, 4);
            string month = YearMonth.Substring(4);
            DateTime MonthTimeStart = (year + "-" + month + "-01 00:00:01").ObjToDate();
            #region 统计验证
            if (isstrong == 0)
            {
                Expression<Func<T_SysUser_Grade, bool>> whereExpression = q => q.F_State == 5 && q.F_Month == YearMonth && q.F_Type == "月";
                if (deptid > 0)
                {
                    whereExpression.And(q => q.F_DeptId == deptid);
                }
                if (teamid > 0)
                {
                    whereExpression.And(q => q.F_TeamId == teamid);
                }
                if (!string.IsNullOrEmpty(usercode))
                {
                    whereExpression.And(q => q.F_UserCode == usercode);
                }

                T_SysUser_Grade modelGrade = await busGradeRepository.GetFirst(whereExpression, o => o.F_Month, OrderByType.Desc);
                if (modelGrade != null)
                {
                    return ("有锁定绩效，无法更新，请换使用强制更新功能(会消除所有有关更新)");
                }
            }
            #endregion

            #region 销毁要统计的记录
            Expression<Func<T_SysUser_Grade, bool>> whereGradeExpression = q => q.F_Month == YearMonth && q.F_Type == "月";
            if (deptid > 0)
            {
                whereGradeExpression.And(q => q.F_DeptId == deptid);
            }
            if (teamid > 0)
            {
                whereGradeExpression.And(q => q.F_TeamId == teamid);
            }
            if (!string.IsNullOrEmpty(usercode))
            {
                whereGradeExpression.And(q => q.F_UserCode == usercode);
            }
            bool temp100 = await busGradeRepository.Delete(whereGradeExpression);
            #endregion



            Expression<Func<T_Sys_Department, bool>> whereExpressiondept = q =>q.F_State==1&& q.F_DeptCode.Contains("|0|1|");
            if (deptid > 0)
            {
                whereExpressiondept.And(q => q.F_DeptId == deptid);
            }
            List<T_Sys_Department> modeldeptlist = await busDepartmentRepository.GetListALL(whereExpressiondept);
            List<int> strlist = new List<int>();
            if (modeldeptlist != null)
            {
                foreach (T_Sys_Department modeldept in modeldeptlist)
                {
                    strlist.Add(modeldept.F_DeptId);
                }
            }
            int[] deptarry = strlist.ToArray();

            Expression<Func<T_Sys_UserAccount, bool>> whereExpressionUserinfo = q => deptarry.Contains(q.F_DeptId);
            if (teamid > 0)
            {
                whereExpressionUserinfo.And(q => q.F_DeptTeamId == teamid);
            }
            if (!string.IsNullOrEmpty(usercode))
            {
                whereExpressionUserinfo.And(q => q.F_UserCode == usercode);
            }


            //强制更新
            //查询出要更新的人
            List<T_Sys_UserAccount> modeluserlist = await busUserAccountRepository.GetListALL(whereExpressionUserinfo);

            if (modeluserlist != null && modeluserlist.Count > 0)
            {
                ntotle = modeluserlist.Count;
                List<T_SysUser_Grade> modellist = new List<T_SysUser_Grade>();
                foreach (T_Sys_UserAccount modelUser in modeluserlist)
                {
                    T_SysUser_Grade modelGrade = new T_SysUser_Grade();
                    modelGrade.F_Id = $"{modelUser.F_UserCode}-{ MonthTimeStart.ToString("yyyyMM")}-{DateTime.Now.ToString("yyyyMMdd")}";
                    modelGrade.F_UserName = modelUser.F_UserName;
                    modelGrade.F_UserId = modelUser.F_UserId;
                    modelGrade.F_UserCode = modelUser.F_UserCode;
                    modelGrade.F_AddTime = DateTime.Now;
                    modelGrade.F_Dept = modelUser.F_Dept;
                    modelGrade.F_DeptId = modelUser.F_DeptId;
                    modelGrade.F_Post = modelUser.F_Post;
                    modelGrade.F_PostId = modelUser.F_DutyId.GetValueOrDefault(0);
                    modelGrade.F_Type = "月";
                    modelGrade.F_Month = YearMonth;
                    modelGrade.F_AddTime = DateTime.Now;
                    modelGrade.F_TaskNumber = 0;
                    modelGrade.F_TaskOverNumber = 0;
                    modelGrade.F_TaskRate = "—";

                    List<decimal> totleArry = await bus_OrderRepository.SendTotleNumber(modelUser.F_UserId, MonthTimeStart);
                    modelGrade.F_SendTotleNumber = totleArry[0].ObjToInt();
                    modelGrade.F_TotleMoney = totleArry[1];

                    totleArry = await bus_OrderRepository.SignNumber(modelUser.F_UserId, MonthTimeStart);
                    modelGrade.F_SignNumber = totleArry[0].ObjToInt();
                    modelGrade.F_SignMoney = totleArry[1];

                    totleArry = await bus_OrderRepository.RefuseNumber(modelUser.F_UserId, MonthTimeStart);
                    modelGrade.F_RefuseNumber = totleArry[0].ObjToInt();
                    modelGrade.F_RefuseMoney = totleArry[1];

                    modelGrade.F_NoSignNumber = modelGrade.F_SendTotleNumber - modelGrade.F_SignNumber - modelGrade.F_RefuseNumber;
                    modelGrade.F_NoSignMoney = modelGrade.F_TotleMoney - modelGrade.F_SignMoney - modelGrade.F_SignMoney;
                    totleArry = await busAfterSaleRepository.BackNumberSH(modelUser.F_UserId, MonthTimeStart);

                    modelGrade.F_AfterNumber = totleArry[0].ObjToInt();
                    modelGrade.F_AfterMoney = totleArry[1];


                    totleArry = await bus_OrderRepository.ErrorNumber(modelUser.F_UserId, MonthTimeStart);

                    modelGrade.F_ErrorMoney = totleArry[1];//统计上个月的

                    modelGrade.F_AlongMoney = await bus_OrderRepository.AlongMoney(modelUser.F_UserId, MonthTimeStart);
                    modelGrade.F_SignRate = modelGrade.F_SendTotleNumber > 0 ? (modelGrade.F_SignNumber.ObjToDecimal() / modelGrade.F_SendTotleNumber).ToString("P2") : "—";

                    modelGrade.F_TaskNumber = 0;
                    modelGrade.F_TaskOverNumber = modelGrade.F_SignNumber + modelGrade.F_ErrorMoney + modelGrade.F_AfterMoney + modelGrade.F_LastSignMoney;
                    modelGrade.F_TaskRate = "—";

                    modelGrade.F_CallNumber = await busCallRecordsRepository.GetCount(q=>q.UserCode== modelUser.F_UserCode&&q.TalkLongTime>0&&q.BeginTime> MonthTimeStart&&q.BeginTime< MonthTimeStart.AddMonths(1));
                    modelGrade.F_CallTotleNumber = await busCallRecordsRepository.GetCount(q => q.UserCode == modelUser.F_UserCode  && q.BeginTime > MonthTimeStart && q.BeginTime < MonthTimeStart.AddMonths(1));

                    modelGrade.F_CallNumber = modelGrade.F_CallNumber == 0 ? 1 : modelGrade.F_CallNumber;
                    modelGrade.F_CallSingleMoney = modelGrade.F_TaskOverNumber / modelGrade.F_CallNumber;

                    modellist.Add(modelGrade);
                    n++;
                }
                await busGradeRepository.AddMany(modellist);
            }

            return $"同步情况  成功/总数 = {n}/{ntotle}";
        }

        #endregion
    }
}