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 TeamGradeController : BaseController
    {
        private readonly IConfiguration config;
        private readonly ISysUser_GradeRepository busGradeRepository;
        private readonly ISysUser_TeamGradeRepository busTeamGradeRepository;
        private readonly ISys_DepartmentRepository busDepartmentRepository;
        private readonly ISys_DeptTeamRepository busDeptTeamRepository;
        private readonly ICall_CallRecordsRepository busCallRecordsRepository;
        public TeamGradeController(ICall_CallRecordsRepository _busCallRecordsRepository, ISys_DeptTeamRepository _busDeptTeamRepository, ISys_DepartmentRepository _busDepartmentRepository, ISysUser_TeamGradeRepository _busTeamGradeRepository, ISysUser_GradeRepository _busGradeRepository, IConfiguration _configuration)
        {
            busCallRecordsRepository = _busCallRecordsRepository;
            busDeptTeamRepository = _busDeptTeamRepository;
            busDepartmentRepository = _busDepartmentRepository;
            busTeamGradeRepository = _busTeamGradeRepository;
            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 = "", int teamid = 0, int deptid = 0, int isstrong = 0)
        {
            string str = await UpdateTeamGrade(date, teamid, deptid, isstrong);
            return Success("成功", str);

        }


        /// <summary>
        ///  获取团队绩效列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("getlistbypage")]
        public async Task<IActionResult> GetListByPage(SysUser_TeamGradeInput input)
        {

            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 (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_TeamGrade> pagelist = await busTeamGradeRepository.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_TeamGrade model = await busTeamGradeRepository.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 busTeamGradeRepository.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_TeamGradeInput input)
        {
            if (UserLogin.RoleCode == "XS" || UserLogin.RoleCode == "SH" || UserLogin.RoleCode == "KG")
            {
                return Error("没有权限");
            }
            T_SysUser_TeamGrade model = await busTeamGradeRepository.GetSingle(q => q.F_Id == input.F_Id);
            if (model.F_State == 5)
            {
                return Error("已锁定绩效不能修改");
            }
            ModelConvertHelper<T_SysUser_TeamGrade, SysUser_TeamGradeInput>.ModeToModelDefault(model, input);
            model.F_State = 4;
            if (await busTeamGradeRepository.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" || UserLogin.RoleCode == "SH" || UserLogin.RoleCode == "KG")
            {
                return Error("没有权限");
            }
            T_SysUser_TeamGrade model = await busTeamGradeRepository.GetSingle(q => q.F_Id == id);
            if (model.F_State == 5)
            { return Error("绩效已锁定不能更改"); }
            if (!string.IsNullOrEmpty(remark))
            {
                model.F_StateReamrk += $"【{remark}】";
            }

            model.F_State = state;
            model.F_SureTime = DateTime.Now;


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


        #region 方法
        /// <summary>
        /// 更新团队绩效
        /// </summary>
        /// <param name="date"></param>
        /// <param name="teamid">-1不更新 0更新全部</param>
        /// <param name="deptid">-1不更新 0更新全部</param>
        /// <param name="isstrong"></param>
        /// <returns></returns>
        [NonAction]
        public async Task<string> UpdateTeamGrade(string date = "", int teamid = 0, int deptid = 0, int isstrong = 0)
        {
            int nteam = 0;
            int ndept = 0;
            int ntotle = 0;
            #region 前置条件准备
            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();
            #endregion

            if (isstrong == 0)
            {
                #region 非强制更新验证
                Expression<Func<T_SysUser_TeamGrade, 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 (deptid == -1)
                {
                    //不更新部门  意思是更新团队
                    whereExpression.And(q => q.F_TeamId > 0);
                }
                if (teamid > 0)
                {
                    whereExpression.And(q => q.F_TeamId == teamid);
                }
                if (teamid == -1)
                {
                    //不更新团队 意思是更新部门
                    whereExpression.And(q => q.F_TeamId == 0);
                }

                T_SysUser_TeamGrade modelGrade = await busTeamGradeRepository.GetFirst(whereExpression, o => o.F_Month, OrderByType.Desc);
                if (modelGrade != null)
                {
                    return ("有锁定绩效，无法更新，请换使用强制更新功能(会消除所有有关更新)");
                }
                #endregion
            }
            #region 有效部门
            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();
            #endregion

            #region 销毁要统计的记录
            Expression<Func<T_SysUser_TeamGrade, bool>> whereGradeExpressionDel = q => q.F_Month == YearMonth && q.F_Type == "月";
            if (deptid > 0)
            {
                whereGradeExpressionDel.And(q => q.F_DeptId == deptid);
            }
            if (deptid == -1)
            {
                //不更新部门  意思是更新团队
                whereGradeExpressionDel.And(q => q.F_TeamId > 0);
            }
            if (teamid > 0)
            {
                whereGradeExpressionDel.And(q => q.F_TeamId == teamid);
            }
            if (teamid == -1)
            {
                //不更新团队 意思是更新部门
                whereGradeExpressionDel.And(q => q.F_TeamId == 0);
            }

            bool temp100 = await busTeamGradeRepository.Delete(whereGradeExpressionDel);
            #endregion

            #region 更新团队
            if (teamid >= 0)
            {
                Expression<Func<T_Sys_DeptTeam, bool>> whereExpressionTeam = q => deptarry.Contains(q.F_DeptId)&& q.F_State == 1;
                if (teamid > 0)
                {
                    whereExpressionTeam.And(q => q.F_Id == teamid);
                }
                //强制更新
                //查询出要更新的人
                List<T_Sys_DeptTeam> modelteamlist = await busDeptTeamRepository.GetListALL(whereExpressionTeam);

                if (modelteamlist != null && modelteamlist.Count > 0)
                {
                    ntotle = modelteamlist.Count;
                    List<T_SysUser_TeamGrade> modellist = new List<T_SysUser_TeamGrade>();
                    foreach (T_Sys_DeptTeam modelTeam in modelteamlist)
                    {
                        T_Sys_Department modeldept = modeldeptlist.FirstOrDefault(q => q.F_DeptId == modelTeam.F_DeptId);
                        if (modeldept == null)
                            modeldept = new T_Sys_Department() { F_DeptName = "N/A" };
                        T_SysUser_TeamGrade modelGrade = new T_SysUser_TeamGrade();
                        modelGrade.F_Id = $"team{modelTeam.F_Id}-{ YearMonth}-{DateTime.Now.ToString("yyyyMMdd")}";
                        modelGrade.F_AddTime = DateTime.Now;
                        modelGrade.F_Dept = modeldept.F_DeptName;
                        modelGrade.F_DeptId = modelTeam.F_DeptId;
                        modelGrade.F_Team = modelTeam.F_Name;
                        modelGrade.F_TeamId = modelTeam.F_Id;
                        modelGrade.F_Post = "";
                        modelGrade.F_PostId = 0;
                        modelGrade.F_Type = "月";
                        modelGrade.F_Month = YearMonth;
                        modelGrade.F_AddTime = DateTime.Now;


                        List<decimal> totleArry = await busGradeRepository.GetALLNumber(modelTeam.F_Id, MonthTimeStart, 0);
                        modelGrade.F_SendTotleNumber = totleArry[0].ObjToInt();
                        modelGrade.F_TotleMoney = totleArry[1];

                        modelGrade.F_SignNumber = totleArry[2].ObjToInt();
                        modelGrade.F_SignMoney = totleArry[3];

                        modelGrade.F_RefuseNumber = totleArry[4].ObjToInt();
                        modelGrade.F_RefuseMoney = totleArry[5];

                        modelGrade.F_NoSignNumber = totleArry[6].ObjToInt();
                        modelGrade.F_NoSignMoney = totleArry[7];


                        modelGrade.F_AfterNumber = totleArry[8].ObjToInt();
                        modelGrade.F_AfterMoney = totleArry[9];

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

                        modelGrade.F_AlongMoney = totleArry[11];
                        modelGrade.F_SignRate = modelGrade.F_SendTotleNumber > 0 ? (modelGrade.F_SignNumber.ObjToDecimal() / modelGrade.F_SendTotleNumber).ToString("P2") : "—";

                        modelGrade.F_TaskNumber = modelTeam.F_TargetMoney;
                        modelGrade.F_TaskOverNumber = modelGrade.F_SignNumber + modelGrade.F_ErrorMoney + modelGrade.F_AfterMoney + modelGrade.F_LastSignMoney;
                        modelGrade.F_TaskRate = modelGrade.F_TaskNumber == 0.00M ? "—" : (modelGrade.F_TaskOverNumber / modelGrade.F_TaskNumber).ToString("#0.00");

                        modelGrade.F_CallNumber = await busCallRecordsRepository.GetCallNumber("", modelTeam.F_Id, MonthTimeStart);
                        modelGrade.F_CallTotleNumber = await busCallRecordsRepository.GetTotleCallNumber("", modelTeam.F_Id, MonthTimeStart);

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

                        modellist.Add(modelGrade);
                        nteam++;
                    }
                    await busTeamGradeRepository.AddMany(modellist);
                }
            }
            #endregion

            #region 更新部门
            if (deptid >= 0)
            {
                if (modeldeptlist != null && modeldeptlist.Count > 0)
                {
                    ntotle += modeldeptlist.Count;
                    List<T_SysUser_TeamGrade> modellist = new List<T_SysUser_TeamGrade>();
                    foreach (T_Sys_Department modeldepttemp in modeldeptlist)
                    {

                        T_SysUser_TeamGrade modelGrade = new T_SysUser_TeamGrade();
                        modelGrade.F_Id = $"dept{modeldepttemp.F_DeptId}-{ YearMonth}-{DateTime.Now.ToString("yyyyMMdd")}";
                        modelGrade.F_AddTime = DateTime.Now;
                        modelGrade.F_Dept = modeldepttemp.F_DeptName;
                        modelGrade.F_DeptId = modeldepttemp.F_DeptId;
                        modelGrade.F_Team = "";
                        modelGrade.F_TeamId = 0;
                        modelGrade.F_Post = "";
                        modelGrade.F_PostId = 0;
                        modelGrade.F_Type = "月";
                        modelGrade.F_Month = YearMonth;
                        modelGrade.F_AddTime = DateTime.Now;


                        List<decimal> totleArry = await busGradeRepository.GetALLNumber(modeldepttemp.F_DeptId, MonthTimeStart, 1);
                        modelGrade.F_SendTotleNumber = totleArry[0].ObjToInt();
                        modelGrade.F_TotleMoney = totleArry[1];

                        modelGrade.F_SignNumber = totleArry[2].ObjToInt();
                        modelGrade.F_SignMoney = totleArry[3];

                        modelGrade.F_RefuseNumber = totleArry[4].ObjToInt();
                        modelGrade.F_RefuseMoney = totleArry[5];

                        modelGrade.F_NoSignNumber = totleArry[6].ObjToInt();
                        modelGrade.F_NoSignMoney = totleArry[7];


                        modelGrade.F_AfterNumber = totleArry[8].ObjToInt();
                        modelGrade.F_AfterMoney = totleArry[9];

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

                        modelGrade.F_AlongMoney = totleArry[11];
                        modelGrade.F_SignRate = modelGrade.F_SendTotleNumber > 0 ? (modelGrade.F_SignNumber.ObjToDecimal() / modelGrade.F_SendTotleNumber).ToString("P2") : "—";

                        modelGrade.F_TaskNumber = modeldepttemp.F_TargetMoney;
                        modelGrade.F_TaskOverNumber = modelGrade.F_SignNumber + modelGrade.F_ErrorMoney + modelGrade.F_AfterMoney + modelGrade.F_LastSignMoney;
                        modelGrade.F_TaskRate = modelGrade.F_TaskNumber == 0.00M ? "—" : (modelGrade.F_TaskOverNumber / modelGrade.F_TaskNumber).ToString("#0.00");

                        modelGrade.F_CallNumber = await busCallRecordsRepository.GetCallNumber(modeldepttemp.F_DeptCode, 0, MonthTimeStart);
                        modelGrade.F_CallTotleNumber = await busCallRecordsRepository.GetTotleCallNumber(modeldepttemp.F_DeptCode, 0, MonthTimeStart);

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

                        modellist.Add(modelGrade);
                        ndept++;
                    }


                    await busTeamGradeRepository.AddMany(modellist);
                }
               
            }
            #endregion

            return $"同步情况  部门/团队 = {ndept}/{nteam}";
        }

        #endregion

    }
}