using System;
using System.Collections.Generic;
using System.Common;
using System.IRepositories;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace TVShoppingCallCenter_ZLJ.Controllers.ManagementCenter
{
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class ManagementCenterController : BaseController
    {
        private readonly IBus_AfterSaleRepository _busAfterSaleRepository;//售后
        private readonly IBus_OrderRepository _bus_OrderRepository;//订单
        private readonly ICus_VipInfoRepository _cus_vip_infoRepository;//客户
        private readonly ISys_UserAccountRepository _sys_useraccountRepository;//用户
        private readonly ISys_TaskManagementRepository _sys_taskmanagement_Repository;//任务
        private readonly ISys_DepartmentRepository _sys_departmentRepository;//部门
        private readonly ISys_PlanManagemenRepository _sys_planmanagemenRepository;//广告
        private readonly ISys_MarketingRepository _sys_marketing_Repository;//营销活动
        private readonly ISys_TodoManagementRepository _sys_todomanagementrepository;
        private readonly ISys_MediaManagementRepository _sys_mediaManagement_Repository;//媒体
        private readonly ICall_CallRecordsRepository _busCallRecordsRepository;//通话记录表
        public ManagementCenterController(ICus_VipInfoRepository cus_vip_infoRepository, ISys_TaskManagementRepository sys_taskmanagement_Repository, ISys_DepartmentRepository sys_departmentRepository, ISys_UserAccountRepository sys_useraccountRepository,IBus_OrderRepository bus_OrderRepository, ISys_PlanManagemenRepository sys_planmanagemenRepository,ISys_MarketingRepository sys_marketing_Repository, ISys_TodoManagementRepository sys_todomanagementrepository, IBus_AfterSaleRepository busAfterSaleRepository, ISys_MediaManagementRepository sys_mediaManagement_Repository, ICall_CallRecordsRepository busCallRecordsRepository)
        {
            _bus_OrderRepository = bus_OrderRepository;
            _cus_vip_infoRepository = cus_vip_infoRepository;
            _sys_taskmanagement_Repository = sys_taskmanagement_Repository;
            _sys_departmentRepository = sys_departmentRepository;
            _sys_useraccountRepository = sys_useraccountRepository;
            _sys_planmanagemenRepository = sys_planmanagemenRepository;
            _sys_marketing_Repository = sys_marketing_Repository;
            _sys_todomanagementrepository = sys_todomanagementrepository;
            _busAfterSaleRepository = busAfterSaleRepository;
            _sys_mediaManagement_Repository = sys_mediaManagement_Repository;
            _busCallRecordsRepository = busCallRecordsRepository;
        }
        /// <summary>
        /// 实时销售行为分析
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        [HttpGet("realtimesales")]
        public async Task<IActionResult> Realtimesales(string time)
        {
            if (string.IsNullOrEmpty(time))
                time = DateTime.Now.ToString("yyyy-MM-dd");
            List<IConditionalModel> cosModels = new List<IConditionalModel>();
            cosModels.Add(new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.Equal, FieldValue = ((int)EnumDelState.Enabled).ToString() });
            cosModels.Add(new ConditionalModel() { FieldName = "F_CreateOn", ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = time + " 00:00:00" });
            cosModels.Add(new ConditionalModel() { FieldName = "F_CreateOn", ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = time + " 23:59:59" });
            var todaycustomer = _cus_vip_infoRepository.GetListALL(cosModels, "F_CreateOn asc").Result;//新增客户
            List<IConditionalModel> cosoldModels = new List<IConditionalModel>();
            cosoldModels.Add(new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.Equal, FieldValue = ((int)EnumDelState.Enabled).ToString() });
            cosoldModels.Add(new ConditionalModel() { FieldName = "F_CreateOn", ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = DateTime.Parse(time ).AddDays(-1).ToString ("yyyy-MM-dd") + " 00:00:00"});
            cosoldModels.Add(new ConditionalModel() { FieldName = "F_CreateOn", ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = DateTime.Parse(time).AddDays(-1).ToString("yyyy-MM-dd") + " 23:59:59" });
            var yesterday= _cus_vip_infoRepository.GetListALL(cosoldModels, "F_CreateOn asc").Result;//昨日新增客户


            int newcustomer = todaycustomer != null ? todaycustomer.Count ():0;//新增客户
            int oldcustomer = yesterday != null ? yesterday.Count() : 0;//昨日新增客户



            List<IConditionalModel> cosorderModels = new List<IConditionalModel>();
            cosorderModels.Add(new ConditionalModel() { FieldName = "F_AddTime", ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = time + " 00:00:00" });
            cosorderModels.Add(new ConditionalModel() { FieldName = "F_AddTime", ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = time + " 23:59:59" });
            int neworder = _bus_OrderRepository.GetListALL(cosorderModels, "F_AddTime asc").Result.Count;

            List<IConditionalModel> oldorderModels = new List<IConditionalModel>();
            oldorderModels.Add(new ConditionalModel() { FieldName = "F_AddTime", ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = DateTime.Parse(time).AddDays(-1).ToString("yyyy-MM-dd") + " 00:00:00" });
            oldorderModels.Add(new ConditionalModel() { FieldName = "F_AddTime", ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = DateTime.Parse(time).AddDays(-1).ToString("yyyy-MM-dd") + " 23:59:59" });
            int oldorder = _bus_OrderRepository.GetListALL(oldorderModels, "F_AddTime asc").Result.Count ;


            int newaftersale = _busAfterSaleRepository.GetListALL (cosorderModels, " F_AddTime DESC").Result.Count ;//售后订单量

            int oldaftersale = _busAfterSaleRepository.GetListALL(oldorderModels, " F_AddTime DESC").Result.Count;//昨日售后订单量

            List<IConditionalModel> conModels = new List<IConditionalModel>();
            int newcustomers = 0;//新客户下单量
            int oldcustomers = 0;//昨日新客户下单量
            int newcustomerorder = 0;//老客户下单量
            int oldcustomerorder = 0;//昨日老客户下单量
            string vipid = "";
            if (newcustomer>0)
            {
                string  F_VipId = "";
                foreach (var it in todaycustomer)
                {
                    if (F_VipId == "")
                        F_VipId = it.F_ID + "";
                    else
                        F_VipId +=","+ it.F_ID + "";
                    if (vipid == "")
                        vipid = it.F_ID + "";
                    else
                        vipid += "," + it.F_ID + "";
                }
                if (F_VipId == "")
                    newcustomers = 0;
                else 
                newcustomers = _bus_OrderRepository.GetListALL(ConModels(DateTime .Parse (time), F_VipId,true ), " F_AddTime DESC").Result != null ? _bus_OrderRepository.GetListALL(ConModels(DateTime.Parse(time), F_VipId, true), " F_AddTime DESC").Result.Count : 0;
            }
            if (vipid == "")
                newcustomerorder = 0;
            else
                newcustomerorder = _bus_OrderRepository.GetListALL(ConModels(DateTime.Parse(time), vipid, false), " F_AddTime DESC").Result != null ? _bus_OrderRepository.GetListALL(ConModels(DateTime.Parse(time), vipid, false), " F_AddTime DESC").Result.Count : 0;
            if (oldcustomer > 0)
            { 
                string F_VipId = "";
                foreach (var it in yesterday)
                {
                    if (F_VipId == "")
                        F_VipId = it.F_ID + "";
                    else
                        F_VipId += "," + it.F_ID + "";
                    if (vipid == "")
                        vipid = it.F_ID + "";
                    else
                        vipid += "," + it.F_ID + "";
                }
                if (F_VipId == "")
                    oldcustomers = 0;
                else 
                oldcustomers = _bus_OrderRepository.GetListALL(ConModels(DateTime.Parse(time).AddDays (-1), F_VipId, true), " F_AddTime DESC").Result != null ? _bus_OrderRepository.GetListALL(ConModels(DateTime.Parse(time).AddDays(-1), F_VipId,true), " F_AddTime DESC").Result.Count : 0;
            }
            if (vipid == "")
                oldcustomerorder = 0;
            else
                oldcustomerorder = _bus_OrderRepository.GetListALL(ConModels(DateTime.Parse(time).AddDays(-1), vipid, false), " F_AddTime DESC").Result != null ? _bus_OrderRepository.GetListALL(ConModels(DateTime.Parse(time).AddDays(-1), vipid, false), " F_AddTime DESC").Result.Count : 0;
            var obj = new
            {
                state = "success",
                message = "成功",
                 newcustomer,//新增客户
                oldcustomer,//昨日新增客户
                neworder,//新增客户
                oldorder ,//昨日新增客户
                newaftersale ,//售后订单量
                oldaftersale,//昨日订单量
                newcustomers,//新客户下单量
                oldcustomers,//昨日新客户下单量
                newcustomerorder,//老客户下单量
                oldcustomerorder,//昨日老客户下单量

            };
            return Content(obj.ToJson());
        }
    
            private List<IConditionalModel> ConModels (DateTime time,string F_VipId,bool n )
        {
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            conModels.Add(new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = "0" });
            conModels.Add(new ConditionalModel() { FieldName = "F_AddTime", ConditionalType = ConditionalType.LessThanOrEqual, FieldValue = time.ToString("yyyy-MM-dd 23:59:59") });
            conModels.Add(new ConditionalModel() { FieldName = "F_AddTime", ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = time.ToString("yyyy-MM-dd 00:00:00") });
            if (n )
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_VipId", ConditionalType = ConditionalType.In, FieldValue = F_VipId });
            }
            else
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_VipId", ConditionalType = ConditionalType.NotIn, FieldValue = F_VipId });
            }
            return conModels;
        }
        /// <summary>
        /// 当月任务总量
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        [HttpGet("totaltasks")]
        public async Task<IActionResult> Totaltasks(string time)
        {
            if (string.IsNullOrEmpty(time))
                time = DateTime.Now.ToString("yyyy-MM");
            string user = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            int userid= _sys_useraccountRepository.GetSingle(x => x.F_UserCode  == user&&x.F_DeleteFlag ==0).Result!=null ? _sys_useraccountRepository.GetSingle(x => x.F_UserCode == user && x.F_DeleteFlag == 0).Result.F_UserId:0;
            if (userid > 0)
            {
                List<IConditionalModel> conModels = new List<IConditionalModel>();
                conModels.Add(new ConditionalModel() { FieldName = "F_IsDelete", ConditionalType = ConditionalType.Equal , FieldValue = "0" });
                conModels.Add(new ConditionalModel() { FieldName = "F_CreateTime", ConditionalType = ConditionalType.LessThanOrEqual, FieldValue = DateTime .Parse ( time).AddMonths (1).AddDays (-1).ToString("yyyy-MM-dd 23:59:59") });
                conModels.Add(new ConditionalModel() { FieldName = "F_CreateTime", ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = DateTime.Parse(time).ToString("yyyy-MM-01 00:00:00") });
                conModels.Add(new ConditionalModel() { FieldName = "F_Tasker", ConditionalType = ConditionalType.Equal , FieldValue = userid+"" });
                var task = _sys_taskmanagement_Repository.GetListALL(conModels, " F_CreateTime DESC").Result;
                float tasktotal = 0, taskcurrent = 0;string progress = "0";
                if (task!=null )
                {
                    tasktotal =(float )task.Select(x => x.F_Money).Sum();
                    taskcurrent = (float)task.Select(x => x.F_Currentamount).Sum();
                    if (tasktotal>0)
                    progress = string.Format("{0:f2}", taskcurrent / tasktotal * 100);
                }
                var obj = new
                {
                    state = "success",
                    message = "成功",
                    taskcurrent,//当前任务量
                    tasktotal,//任务总量
                    progress,//进度
                };
                return Content(obj.ToJson());
            }
                else
                return Error("查询失败");

        }
        public class Dictionaries
        {
            public string key;
            public decimal value;
        }
        /// <summary>
        /// 待办事项
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        [HttpGet("todolist")]
        public async Task<IActionResult> Todolist(string time)
        {
            string user = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            DateTime dateTime = DateTime.Now;
            if (!string.IsNullOrEmpty(time))
                dateTime = DateTime.Parse (time);
            List<IConditionalModel> orderModels = new List<IConditionalModel>();
            int days = Thread.CurrentThread.CurrentUICulture.Calendar.GetDaysInMonth(dateTime.Year, dateTime.Month - 1);//获取天数
            orderModels.Add(new ConditionalModel() { FieldName = "F_AddTime", ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = dateTime.ToString("yyyy-MM-01") });
            orderModels.Add(new ConditionalModel() { FieldName = "F_AddTime", ConditionalType = ConditionalType.LessThanOrEqual, FieldValue = dateTime.ToString("yyyy-MM") + "-" + days + " 23:59:59" });
            orderModels.Add(new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue ="0" });
            var Order = _bus_OrderRepository.GetListALL(orderModels, "F_AddTime asc").Result;//订单总量
                int tobeexamine=0/*待审核*/, reviewreturn = 0/*审核退回*/, tobedistribution = 0/*待分配*/,
                aftersale = 0/*售后*/, tobecollected = 0/*待回款*/, toberefunded = 0/*待退款*/, pendingclaims = 0/*待理赔*/, tobecontacted = 0/*待联系客户*/;
            List<IConditionalModel> cosorderModels = new List<IConditionalModel>();
            cosorderModels.Add(new ConditionalModel() { FieldName = "F_AddTime", ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = dateTime.ToString("yyyy-MM-01") });
            cosorderModels.Add(new ConditionalModel() { FieldName = "F_AddTime", ConditionalType = ConditionalType.LessThanOrEqual, FieldValue = dateTime.ToString("yyyy-MM") + "-" + days + " 23:59:59" });
            var AfterOrder = _busAfterSaleRepository.GetListALL(cosorderModels, "F_AddTime asc").Result;//订单总量
            List<Dictionaries> tobetask = new List<Dictionaries>();
                if (Order!=null )
                {
                    tobeexamine = Order.Where(x => x.F_State == 1).Count();//待审核
                    reviewreturn = Order.Where(x => x.F_State == 2).Count();//审核退回
                    tobedistribution = Order.Where(x => x.F_State == 3).Count();//审核退回
                    tobecollected = Order.Where(x => x.F_PayState == 0).Count();//待回款
                toberefunded = Order.Where(x => x.F_PayState  == 2).Count();
            }
                if (AfterOrder!=null )
            {
                aftersale = AfterOrder.Count();//售后订单
                toberefunded += AfterOrder.Where(x => x.F_Type == 2 || x.F_Type == 3).Count();
                pendingclaims = AfterOrder.Where(x => x.F_Type ==6).Count();
            }
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            conModels.Add(new ConditionalModel() { FieldName = "F_IsDelete", ConditionalType = ConditionalType.Equal , FieldValue = "0" });
         //   conModels.Add(new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.Equal, FieldValue = "0" });
            conModels.Add(new ConditionalModel() { FieldName = "F_CreateUser", ConditionalType = ConditionalType.Equal, FieldValue = user });
            var Todo = _sys_todomanagementrepository.GetListALL(conModels, " F_CreateTime DESC").Result;//待办总量 
            if (Todo != null)
            {
                tobecontacted = Todo.Where(x => x.F_Type == 1&&x .F_State ==0).Count();//待联系客户
               var tobe = Todo.Where(x => x.F_Type == 0);//审核退回
                if (tobe!=null )
                {
                    foreach (var it  in tobe)
                    {
                        Dictionaries dictionaries = new Dictionaries();
                        dictionaries.key = it.F_Name;
                        dictionaries.value =(int ) it.F_State;
                        tobetask.Add(dictionaries);
                    }
                }
               
            }

            var obj = new
                {
                    state = "success",
                    message = "成功",
                    tobeexamine,//待审核
                    reviewreturn,//审核退回
                    tobedistribution,//待分配
                    aftersale,//售后
                    tobecollected,//待回款
                    toberefunded,//待退款
                    pendingclaims,//待理赔
                    tobecontacted,//待联系客户
                    tobetask,
                };
                return Content(obj.ToJson());
        }
        public class Personalranking
        {
            public int  Serialnumber;
            public int userid;
            public string name;
            public int Orderquantity;
            public decimal Totalsales;
        }
        /// <summary>
        /// 排行榜
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        [HttpGet("rankinglist")]
        public async Task<IActionResult> RankingList(int type=0)
        {
            DateTime starttime, endtime;
            if (type==0)
            {
                starttime = DateTime.Now.AddMonths(-1).AddDays(1);
                endtime = DateTime.Now;
            }
                else
            {
                starttime = DateTime.Now;
                endtime = DateTime.Now;
            }
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            conModels.Add(new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = "0" });
            conModels.Add(new ConditionalModel() { FieldName = "F_AddTime", ConditionalType = ConditionalType.LessThanOrEqual, FieldValue = endtime.ToString("yyyy-MM-dd 23:59:59") });
            conModels.Add(new ConditionalModel() { FieldName = "F_AddTime", ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = starttime.ToString("yyyy-MM-dd 00:00:00") });
            var Order = _bus_OrderRepository.GetListALL(conModels, " F_AddTime DESC").Result;//订单总量
            List<Dictionaries> tobetask = new List<Dictionaries>();
            List<Personalranking> personalrankings = new List<Personalranking>();
            var query = Order.GroupBy(x => new { x.F_AddUser ,x .F_AddUserName   }).Select(x => new { F_RealPrice = x.Select(y => y.F_RealPrice).Sum(), x.Key.F_AddUser ,x.Key .F_AddUserName , total = x .Select (y=>1).Sum () });
            if (query != null)
            {
                var tobetasklist = query.OrderByDescending(x => x.F_RealPrice).ToList();
                int i = 0;
                foreach (var it in tobetasklist)
                {
                    i++;
                    Personalranking personalranking = new Personalranking();
                    personalranking.Serialnumber = i;
                    personalranking.name = it.F_AddUserName;
                    personalranking.userid = it.F_AddUser;
                    personalranking.Orderquantity = it.total;
                    personalranking.Totalsales = it.F_RealPrice;
                    personalrankings.Add(personalranking);
                 }
                foreach ( var it in personalrankings)
                {
                    Dictionaries dictionaries = new Dictionaries();
                    var user = _sys_useraccountRepository.GetSingle(x => x.F_UserId == it.userid).Result;
                    if (user != null )
                    {
                        dictionaries.key = _sys_departmentRepository.GetSingle(x => x.F_DeptId == user.F_DeptId).Result != null ?
                            _sys_departmentRepository.GetSingle(x => x.F_DeptId == user.F_DeptId).Result.F_DeptName : "";
                    }
                    dictionaries.value = it.Totalsales;
                    tobetask.Add(dictionaries);
                }
              
             }
            var totask = tobetask.GroupBy(x => new { x.key }).Select(x => new { F_RealPrice = x.Select(y => y.value).Sum(), x.Key.key });
            var obj = new
                {
                    state = "success",
                    message = "成功",
                    personalrankings,
                    totask
                };
                return Content(obj.ToJson());
        }
        /// <summary>
        /// 重要提醒
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        [HttpGet("reminder")]
        public async Task<IActionResult> Reminder(string time)
        {
            if (string .IsNullOrEmpty (time))
                time = DateTime.Now.ToString("yyyy-MM-dd");
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            conModels.Add(new ConditionalModel() { FieldName = "F_Type", ConditionalType = ConditionalType.Equal , FieldValue = "0" });
            conModels.Add(new ConditionalModel() { FieldName = "F_EndTime", ConditionalType = ConditionalType.LessThanOrEqual, FieldValue = time+" 23:59:59" });
            conModels.Add(new ConditionalModel() { FieldName = "F_StartTime", ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = time +" 00:00:00" });
            conModels.Add(new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.Equal , FieldValue = "0"});
            conModels.Add(new ConditionalModel() { FieldName = "F_IsDelete", ConditionalType = ConditionalType.Equal, FieldValue = "0" });
            
            string week = Week(DateTime.Parse(time));
            var plan = _sys_planmanagemenRepository.GetListALL(conModels, " F_CreateTime DESC").Result;//广告总量
            List<IConditionalModel> conModel = new List<IConditionalModel>();
            conModel.Add(new ConditionalModel() { FieldName = "F_IsDelete", ConditionalType = ConditionalType.Equal, FieldValue = "0" });
            conModel.Add(new ConditionalModel() { FieldName = "F_EndTime", ConditionalType = ConditionalType.LessThanOrEqual, FieldValue = time + " 23:59:59" });
            conModel.Add(new ConditionalModel() { FieldName = "F_StartTime", ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = time + " 00:00:00" });
          
            var marketin = _sys_marketing_Repository.GetListALL(conModel, " F_CreateTime DESC").Result;//营销活动
            int advertisement = 0, marketing=0;
            if (plan!=null )
                advertisement = plan.Where (x => x.F_PlayDate.Split(',').Contains(week) == true).Count ();
            if (marketin != null)
                marketing = marketin.Count();

            var obj = new
            {
                state = "success",
                message = "成功",
                advertisement,
                marketing
            };
            return Content(obj.ToJson());
        }
        public string Week(DateTime time)
        {
            string week = "";
            string dt = time.DayOfWeek.ToString();
            switch (dt)
            {
                case "Monday":
                    week = "周一";
                    break;
                case "Tuesday":
                    week = "周二";
                    break;
                case "Wednesday":
                    week = "周三";
                    break;
                case "Thursday":
                    week = "周四";
                    break;
                case "Friday":
                    week = "周五";
                    break;
                case "Saturday":
                    week = "周六";
                    break;
                case "Sunday":
                    week = "周日";
                    break;
            }

            return week;
        }


        private  class AftersaleInput
        {
            public string time;//时间
            public string name;//姓名
            public int total;//总数
            public int  problem;//产品问题
            public int warehousehair;//仓库错发漏发
            public int Saleserror;//销售错发漏发
            public int refund;//退款单数
            public decimal refundamount;//退款金额
            public int Totalaftersales;//售后总计
            public int delivergoods;//月总发货数
            public string exchange;//调换所占总发货比例
        }


        /// <summary>
        /// 售后表
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        [HttpGet("aftersale")]
        public async Task<IActionResult> Aftersale(string month)
        {
           // string user = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            DateTime time = DateTime.Now;
            if (!string.IsNullOrEmpty(month))
                time = DateTime.Parse (month);
           
            int   days = Thread.CurrentThread.CurrentUICulture.Calendar.GetDaysInMonth(time.Year, time.Month - 1);//获取天数
            if (time.Month == DateTime.Now.Month)
            {
                days = DateTime.Now.Day;
            }
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            conModels.Add(new ConditionalModel() { FieldName = "F_AddTime", ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = time.ToString("yyyy-MM-01") });
            conModels.Add(new ConditionalModel() { FieldName = "F_AddTime", ConditionalType = ConditionalType.LessThanOrEqual, FieldValue = time.ToString("yyyy-MM") + "-" + days + " 23:59:59" });
            var after = _busAfterSaleRepository.GetListALL(conModels, "F_AddTime asc ").Result;
            conModels.Add(new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.Equal, FieldValue = "6" });
            var order = _bus_OrderRepository.GetListALL(conModels, "F_AddTime asc ").Result;


            var dept = _sys_departmentRepository.GetListALL(x => x.F_DeptName == "销售").Result;
            int refunds = 0; decimal refundamounts =0;
            if (dept != null)
            {
                var userlist = _sys_useraccountRepository.GetListALL(x => x.F_DeptId == dept.FirstOrDefault().F_DeptId
                && x.F_DeleteFlag == 0).Result;
                List<AftersaleInput> aftersaleInputs = new List<AftersaleInput>();
                if (userlist!=null )
                {
                  for (int i=1;i<=days;i++)
                    {
                        foreach (var it in userlist)
                        {
                            AftersaleInput aftersaleInput = new AftersaleInput();
                            var aftertotal= after.Where
                                (x => x.F_CheckUserXS == it.F_UserId);
                            var aftersale = after.Where
                                (x => x.F_AddTime >= DateTime.Parse(time.ToString("yyyy-MM") + "-" + i)
                           && x.F_AddTime <= DateTime.Parse(time.ToString("yyyy-MM"  ) + "-"+ i +" 23:59:59"));

                            aftersaleInput.time = time.Month + "月" + i + "日";
                            aftersaleInput.name = it.F_UserName;
                            aftersaleInput.total = order.Where (x =>x .F_Belong == it.F_UserId&& x.F_AddTime >= DateTime.Parse(time.ToString("yyyy-MM") + "-" + i)
                           && x.F_AddTime <= DateTime.Parse(time.ToString("yyyy-MM" ) + "-"+i + " 23:59:59") && x.F_Type == "售后订单").Count ();
                            aftersaleInput.problem = aftersale.Where(x => x.F_ReturnType == "产品问题").Count();

                            aftersaleInput.warehousehair = aftersale.Where(x => x.F_ReturnType == "仓库错发" ||
                             x.F_ReturnType == "仓库漏发").Count();
                            aftersaleInput.Saleserror = aftersale.Where(x => x.F_ReturnType == "销售错发" ||
                            x.F_ReturnType == "销售漏发").Count();
                            aftersaleInput.refund = aftersale.Where(x => x.F_Money <0).Count();
                            aftersaleInput.refundamount =Math .Abs ( aftersale.Where(x => x.F_Money < 0).Select(x => x.F_Money).Sum());
                            refunds += aftersaleInput.refund;
                            refundamounts += aftersaleInput.refundamount;
                            aftersaleInput.Totalaftersales = aftersaleInput.total - aftersaleInput.problem
                              - aftersaleInput.warehousehair + aftersaleInput.refund;
                            aftersaleInput.delivergoods = order.Where(x => x.F_Belong == it.F_UserId).Count();
                            if (aftersaleInput.delivergoods > 0)
                            {
                                aftersaleInput.exchange = string.Format("{0:f2}%", aftersaleInput.Totalaftersales / aftersaleInput.delivergoods * 100);
                            }
                            else
                                aftersaleInput.exchange = "0%";

                            aftersaleInputs.Add(aftersaleInput);


                        }
                    }
                    string msg = time.Year +"年"+ time.Month  + "月份400销售中心共发货"+order .Count ()+"单, 退款共"+ refunds + "单，退款总金额为"+ refundamounts + "元。";
                    var obj = new
                    {
                        state = "success",
                        message = "成功",
                        aftersaleInputs,
                        msg
                    };
                   return  Content(obj.ToJson());

                }
                else
                    return Error("暂无销售人员");
            }
            else
                return Error("暂无销售部门");

        }
        /// <summary>
        /// 媒体进线量排名表
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        [HttpGet("mediainline")]
        public async Task<IActionResult> Mediainline(string  starttime, string endtime,int type=0)
        {
            DateTime begintime= DateTime.Now , closuretime = DateTime.Now;
            if (!string .IsNullOrEmpty (starttime) )
            {
                begintime =DateTime .Parse ( starttime);
            }
            if (!string.IsNullOrEmpty(endtime))
            {
                closuretime = DateTime.Parse(endtime);
            }
            List<Dictionaries> dictionaries = new List<Dictionaries>();
            var list = await _sys_mediaManagement_Repository.GetListALL (x=>x.F_IsDelete== (int)EnumUserCountState.Enabled);
            var calllist = await _busCallRecordsRepository .GetListALL(x => x.CallType  == 0&&
            x .BeginTime >= begintime&& x .EndTime <= closuretime&&x .CallState ==type );
            if (list!=null &&list.Count > 0)
            {
                foreach (var it in list)
                {
                    Dictionaries dictionarie = new Dictionaries();
                    dictionarie.key = it.F_Name;
                    dictionarie.value = calllist.Select(x => x.Callee == it.F_Telephone).Count();
                    dictionaries.Add(dictionarie);
                }
            }
            return Success("获取成功", dictionaries);

        }
        private class traffic
        {
            public int temporarystorage;//进线暂存量
            public int newIncomingline;//今日新客户进线量
            public int oldIncomingline;//今日老客户进线量
            public int Returnvisit;//今日回访量
            public int Incomingline;//本月进线量
            public int monthReturnvisit;//本月回访量
        }
        /// <summary>
        /// 话务指标
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        [HttpGet("trafficindex")]
        public async Task<IActionResult> Trafficindex(string   time)
        {
            DateTime day = DateTime.Now;
            DateTime mohth= new DateTime(day.Year, day.Month, 1);
            if (!string.IsNullOrEmpty(time))
            {
                day = DateTime.Parse(time);
                mohth = new DateTime(day.Year, day.Month, 1);
            }
            var calllist = await _busCallRecordsRepository.GetListALL(x =>
             x.BeginTime >= mohth && x.EndTime <= DateTime.Parse(day.ToString ("yyyy-MM-dd ")+"23:59:59"));
            var cuslist = await _cus_vip_infoRepository.GetListALL(x => x.F_CreateOn >= day && x.F_State == 1);
            int cusid = 0;
            if (cuslist != null&& cuslist.Count >0)
                cusid = cuslist.FirstOrDefault().F_ID;
           
           traffic traffics = new traffic();

            if (calllist!=null&&calllist.Count >0 )
            {
                traffics.temporarystorage = calllist.Select
                    (x => x.BeginTime >= day && x.EndTime <= DateTime.Parse(day.ToString("yyyy-MM-dd ") + "23:59:59")&&x.CallState ==0&&x.CallType ==0).Count();
               
                if (cusid > 0)
                {
                    traffics.newIncomingline = calllist.Select
                                       (x => x.BeginTime >= day && x.EndTime <= DateTime.Parse(day.ToString("yyyy-MM-dd ") + "23:59:59") && x.CallType == 0&&x .CusId >= cusid).Count();
                    traffics.oldIncomingline = calllist.Select
                                      (x => x.BeginTime >= day && x.EndTime <= DateTime.Parse(day.ToString("yyyy-MM-dd ") + "23:59:59") && x.CallType == 0 && x.CusId < cusid).Count();
                }
                else
                {
                    traffics.newIncomingline = 0;
                }
                traffics.Returnvisit = calllist.Select
                                    (x => x.BeginTime >= day && x.EndTime <= DateTime.Parse(day.ToString("yyyy-MM-dd ") + "23:59:59") && x.CallType == 1).Count();
                traffics.Incomingline = calllist.Select
                    (x => x.CallType == 0).Count();
                traffics.monthReturnvisit = calllist.Select
                  (x =>  x.CallType == 1).Count();
            }
            return Success("获取成功", traffics);

        }
    }
}