using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Edu.AOP;
using Edu.Cache.User;
using Edu.Cache.WeChat;
using Edu.Common.API;
using Edu.Common.Enum.Course;
using Edu.Common.Enum.User;
using Edu.Common.Plugin;
using Edu.Model.ViewModel.Course;
using Edu.Model.ViewModel.Customer;
using Edu.Model.ViewModel.Sell;
using Edu.Model.ViewModel.User;
using Edu.Module.Course;
using Edu.Module.User;
using Edu.Repository.Course;
using Edu.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace Edu.WebApi.Controllers.User
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class StudentStatController : BaseController
    {
        /// <summary>
        /// 学员统计
        /// </summary>
        private readonly StudentStatModule studentStatModule = new StudentStatModule();

        #region 学员跟进

        /// <summary>
        /// 获取学员跟进分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetStudentFollowUpPageList() 
        {
            var userInfo = base.UserInfo;
            ResultPageModel pmodel = JsonHelper.DeserializeObject<ResultPageModel>(base.RequestParm.Msg.ToString());
            RB_Student_ViewModel demodel = new RB_Student_ViewModel()
            {
                BelongType=base.ParmJObj.GetInt("BelongType"),
                ConsultantId=base.ParmJObj.GetInt("ConsultantId"),
                CourseId=base.ParmJObj.GetInt("CourseId"),
                CreateType=(StuCreateTypeEnum)base.ParmJObj.GetInt("CreateType"),
                EFTime=base.ParmJObj.GetStringValue("EFTime"),
                IsQueryMyStu=base.ParmJObj.GetInt("IsQueryMyStu"),
                QQ=base.ParmJObj.GetStringValue("QQ"),
                Q_FType=base.ParmJObj.GetInt("Q_FType"),
                SFTime=base.ParmJObj.GetStringValue("SFTime"),
                StuChannel=base.ParmJObj.GetInt("StuChannel"),
                StuGuestState=(GuestStateEnum)base.ParmJObj.GetInt("StuGuestState"),
                StuName=base.ParmJObj.GetStringValue("StuName"),
                StuRealMobile=base.ParmJObj.GetStringValue("StuRealMobile"),
                StuSourceId=base.ParmJObj.GetInt("StuSourceId"),
                StuStage=base.ParmJObj.GetInt("StuStage"),
                StuType=base.ParmJObj.GetInt("StuType"),
                WeChatNo=base.ParmJObj.GetStringValue("WeChatNo"),
                StuPurpose=base.ParmJObj.GetInt("StuPurpose"),
            };
            string schoolId = base.ParmJObj.GetStringValue("School_Id");
            if (schoolId != "-1")
            {
                demodel.School_Id= base.ParmJObj.GetInt("School_Id");
            }
            string CreateIds = base.ParmJObj.GetStringValue("CreateIds");
            if (!string.IsNullOrEmpty(CreateIds))
            {
                demodel.CreateIds = Common.Plugin.JsonHelper.DeserializeObject<List<int>>(CreateIds);
            }
            demodel.Group_Id = userInfo.Group_Id;
            if (demodel.IsQueryMyStu == 1)
            {
                demodel.CreateBy = userInfo.Id;
            }
            else
            {
                if (demodel.BelongType == 1)
                {
                    demodel.BelongType = 0;//暂先查全部
                }
                if (demodel.BelongType > 1)
                {
                    demodel.CreateBy = userInfo.Id;
                }
            }

            var list = studentStatModule.GetStudentFollowUpPageModule(pmodel.PageIndex, pmodel.PageSize, out long count, demodel);
            pmodel.Count = count;
            pmodel.PageData = list;
            return ApiResult.Success("", pmodel);
        }

        /// <summary>
        /// 下载学员跟进信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Obsolete]
        public FileContentResult DownLoadStudentFollowUp()
        {
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            RB_Student_ViewModel demodel = new RB_Student_ViewModel()
            {
                BelongType = base.ParmJObj.GetInt("BelongType"),
                ConsultantId = base.ParmJObj.GetInt("ConsultantId"),
                CourseId = base.ParmJObj.GetInt("CourseId"),
                CreateType = (StuCreateTypeEnum)base.ParmJObj.GetInt("CreateType"),
                EFTime = base.ParmJObj.GetStringValue("EFTime"),
                IsQueryMyStu = base.ParmJObj.GetInt("IsQueryMyStu"),
                QQ = base.ParmJObj.GetStringValue("QQ"),
                Q_FType = base.ParmJObj.GetInt("Q_FType"),
                SFTime = base.ParmJObj.GetStringValue("SFTime"),
                StuChannel = base.ParmJObj.GetInt("StuChannel"),
                StuGuestState = (GuestStateEnum)base.ParmJObj.GetInt("StuGuestState"),
                StuName = base.ParmJObj.GetStringValue("StuName"),
                StuRealMobile = base.ParmJObj.GetStringValue("StuRealMobile"),
                StuSourceId = base.ParmJObj.GetInt("StuSourceId"),
                StuStage = base.ParmJObj.GetInt("StuStage"),
                StuType = base.ParmJObj.GetInt("StuType"),
                WeChatNo = base.ParmJObj.GetStringValue("WeChatNo"),
                StuPurpose = base.ParmJObj.GetInt("StuPurpose"),
            };
            string schoolId = base.ParmJObj.GetStringValue("School_Id");
            if (schoolId != "-1")
            {
                demodel.School_Id = base.ParmJObj.GetInt("School_Id");
            }
            string CreateIds = base.ParmJObj.GetStringValue("CreateIds");
            if (!string.IsNullOrEmpty(CreateIds))
            {
                demodel.CreateIds = Common.Plugin.JsonHelper.DeserializeObject<List<int>>(CreateIds);
            }
            demodel.Group_Id = base.UserInfo.Group_Id;
            if (demodel.IsQueryMyStu == 1)
            {
                demodel.CreateBy = base.UserInfo.Id;
            }
            else
            {
                if (demodel.BelongType == 1)
                {
                    demodel.BelongType = 0;//暂先查全部
                }
                if (demodel.BelongType > 1)
                {
                    demodel.CreateBy = base.UserInfo.Id;
                }
            }
            var list = studentStatModule.GetStudentFollowUpPageModule(1, 1000000, out long count, demodel);
            string excelName = "学员跟踪.xls";
            try
            {
                ExcelDataSource header = new ExcelDataSource
                {
                    ExcelRows = new List<ExcelColumn>()
                    {
                        new ExcelColumn("学生"){ CellWidth=15,Rowspan=2},
                        new ExcelColumn("电话"){ CellWidth=15,Rowspan=2},
                        new ExcelColumn("课程顾问"){ CellWidth=15,Rowspan=2},
                        new ExcelColumn("协助老师"){ CellWidth=10,Rowspan=2},
                        new ExcelColumn("合同时间"){ CellWidth=15,Rowspan=2},
                        new ExcelColumn("所报课程"){ CellWidth=20,Rowspan=2},
                        new ExcelColumn("当前级别"){ CellWidth=15,Rowspan=2},
                        new ExcelColumn("生日"){ CellWidth=15,Rowspan=2},
                        new ExcelColumn("客户来源"){ CellWidth=15,Rowspan=2},
                        new ExcelColumn("学习目的"){ CellWidth=15,Rowspan=2},
                        new ExcelColumn("关联来源人"){ CellWidth=15,Rowspan=2},
                        new ExcelColumn("收客渠道"){ CellWidth=15,Rowspan=2},
                        new ExcelColumn("负责人"){ CellWidth=15,Rowspan=2},
                        new ExcelColumn("合同状态"){ CellWidth=15,Rowspan=2},
                    }
                };
                ExcelDataSource subHeader = new ExcelDataSource()
                {
                    ExcelRows = new List<ExcelColumn>()
                    {
                        new ExcelColumn(),
                        new ExcelColumn(),
                        new ExcelColumn(),
                        new ExcelColumn(),
                        new ExcelColumn(),
                        new ExcelColumn(),
                        new ExcelColumn(),
                        new ExcelColumn(),
                        new ExcelColumn(),
                        new ExcelColumn(),
                        new ExcelColumn(),
                        new ExcelColumn(),
                        new ExcelColumn(),
                        new ExcelColumn(),
                    }
                };

                var rootObj = JObject.Parse(JsonHelper.Serialize(list));
                int MaxMonth = rootObj.GetInt("MaxMonth");
                for (var i = 0; i < MaxMonth; i++)
                {
                    header.ExcelRows.Add(new ExcelColumn(value: "第" + (i + 1) + "个月") { Colspan = 3 });
                    subHeader.ExcelRows.Add(new ExcelColumn(value: "月份/续费/转介") { CellWidth=25});
                    subHeader.ExcelRows.Add(new ExcelColumn(value: "教师跟踪时间及情况说明") { CellWidth = 30 });
                    subHeader.ExcelRows.Add(new ExcelColumn(value: "顾问跟踪时间及情况说明") { CellWidth = 30 });
                }
                slist.Add(header);
                slist.Add(subHeader);

                JArray arrayList = JArray.Parse(rootObj.GetStringValue("RList"));
                if (arrayList != null && arrayList.Count > 0)
                {
                    foreach (var jItem in arrayList)
                    {
                        JObject dObj = JObject.Parse(JsonHelper.Serialize(jItem));
                        var columns = new List<ExcelColumn>
                        {
                            new ExcelColumn(dObj.GetStringValue("StuName")),
                            new ExcelColumn(dObj.GetStringValue("StuRealMobile")),
                        };
                        string courseManager = "";
                        string teacherNamager = "";
                        JArray assistList = JArray.Parse(dObj.GetStringValue("AssistList"));
                        if (assistList != null && assistList.Count > 0)
                        {
                            foreach (var sItem in assistList)
                            {
                                JObject sObk = JObject.Parse(JsonHelper.Serialize(sItem));
                                if (sObk.GetInt("AssistType") == 2)
                                {
                                    courseManager = sObk.GetStringValue("AssistName");
                                }
                                if (sObk.GetInt("AssistType") == 4)
                                {
                                    teacherNamager = sObk.GetStringValue("AssistName");
                                }
                            }
                        }
                        columns.Add(new ExcelColumn(courseManager));
                        columns.Add(new ExcelColumn(teacherNamager));
                        columns.Add(new ExcelColumn(dObj.GetStringValue("ContractSTime")));
                        columns.Add(new ExcelColumn(dObj.GetStringValue("CourseName")));
                        columns.Add(new ExcelColumn(dObj.GetStringValue("JapanBaseInfo")));
                        columns.Add(new ExcelColumn(dObj.GetStringValue("StuBirthStr")));
                        columns.Add(new ExcelColumn(dObj.GetStringValue("CreateTypeName")));
                        columns.Add(new ExcelColumn(dObj.GetStringValue("StuPurposeName")));
                        columns.Add(new ExcelColumn(dObj.GetStringValue("StuSourceIdName")));
                        columns.Add(new ExcelColumn(dObj.GetStringValue("StuChannelName")));
                        columns.Add(new ExcelColumn(dObj.GetStringValue("CreateByName")));
                        columns.Add(new ExcelColumn(dObj.GetStringValue("StuGuestStateName")));

                        JArray monthArray = JArray.Parse(dObj.GetStringValue("MonthList"));
                        if (monthArray != null && monthArray.Count > 0)
                        {
                            foreach (var mItem in monthArray)
                            {
                                JObject mObj = JObject.Parse(JsonHelper.Serialize(mItem));
                                int IsRenew = mObj.GetInt("IsRenew");
                                int IntroductionNum = mObj.GetInt("IntroductionNum");
                                string columns1 = mObj.GetStringValue("Month") + "/" + (IsRenew == 1 ? "是" : "否") + "/" + IntroductionNum;
                                columns.Add(new ExcelColumn(columns1));

                                string TeacherTime = mObj.GetStringValue("TeacherTime");
                                string Teacher = mObj.GetStringValue("Teacher");

                                string columns2 = TeacherTime + "-" + Teacher;
                                columns.Add(new ExcelColumn(columns2));

                                string ConsultantTime = mObj.GetStringValue("ConsultantTime");
                                string Consultant = mObj.GetStringValue("Consultant");
                                
                                string columns3 = ConsultantTime;
                                if (!string.IsNullOrEmpty(Consultant))
                                {
                                    columns3 += "\r\n" + Common.Plugin.StringHelper.AppHtmlFilterr(Consultant);
                                }
                                columns.Add(new ExcelColumn(columns3));
                            }
                        }
                        var dataRow = new ExcelDataSource()
                        {
                            ExcelRows = columns
                        };
                        slist.Add(dataRow);
                    }
                }
             
                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData, "application/octet-stream", excelName);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "OutToExcelOrderStudentClassHoursList");
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", excelName);
            }
        }

            #endregion

            #region 客人咨询

            /// <summary>
            /// 获取学员咨询分页列表
            /// </summary>
            /// <returns></returns>
            [HttpPost]
        public ApiResult GetStudentConsultPageList()
        {
            var userInfo = base.UserInfo;
            ResultPageModel pmodel = JsonHelper.DeserializeObject<ResultPageModel>(base.RequestParm.Msg.ToString());
            RB_Student_ViewModel demodel = new RB_Student_ViewModel()
            {
                BelongType=base.ParmJObj.GetInt("BelongType"),
                ConsultantId=base.ParmJObj.GetInt("ConsultantId"),
                EFTime=base.ParmJObj.GetStringValue("EFTime"),
                IsQueryMyStu=base.ParmJObj.GetInt("IsQueryMyStu"),
                QQ=base.ParmJObj.GetStringValue("QQ"),
                Q_EnrollState=base.ParmJObj.GetInt("Q_EnrollState"),
                Q_FType=base.ParmJObj.GetInt("Q_FType"),
                SFTime=base.ParmJObj.GetStringValue("SFTime"),
                StuChannel=base.ParmJObj.GetInt("StuChannel"),
                StuGuestState=(GuestStateEnum)base.ParmJObj.GetInt("StuGuestState"),
                StuName = base.ParmJObj.GetStringValue("StuName"),
                StuRealMobile=base.ParmJObj.GetStringValue("StuRealMobile"),
                StuStage=base.ParmJObj.GetInt("StuStage"),
                StuType=base.ParmJObj.GetInt("StuType"),
                WeChatNo=base.ParmJObj.GetStringValue("WeChatNo"),
            };
            List<int> empIds = new List<int>();
            string createIds = base.ParmJObj.GetStringValue("CreateIds");
            if (!string.IsNullOrEmpty(createIds))
            {
                empIds = JsonHelper.DeserializeObject<List<int>>(createIds);
            }
            demodel.CreateIds = empIds;

            demodel.Group_Id = userInfo.Group_Id;
            if (demodel.IsQueryMyStu == 1)
            {
                demodel.CreateBy = userInfo.Id;
            }
            else
            {
                if (demodel.BelongType == 1)
                {
                    demodel.BelongType = 0;//暂先查全部
                }
                if (demodel.BelongType > 1)
                {
                    demodel.CreateBy = userInfo.Id;
                }
            }

            var list = studentStatModule.GetStudentConsultPageList(pmodel.PageIndex, pmodel.PageSize, out long count, demodel);
            pmodel.Count = count;
            pmodel.PageData = list;
            return ApiResult.Success("", pmodel);
        }

        /// <summary>
        /// 下载客人咨询信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Obsolete]
        public FileContentResult DownLoadStudentConsult()
        {
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            RB_Student_ViewModel demodel = new RB_Student_ViewModel()
            {
                BelongType = base.ParmJObj.GetInt("BelongType"),
                ConsultantId = base.ParmJObj.GetInt("ConsultantId"),
                EFTime = base.ParmJObj.GetStringValue("EFTime"),
                IsQueryMyStu = base.ParmJObj.GetInt("IsQueryMyStu"),
                QQ = base.ParmJObj.GetStringValue("QQ"),
                Q_EnrollState = base.ParmJObj.GetInt("Q_EnrollState"),
                Q_FType = base.ParmJObj.GetInt("Q_FType"),
                SFTime = base.ParmJObj.GetStringValue("SFTime"),
                StuChannel = base.ParmJObj.GetInt("StuChannel"),
                StuGuestState = (GuestStateEnum)base.ParmJObj.GetInt("StuGuestState"),
                StuName = base.ParmJObj.GetStringValue("StuName"),
                StuRealMobile = base.ParmJObj.GetStringValue("StuRealMobile"),
                StuStage = base.ParmJObj.GetInt("StuStage"),
                StuType = base.ParmJObj.GetInt("StuType"),
                WeChatNo = base.ParmJObj.GetStringValue("WeChatNo"),
            };
            List<int> empIds = new List<int>();
            string createIds = base.ParmJObj.GetStringValue("CreateIds");
            if (!string.IsNullOrEmpty(createIds))
            {
                empIds = JsonHelper.DeserializeObject<List<int>>(createIds);
            }
            demodel.CreateIds = empIds;

            demodel.Group_Id = base.UserInfo.Group_Id;
            if (demodel.IsQueryMyStu == 1)
            {
                demodel.CreateBy = base.UserInfo.Id;
            }
            else
            {
                if (demodel.BelongType == 1)
                {
                    demodel.BelongType = 0;//暂先查全部
                }
                if (demodel.BelongType > 1)
                {
                    demodel.CreateBy = base.UserInfo.Id;
                }
            }
            var list = studentStatModule.GetStudentConsultPageList(1, 1000000, out long count, demodel);
            string excelName = "客人咨询.xls";
            try
            {
                ExcelDataSource header = new ExcelDataSource
                {
                    ExcelRows = new List<ExcelColumn>()
                    {
                        new ExcelColumn("学生"){ CellWidth=15},
                        new ExcelColumn("状态"){ CellWidth=15},
                        new ExcelColumn("课程顾问"){ CellWidth=15},
                        new ExcelColumn("生日"){ CellWidth=10},
                        new ExcelColumn("电话"){ CellWidth=15},
                        new ExcelColumn("地址"){ CellWidth=15},
                        new ExcelColumn("渠道来源"){ CellWidth=20},
                        new ExcelColumn("日语基础"){ CellWidth=20},
                        new ExcelColumn("规划课程及报价"){ CellWidth=20},
                        new ExcelColumn("客户情况分析"){ CellWidth=50},
                        new ExcelColumn("顾问跟进备注"){ CellWidth=50},
                         
                    }
                };
                slist.Add(header);
                foreach (var item in list)
                {
                    JObject dObj = JObject.Parse(JsonHelper.Serialize(item));
                    var columns = new List<ExcelColumn>
                    {
                        new ExcelColumn(dObj.GetStringValue("StuName"))
                    };
                    string EnrollState = dObj.GetInt("EnrollState") == 1 ? "已报名" : "未成交";
                    columns.Add(new ExcelColumn(EnrollState));
                    columns.Add(new ExcelColumn(dObj.GetStringValue("AssistName")));
                    columns.Add(new ExcelColumn(dObj.GetStringValue("StuBirthStr")));
                    columns.Add(new ExcelColumn(dObj.GetStringValue("StuRealMobile")));
                    columns.Add(new ExcelColumn(dObj.GetStringValue("StuAddress")));
                    columns.Add(new ExcelColumn(dObj.GetStringValue("StuChannelName")));
                    columns.Add(new ExcelColumn(dObj.GetStringValue("JapanBaseInfo")));
                    columns.Add(new ExcelColumn(dObj.GetStringValue("PlanPrice")));
                    string baseCondition = dObj.GetStringValue("BaseCondition");
                    string demandPoint = dObj.GetStringValue("DemandPoint");
                    string resistPoint = dObj.GetStringValue("ResistPoint");
                    string consultingResults = dObj.GetStringValue("ConsultingResults");

                    baseCondition = !string.IsNullOrEmpty(baseCondition) ? baseCondition : "暂无";
                    demandPoint = !string.IsNullOrEmpty(demandPoint) ? demandPoint : "暂无";
                    resistPoint = !string.IsNullOrEmpty(resistPoint) ? resistPoint : "暂无";
                    consultingResults = !string.IsNullOrEmpty(consultingResults) ? consultingResults : "暂无";
                    string baseInfo = "基本情况：" + baseCondition + "\r\n" + "需求点：" + consultingResults + "\r\n" + "抗拒点：" + resistPoint + "\r\n" + "咨询结果：" + consultingResults;
                    columns.Add(new ExcelColumn(baseInfo));

                    string remark = "";
                    string FUTime = dObj.GetStringValue("FUTime");
                    if (!string.IsNullOrEmpty(FUTime))
                    {
                        remark += FUTime;
                    }
                    string FURemark = dObj.GetStringValue("FURemark");
                    if (!string.IsNullOrEmpty(FURemark))
                    {
                        remark += "\r\n" +StringHelper.FilterHtml(FURemark);
                    }
                    columns.Add(new ExcelColumn()
                    {
                        Value = remark
                    });

                    var dataRow = new ExcelDataSource()
                    {
                        ExcelRows = columns
                    };
                    slist.Add(dataRow);
                }
                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData, "application/octet-stream", excelName);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "OutToExcelOrderStudentClassHoursList");
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", excelName);
            }
        }
        #endregion
    }
}
