using CallCenter.Utility;
using CallCenter.Utility.Linq;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using CallCenterApi.Interface.Models.Dto;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers.report
{
    [Authority]
    public class DeptAssessmentController : BaseController
    {
        private readonly BLL.Rep_Dept_Assessment bll = new BLL.Rep_Dept_Assessment();
        private readonly BLL.T_Sys_Department blldepartment = new BLL.T_Sys_Department();
        private readonly BLL.T_Bus_Feedback feedbackBLL = new BLL.T_Bus_Feedback();
        private readonly BLL.T_Bus_AssignedInfo assignedInfoBLL = new BLL.T_Bus_AssignedInfo();

        #region 管理部门绩效
        /// <summary>
        /// 获取所有库列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAllList()
        {
            DataTable dt = new DataTable();
            string deptId = RequestString.GetQueryString("deptId");
            string typeCode = RequestString.GetQueryString("typeCode");      //分数分类
            string gradeCode = RequestString.GetQueryString("gradeCode");    //分数项code
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("strdatetime"));
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            #region 参数判断
            if (string.IsNullOrEmpty(deptId))
            {
                return Error("单位不能为空");
            }
            if (string.IsNullOrEmpty(typeCode))
            {
                return Error("分数分类不能为空");
            }
            if (string.IsNullOrEmpty(gradeCode))
            {
                return Error("分数项不能为空");
            }
            if (string.IsNullOrEmpty(strstarttime))
            {
                return Error("日期不能为空");
            }
            #endregion

            DateTime? start = null;
            DateTime? end = null;
            DateTime strdatetime = Convert.ToDateTime(strstarttime);
            if (!string.IsNullOrEmpty(strdatetime.ToString()))
            {
                //取得上个月的26号
                start = DateTime.Parse((strdatetime.AddDays(1 - strdatetime.Day + 25).AddMonths(-1)).ToShortDateString() + " 00:00:00");
                //取得本月的26号
                end = DateTime.Parse((strdatetime.AddDays(1 - strdatetime.Day + 25).AddMonths(0)).ToShortDateString() + " 23:59:59");
            }

            string sql = " ";
            if (deptId.Trim() != "")
            {
                sql += " and F_DeptId = '" + deptId + "'";
            }
            if (typeCode.Trim() != "")
            {
                sql += " and F_TypeCode = '" + typeCode + "'";
            }
            if (gradeCode.Trim() != "")
            {
                sql += " and F_GradeCode = '" + gradeCode + "'";
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and DATEDIFF(s,'"+ start + "',F_DateTime)>0 and DATEDIFF(s,'" + end + "',F_DateTime)<0  ";
            }
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }
            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            int recordCount = 0;
            string cols = "dbo.GetDeptName(F_DeptId) as deptname,"
                + "F_Id,F_DeptId,F_TypeCode,F_GradeCode,F_Grade,F_Note,F_DateTime,F_CreateTime";
            dt = BLL.PagerBLL.GetListPager(
                    "Rep_Dept_Assessment",
                    "F_Id",
                    cols,
                    sql,
                    "ORDER BY F_Id desc",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);
            var obj = new
            {
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());
        }

        /// <summary>
        /// 保存信息
        /// </summary>
        /// <returns></returns>
        public ActionResult SaveInfo()
        {
            int id = RequestString.GetInt("id", 0);
            int f_DeptId = RequestString.GetInt("deptId", 0);
            string f_TypeCode = RequestString.GetFormString("typeCode");
            string f_GradeCode = RequestString.GetFormString("gradeCode");
            string f_Grade = RequestString.GetFormString("grade");
            string f_Note = RequestString.GetFormString("note");
            string f_DateTime = RequestString.GetFormString("dateTime");
            string f_strdatetime = RequestString.GetFormString("strdatetime");
            #region 判断提示
            if (f_DeptId == 0)
            {
                return Error("请选择部门");
            }
            if (string.IsNullOrWhiteSpace(f_TypeCode))
            {
                return Error("分数分类不能为空");
            }
            if (string.IsNullOrWhiteSpace(f_GradeCode))
            {
                return Error("分数项不能为空");
            }
            if (string.IsNullOrEmpty(f_Grade))
            {
                return Error("分数不能为空");
            }
            if (string.IsNullOrEmpty(f_DateTime))
            {
                return Error("时间不能为空");
            }
            if (string.IsNullOrEmpty(f_strdatetime))
            {
                return Error("日期不能为空");
            }
            #endregion

            DateTime? start = null;
            DateTime? end = null;
            DateTime strdatetime = Convert.ToDateTime(f_strdatetime);
            if (!string.IsNullOrEmpty(f_strdatetime))
            {
                //取得上个月的26号
                start = DateTime.Parse((strdatetime.AddDays(1 - strdatetime.Day + 25).AddMonths(-1)).ToShortDateString() + " 00:00:00");
                //取得本月的26号
                end = DateTime.Parse((strdatetime.AddDays(1 - strdatetime.Day + 25).AddMonths(0)).ToShortDateString() + " 23:59:59");
            }
            //else
            //{
            //    //取得上个月的26号
            //    start = DateTime.Parse((DateTime.Now.AddDays(1 - DateTime.Now.Day + 25).AddMonths(-1)).ToShortDateString() + " 00:00:00");
            //    //取得本月的26号
            //    end = DateTime.Parse((DateTime.Now.AddDays(1 - DateTime.Now.Day + 25).AddMonths(0)).ToShortDateString() + " 23:59:59");
            //}

            #region 判断添加时间为上月26到本月26号之前
            DateTime fdateTime = Convert.ToDateTime(f_DateTime);
            if (DateTime.Compare(fdateTime, Convert.ToDateTime(start)) < 0)
            {
                return Error("添加日期应大于当前月上月26号");
            }
            if (DateTime.Compare(fdateTime, Convert.ToDateTime(end)) > 0)
            {
                return Error("添加日期应小于当前月本月26号");
            }
            #endregion

            #region 延期统计100204
            //延期统计100204
            var delayList = new BLL.T_Bus_WorkOrderReport().DataTableToDelayList(DbHelperSQL.Query($"SELECT A.F_WorkOrderId,B.F_MainDeptId, C.F_ID FROM T_Bus_WorkOrder A LEFT JOIN T_Bus_AssignedInfo B ON A.F_WorkOrderId = B.F_WorkOrderId LEFT JOIN T_Bus_DelayTime C ON B.F_Id = C.F_AssignedId where datediff(s, '{start}', A.F_CreateTime) > 0  and datediff(s, '{end}', A.F_CreateTime) < 0  and A.F_IsDelete = 0 AND A.F_WorkOrderId IS NOT NULL AND B.F_ID IS NOT NULL AND B.F_MainDeptId IS NOT NULL AND  B.F_IsDelete=0 and B.F_IsSure in (0,1,2) and  B.F_State in (0,1)  ").Tables[0]);
            var delayLists = delayList.Where(y => y.DeptId == f_DeptId).ToList();
            var delayQuery = delayLists.Where(y => y.DelayId > 0).ToList();    //延期
            var delayallcount = delayLists.Count();
            var delayCount = delayQuery.Count();
            var delayrate = delayallcount == 0 ? "0" : delayCount == 0 ? "0" : (delayCount / delayallcount * 100).ToString("f2");
            double delayc = 0;
            double.TryParse(delayrate, out delayc);
            //延期单数超过总办件数的5%扣1分，超过10%扣2分，超过15%扣3分，超过20%扣5分
            double workorderCount04 = 0;
            if (delayc > 5 && delayc <= 10)
            {
                workorderCount04 = -1;
            }
            else if (delayc > 10 && delayc <= 15)
            {
                workorderCount04 = -2;
            }
            else if (delayc > 15 && delayc <= 20)
            {
                workorderCount04 = -3;
            }
            else if (delayc > 20)
            {
                workorderCount04 = -5;
            }
            #endregion

            #region 不满意度评价100205
            var assignedList = assignedInfoBLL.DataTableToList(assignedInfoBLL.GetList($" F_MainDeptId = '{f_DeptId}' and F_IsDelete=0 and F_IsSure in (0,1,2) and  F_State in (0,1)   and  datediff(s,'{start}',F_CreateTime)>0 and datediff(s,'{end}',F_CreateTime)<0  ").Tables[0]).DistinctBy(y => y.F_WorkOrderId);
            //F_IsSatisfie 1不满意     F_IsReload 0不重办，>0重办次数
            var assignedListsS = assignedList.Where(y => y.F_IsSatisfie == 1 && (y.F_IsReload == 0 || y.F_IsReload == null)).ToList();   //每件扣1分 F_IsReload == 0没有重办
            var assignedListsR = assignedList.Where(y => y.F_IsSatisfie == 1 && y.F_IsReload > 0).ToList();    //每件扣2分 F_IsReload > 0重办次数
            int assignedCountS = assignedListsS.Count();
            int satisfieCountR = assignedListsR.Count() * 2;
            double nosatisfieCount = -(double)(assignedCountS + satisfieCountR);
            #endregion

            #region 逾期未办100201
            //逾期未办每件扣2分
            var outtimeQuery = assignedList.Where(y => y.F_LimitTime > end && y.F_FeedbackTime == null).ToList();   //F_LimitTime逾期 F_FeedbackTime==null未办
            int outtimeCount = outtimeQuery.Count() * 2;
            double outtimeCounts = -(double)outtimeCount;
            #endregion

            #region 电子工单按时办结
            //电子工单及书面交办件每按时办结100件加2分
            //及时办结
            var intimeQuery = assignedList.Where(y => y.F_IsOverdue == 0).ToList();    //F_IsOverdue == 0及时办结
            int intimeCount = (intimeQuery.Count() / 100) * 2;
            double intimeCounts = (double)intimeCount;
            #endregion

            //获取部门考核
            var assessmentList = bll.DataTableToList(bll.GetList($" F_DeptId = {f_DeptId} and DATEDIFF(s,'{start}',F_DateTime)>0 and DATEDIFF(s,'{end}',F_DateTime)<0 ").Tables[0]);
            var phone = assessmentList.Where(y => y.F_TypeCode == "1001").ToList();     //电话办理（20分）
            var workorder = assessmentList.Where(y => y.F_TypeCode == "1002").ToList(); //电子工单办理及书面交办件办理（60分）
            var send = assessmentList.Where(y => y.F_TypeCode == "1003").ToList();      //信息报送（15分）
            var elses = assessmentList.Where(y => y.F_TypeCode == "1004").ToList();     //其他（5分）
            var addgrade = assessmentList.Where(y => y.F_TypeCode == "2000").ToList();  //加分事项（加分不受100分限制；每月最高加10分）

            double phonesum = 20 + (double)phone.Sum(y => y.F_Grade);           //电话办理（20分）
            double workordersum = 60 + (double)workorder.Sum(y => y.F_Grade) + workorderCount04 + nosatisfieCount + outtimeCounts;   //电子工单办理及书面交办件办理（60分）
            double sendsum = 15 + (double)send.Sum(y => y.F_Grade);             //信息报送（15分）
            double elsenum = 5 + (double)elses.Sum(y => y.F_Grade);            //其他（5分）
            double handlednum = 100 + (double)(phone.Sum(y => y.F_Grade) + workorder.Sum(y => y.F_Grade) + send.Sum(y => y.F_Grade) + elses.Sum(y => y.F_Grade));    //办理情况评分（100分）
            double addgradenum = (double)addgrade.Sum(y => y.F_Grade) + intimeCounts;     //加分事项（加分不受100分限制；每月最高加10分）
            double totalnum = (double)(100 + phone.Sum(y => y.F_Grade) + workorder.Sum(y => y.F_Grade) + send.Sum(y => y.F_Grade) + elses.Sum(y => y.F_Grade) + addgrade.Sum(y => y.F_Grade));   //承办单位总分

            double p = phonesum + double.Parse(f_Grade);
            if (p < 0 && f_TypeCode == "1001")
            {
                return Error("电话办理最多扣除20分,还可扣" + phonesum + "分");
            }
            p = workordersum + double.Parse(f_Grade);
            if (p < 0 && f_TypeCode == "1002")
            {
                return Error("电话办理最多扣除60分,还可扣" + workordersum + "分");
            }
            p = sendsum + double.Parse(f_Grade);
            if (p < 0 && f_TypeCode == "1003")
            {
                return Error("电话办理最多扣除15分,还可扣" + sendsum + "分");
            }
            p = elsenum + double.Parse(f_Grade);
            if (p < 0 && f_TypeCode == "1004")
            {
                return Error("电话办理最多扣除5分,还可扣" + elsenum + "分");
            }
            p = addgradenum + double.Parse(f_Grade);
            if (p > 10 && f_TypeCode == "2000")
            {
                return Error("电话办理最多可加10分,还可加" + (10 - addgradenum) + "分");
            }

            Model.Rep_Dept_Assessment model = new Model.Rep_Dept_Assessment();
            if (id == 0)
            {
                model.F_DeptId = f_DeptId;
                model.F_TypeCode = f_TypeCode;
                model.F_GradeCode = f_GradeCode;
                model.F_Grade = decimal.Parse(f_Grade);
                model.F_Note = f_Note;
                model.F_DateTime = DateTime.Parse(f_DateTime);
                model.F_CreateTime = DateTime.Now;
                int n = bll.Add(model);
                if (n > 0)
                {
                    return Success("添加成功");
                }
                else
                {
                    return Error("添加失败");
                }
            }
            else
            {
                model = bll.GetModel(id);
                if (model != null)
                {
                    model.F_Id = id;
                    model.F_DeptId = f_DeptId;
                    model.F_TypeCode = f_TypeCode;
                    model.F_GradeCode = f_GradeCode;
                    model.F_Grade = decimal.Parse(f_Grade);
                    model.F_Note = f_Note;
                    model.F_DateTime = DateTime.Parse(f_DateTime);
                    if (bll.Update(model))
                    {
                        return Success("修改成功");
                    }
                    else
                    {
                        return Error("修改失败");
                    }
                }
                return Error("信息不存在");
            }
        }

        /// <summary>
        /// 获取一条详细信息
        /// </summary>
        /// <param name="infoid"></param>
        /// <returns></returns>
        public ActionResult GetInfo(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return Error("获取参数失败");
            }
            Model.Rep_Dept_Assessment model = bll.GetModel(int.Parse(id.Trim()));
            if (model != null)
            {
                return Success("获取成功", model);
            }
            else
            {
                return Error("获取失败");
            };
        }

        /// <summary>
        /// 删除信息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        //[Authority]
        public ActionResult DelInfo(string[] ids)
        {
            string idd = " ";
            foreach (string str in ids)
            {
                idd += str + ",";
            }
            if (string.IsNullOrEmpty(idd))
            {
                return Error("获取参数失败");
            }
            bool b = bll.DeleteList("" + idd.TrimEnd(',') + "");
            if (b)
            {
                return Success("删除成功");
            }
            else
            {
                return Error("删除失败");
            }
        }
        #endregion

        #region 某一部门绩效
        /// <summary>
        /// 获取某一部门绩效
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult GetDeptAssessmentByDeptId(DateTime strdatetime, string deptid)
        {
            if (string.IsNullOrEmpty(deptid)) {
                return Error("单位不能为空");
            }
            DateTime? start = null;
            DateTime? end = null;
            if (!string.IsNullOrEmpty(strdatetime.ToString()))
            {
                //取得上个月的26号
                start = DateTime.Parse((strdatetime.AddDays(1 - strdatetime.Day + 25).AddMonths(-1)).ToShortDateString() + " 00:00:00");
                //取得本月的26号
                end = DateTime.Parse((strdatetime.AddDays(1 - strdatetime.Day + 25).AddMonths(0)).ToShortDateString() + " 23:59:59");
            }
            else {
                //取得上个月的26号
                start = DateTime.Parse((DateTime.Now.AddDays(1 - DateTime.Now.Day + 25).AddMonths(-1)).ToShortDateString() + " 00:00:00");
                //取得本月的26号
                end = DateTime.Parse((DateTime.Now.AddDays(1 - DateTime.Now.Day + 25).AddMonths(0)).ToShortDateString() + " 23:59:59");
            }
            //var deptList = blldepartment.DataTableToList(blldepartment.GetList(" F_DeptNameSpell=3 ").Tables[0]);
            var assessmentList = bll.DataTableToList(bll.GetList($" DATEDIFF(s,'{start}',F_DateTime)>0 and DATEDIFF(s,'{end}',F_DateTime)<0 and F_DeptId = " + deptid + " ").Tables[0]);
                                   
            #region 延期统计100204
            //延期统计100204
            var delayList = new BLL.T_Bus_WorkOrderReport().DataTableToDelayList(DbHelperSQL.Query($"SELECT A.F_WorkOrderId,B.F_MainDeptId, C.F_ID FROM T_Bus_WorkOrder A LEFT JOIN T_Bus_AssignedInfo B ON A.F_WorkOrderId = B.F_WorkOrderId LEFT JOIN T_Bus_DelayTime C ON B.F_Id = C.F_AssignedId where datediff(s, '{start}', A.F_CreateTime) > 0  and datediff(s, '{end}', A.F_CreateTime) < 0  and A.F_IsDelete = 0 AND A.F_WorkOrderId IS NOT NULL AND B.F_ID IS NOT NULL AND B.F_MainDeptId IS NOT NULL AND  B.F_IsDelete=0 and B.F_IsSure in (0,1,2) and  B.F_State in (0,1)  ").Tables[0]);
            var delayLists = delayList.Where(y => y.DeptId == int.Parse(deptid)).ToList();
            var delayQuery = delayLists.Where(y => y.DelayId > 0).ToList();    //延期
            var delayallcount = delayLists.Count();
            var delayCount = delayQuery.Count();
            var delayrate = delayallcount == 0 ? "0" : delayCount == 0 ? "0" : ((double)delayCount / delayallcount * 100).ToString("f2");
            double delayc = 0;
            double.TryParse(delayrate, out delayc);
            //延期单数超过总办件数的5%扣1分，超过10%扣2分，超过15%扣3分，超过20%扣5分
            double workorderCount04 = 0;
            if (delayc > 5 && delayc <= 10)
            {
                workorderCount04 = -1;
            }
            else if (delayc > 10 && delayc <= 15)
            {
                workorderCount04 = -2;
            }
            else if (delayc > 15 && delayc <= 20)
            {
                workorderCount04 = -3;
            }
            else if (delayc > 20)
            {
                workorderCount04 = -5;
            }
            #endregion

            #region 不满意度评价100205
            var assignedList = assignedInfoBLL.DataTableToList(assignedInfoBLL.GetList($" F_MainDeptId = '{int.Parse(deptid)}' and F_IsDelete=0 and F_IsSure in (0,1,2) and  F_State in (0,1)   and  datediff(s,'{start}',F_CreateTime)>0 and datediff(s,'{end}',F_CreateTime)<0  ").Tables[0]).DistinctBy(y => y.F_WorkOrderId);
            //F_IsSatisfie 1不满意     F_IsReload 0不重办，>0重办次数
            var assignedListsS = assignedList.Where(y => y.F_IsSatisfie == 1 && (y.F_IsReload == 0 || y.F_IsReload == null)).ToList();   //每件扣1分 F_IsReload == 0没有重办
            var assignedListsR = assignedList.Where(y => y.F_IsSatisfie == 1 && y.F_IsReload > 0).ToList();    //每件扣2分 F_IsReload > 0重办次数
            int assignedCountS = assignedListsS.Count();
            int satisfieCountR = assignedListsR.Count() * 2;
            double nosatisfieCount = -(double)(assignedCountS + satisfieCountR);
            #endregion

            #region 逾期未办100201
            //逾期未办每件扣2分
            var outtimeQuery = assignedList.Where(y => y.F_LimitTime > end && y.F_FeedbackTime == null).ToList();   //F_LimitTime逾期 F_FeedbackTime==null未办
            int outtimeCount = outtimeQuery.Count() * 2;
            double outtimeCounts = -(double)outtimeCount;
            #endregion

            #region 电子工单按时办结
            //电子工单及书面交办件每按时办结100件加2分
            //及时办结
            var intimeQuery = assignedList.Where(y => y.F_IsOverdue == 0).ToList();    //F_IsOverdue == 0及时办结
            int intimeCount = (intimeQuery.Count() / 100) * 2;
            double intimeCounts = (double)intimeCount;
            #endregion

            var deptModel = blldepartment.GetModelList(" F_DeptId="+ deptid + " ").FirstOrDefault();

            var phone01 = assessmentList.Where(y => y.F_GradeCode == "100101").ToList();
            var phone02 = assessmentList.Where(y => y.F_GradeCode == "100102").ToList();
            var workorder01 = assessmentList.Where(y => y.F_GradeCode == "100201").ToList();    //逾期办结未说明原因，逾期未办
            var workorder02 = assessmentList.Where(y => y.F_GradeCode == "100202").ToList();
            var workorder03 = assessmentList.Where(y => y.F_GradeCode == "100203").ToList();
            //var workorder04 = assessmentList.Where(y => y.F_GradeCode == "100204").ToList();
            //var workorder05 = assessmentList.Where(y => y.F_GradeCode == "100205").ToList();
            var workorder06 = assessmentList.Where(y => y.F_GradeCode == "100206").ToList();
            var send01 = assessmentList.Where(y => y.F_GradeCode == "100301").ToList();
            var send02 = assessmentList.Where(y => y.F_GradeCode == "100302").ToList();
            var send03 = assessmentList.Where(y => y.F_GradeCode == "100303").ToList();
            var else01 = assessmentList.Where(y => y.F_GradeCode == "100401").ToList();
            var else02 = assessmentList.Where(y => y.F_GradeCode == "100402").ToList();
            var else03 = assessmentList.Where(y => y.F_GradeCode == "100403").ToList();
            var addgrade01 = assessmentList.Where(y => y.F_GradeCode == "200001").ToList();
            var addgrade02 = assessmentList.Where(y => y.F_GradeCode == "200002").ToList();
            var addgrade03 = assessmentList.Where(y => y.F_GradeCode == "200003").ToList();
            var addgrade04 = assessmentList.Where(y => y.F_GradeCode == "200004").ToList();
            var addgrade05 = assessmentList.Where(y => y.F_GradeCode == "200005").ToList();
            var addgrade06 = assessmentList.Where(y => y.F_GradeCode == "200006").ToList();     //电子工单、书面交办
            var addgrade07 = assessmentList.Where(y => y.F_GradeCode == "200007").ToList();
            var total = new
            {
                deptname = deptModel.F_DeptName ?? "",
                gphone01 = phone01.Sum(x => x.F_Grade),
                gphone02 = phone02.Sum(x => x.F_Grade),
                gworkorder01 = (double)workorder01.Sum(x => x.F_Grade) + outtimeCounts,     //逾期办结未说明原因，逾期未办
                gworkorder02 = workorder02.Sum(x => x.F_Grade),
                gworkorder03 = workorder03.Sum(x => x.F_Grade),
                gworkorder04 = workorderCount04,    //延期工单办理
                gworkorder05 = nosatisfieCount,     //不满意
                gworkorder06 = workorder06.Sum(x => x.F_Grade),
                gsend01 = send01.Sum(x => x.F_Grade),
                gsend02 = send02.Sum(x => x.F_Grade),
                gsend03 = send03.Sum(x => x.F_Grade),
                gelse01 = else01.Sum(x => x.F_Grade),
                gelse02 = else02.Sum(x => x.F_Grade),
                gelse03 = else03.Sum(x => x.F_Grade),
                gaddgrade01 = addgrade01.Sum(x => x.F_Grade),
                gaddgrade02 = addgrade02.Sum(x => x.F_Grade),
                gaddgrade03 = addgrade03.Sum(x => x.F_Grade),
                gaddgrade04 = addgrade04.Sum(x => x.F_Grade),
                gaddgrade05 = addgrade05.Sum(x => x.F_Grade),
                gaddgrade06 = (double)addgrade06.Sum(x => x.F_Grade) + intimeCounts,    //电子工单、书面交办
                gaddgrade07 = addgrade07.Sum(x => x.F_Grade),
            };
            var obj = new
            {
                rows = "",
                total = total
            };
            return Content(obj.ToJson());
        }
        #endregion

        #region 统计部门绩效
        /// <summary>
        /// 统计部门绩效
        /// </summary>
        /// <param name="strdatetime"></param>
        /// <returns></returns>
        public ActionResult GetDeptAssessment(DateTime strdatetime, bool isExport = false)
        {
            List<DeptAssessment> list = new List<DeptAssessment>();
            var deptList = blldepartment.DataTableToList(blldepartment.GetList(" F_DeptNameSpell=3 ").Tables[0]);

            int total = 0;
            DateTime? start = null;
            DateTime? end = null;
            if (!string.IsNullOrEmpty(strdatetime.ToString()))
            {
                //取得上个月的26号
                start = DateTime.Parse((strdatetime.AddDays(1 - strdatetime.Day + 25).AddMonths(-1)).ToShortDateString() + " 00:00:00");
                //取得本月的26号
                end = DateTime.Parse((strdatetime.AddDays(1 - strdatetime.Day + 25).AddMonths(0)).ToShortDateString() + " 23:59:59");
            }
            else
            {
                //取得上个月的26号
                start = DateTime.Parse((DateTime.Now.AddDays(1 - DateTime.Now.Day + 25).AddMonths(-1)).ToShortDateString() + " 00:00:00");
                //取得本月的26号
                end = DateTime.Parse((DateTime.Now.AddDays(1 - DateTime.Now.Day + 25).AddMonths(0)).ToShortDateString() + " 23:59:59");
            }
            var assessmentList = bll.DataTableToList(bll.GetList($" DATEDIFF(s,'{start}',F_DateTime)>0 and DATEDIFF(s,'{end}',F_DateTime)<0 ").Tables[0]);
            total = deptList.Count;
            deptList.ForEach(x =>
            {
                var phone = assessmentList.Where(y => y.F_DeptId == x.F_DeptId && y.F_TypeCode == "1001").ToList();     //电话办理（20分）
                var workorder = assessmentList.Where(y => y.F_DeptId == x.F_DeptId && y.F_TypeCode == "1002").ToList(); //电子工单办理及书面交办件办理（60分）
                var send = assessmentList.Where(y => y.F_DeptId == x.F_DeptId && y.F_TypeCode == "1003").ToList();      //信息报送（15分）
                var elses = assessmentList.Where(y => y.F_DeptId == x.F_DeptId && y.F_TypeCode == "1004").ToList();     //其他（5分）
                var addgrade = assessmentList.Where(y => y.F_DeptId == x.F_DeptId && y.F_TypeCode == "2000").ToList();  //加分事项（加分不受100分限制；每月最高加10分）

                #region 延期统计100204
                //延期统计100204
                var delayList = new BLL.T_Bus_WorkOrderReport().DataTableToDelayList(DbHelperSQL.Query($"SELECT A.F_WorkOrderId,B.F_MainDeptId, C.F_ID FROM T_Bus_WorkOrder A LEFT JOIN T_Bus_AssignedInfo B ON A.F_WorkOrderId = B.F_WorkOrderId LEFT JOIN T_Bus_DelayTime C ON B.F_Id = C.F_AssignedId where datediff(s, '{start}', A.F_CreateTime) > 0  and datediff(s, '{end}', A.F_CreateTime) < 0  and A.F_IsDelete = 0 AND A.F_WorkOrderId IS NOT NULL AND B.F_ID IS NOT NULL AND B.F_MainDeptId IS NOT NULL AND  B.F_IsDelete=0 and B.F_IsSure in (0,1,2) and  B.F_State in (0,1)  ").Tables[0]);
                var delayLists = delayList.Where(y => y.DeptId == x.F_DeptId).ToList();
                var delayQuery = delayLists.Where(y => y.DelayId > 0).ToList();    //延期
                var delayallcount = delayLists.Count();
                var delayCount = delayQuery.Count();
                var delayrate = delayallcount == 0 ? "0" : delayCount == 0 ? "0" : (delayCount / delayallcount * 100).ToString("f2");
                double delayc = 0;
                double.TryParse(delayrate, out delayc);
                //延期单数超过总办件数的5%扣1分，超过10%扣2分，超过15%扣3分，超过20%扣5分
                double workorderCount04 = 0;
                if (delayc > 5 && delayc <= 10)
                {
                    workorderCount04 = -1;
                }
                else if (delayc > 10 && delayc <= 15)
                {
                    workorderCount04 = -2;
                }
                else if (delayc > 15 && delayc <= 20)
                {
                    workorderCount04 = -3;
                }
                else if (delayc > 20)
                {
                    workorderCount04 = -5;
                }
                #endregion

                #region 不满意度评价100205
                var assignedList = assignedInfoBLL.DataTableToList(assignedInfoBLL.GetList($" F_MainDeptId = '{x.F_DeptId}' and F_IsDelete=0 and F_IsSure in (0,1,2) and  F_State in (0,1)   and  datediff(s,'{start}',F_CreateTime)>0 and datediff(s,'{end}',F_CreateTime)<0  ").Tables[0]).DistinctBy(y => y.F_WorkOrderId);
                //F_IsSatisfie 1不满意     F_IsReload 0不重办，>0重办次数
                var assignedListsS = assignedList.Where(y => y.F_IsSatisfie == 1 && (y.F_IsReload == 0 || y.F_IsReload == null)).ToList();   //每件扣1分 F_IsReload == 0没有重办
                var assignedListsR = assignedList.Where(y => y.F_IsSatisfie == 1 && y.F_IsReload > 0).ToList();    //每件扣2分 F_IsReload > 0重办次数
                int assignedCountS = assignedListsS.Count();
                int satisfieCountR = assignedListsR.Count() * 2;
                double nosatisfieCount = -(double)(assignedCountS + satisfieCountR);
                #endregion

                #region 逾期未办100201
                //逾期未办每件扣2分
                var outtimeQuery = assignedList.Where(y => y.F_LimitTime > end && y.F_FeedbackTime == null).ToList();   //F_LimitTime逾期 F_FeedbackTime==null未办
                int outtimeCount = outtimeQuery.Count() * 2;
                double outtimeCounts = -(double)outtimeCount;
                #endregion

                #region 电子工单按时办结
                //电子工单及书面交办件每按时办结100件加2分
                //及时办结
                var intimeQuery = assignedList.Where(y => y.F_IsOverdue == 0).ToList();    //F_IsOverdue == 0及时办结
                int intimeCount = (intimeQuery.Count() / 100) * 2;
                double intimeCounts = (double)intimeCount;
                #endregion

                double phonecount = 20 + (double)phone.Sum(y => y.F_Grade);           //电话办理（20分）
                if (phonecount < 0) {
                    phonecount = 0;
                }
                double workordercount = 60 + (double)workorder.Sum(y => y.F_Grade) + workorderCount04 + nosatisfieCount + outtimeCounts;   //电子工单办理及书面交办件办理（60分）
                if (workordercount < 0) {
                    workordercount = 0;
                }
                double sendcount = 15 + (double)send.Sum(y => y.F_Grade);             //信息报送（15分）
                if (sendcount < 0) {
                    sendcount = 0;
                }
                double elsecount = 5 + (double)elses.Sum(y => y.F_Grade);            //其他（5分）
                if (elsecount < 0) {
                    elsecount = 0;
                }
                //double handledcount = 100 + (double)(phone.Sum(y => y.F_Grade) + workorder.Sum(y => y.F_Grade) + send.Sum(y => y.F_Grade) + elses.Sum(y => y.F_Grade));    //办理情况评分（100分）
                double handledcount = phonecount + workordercount + sendcount + elsecount;    //办理情况评分（100分）
                if (handledcount < 0) {
                    handledcount = 0;
                }
                double addgradecount = (double)addgrade.Sum(y => y.F_Grade) + intimeCounts;     //加分事项（加分不受100分限制；每月最高加10分）
                if (addgradecount > 10) {
                    addgradecount = 10;
                }

                list.Add(new DeptAssessment
                {
                    deptid = x.F_DeptId,
                    deptname = x.F_DeptName ?? "",
                    phonesum = phonecount,           //电话办理（20分）
                    workordersum = workordercount,   //电子工单办理及书面交办件办理（60分）
                    sendsum = sendcount,             //信息报送（15分）
                    elsenum = elsecount,            //其他（5分）
                    handlednum = handledcount,    //办理情况评分（100分）
                    addgradenum = addgradecount,     //加分事项（加分不受100分限制；每月最高加10分）
                    totalnum = (double)(phonecount + workordercount + sendcount + elsecount + addgradecount),   //承办单位总分
                });

            });
            if (isExport)
            {
                var dt = list.ToDataTable(new string[] { "deptname", "phonesum", "workordersum", "sendsum", "elsenum", "handlednum", "addgradenum", "totalnum" });
                new NPOIHelper().ExportToExcel($"二级单位绩效考核统计{Convert.ToDateTime(start).ToString("yyyyMMdd")}-{Convert.ToDateTime(end).ToString("yyyyMMdd")}", dt, new string[] { "单位名称", "电话办理（20分）", "电子工单及书面交办件办理（60分）", "信息报送（15分）", "其他（5分）", "办理情况评分（100分）", "加分事项（每月最高加10分）", "总计" });
                return Success("导出excel");
            }
            var obj = new
            {
                rows = list,
                total = total
            };
            return Content(obj.ToJson());

        }
        #endregion
    }
}