using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Edu.Cache.User;
using Edu.Common;
using Edu.Common.API;
using Edu.Common.Enum.Course;
using Edu.Common.Plugin;
using Edu.Model.ViewModel.Contract;
using Edu.Model.ViewModel.Course;
using Edu.Module.Course;
using Edu.WebApi.Filter;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace Edu.WebApi.Controllers.Course
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class EducationContractController : BaseController
    {
        /// <summary>
        /// 教育合同处理类对象
        /// </summary>
        private readonly EducationContractModule educationContractModule = AOP.AOPHelper.CreateAOPObject<EducationContractModule>();

        #region 合同列表

        /// <summary>
        /// 获取学员信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetStudentInfo()
        {
            int OrderId = base.ParmJObj.GetInt("OrderId", 0);//订单编号
            int GuestId = base.ParmJObj.GetInt("GuestId", 0);//学员编号
            var model = educationContractModule.GetStudentInfoModule(OrderId, GuestId);
            return ApiResult.Success("", model);
        }

        /// <summary>
        /// 获取合同分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetEducationContractPageList()
        {
            var userInfo = base.UserInfo;
            var pageModel = JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var dmodel = new RB_Education_Contract_ViewModel()
            {
                OrderId = base.ParmJObj.GetInt("OrderId"),
                ContractNo = base.ParmJObj.GetStringValue("ContractNo"),
                CType = (ContractTypeEnum)base.ParmJObj.GetInt("CType"),
                Status = base.ParmJObj.GetInt("Status"),
                StudentName = base.ParmJObj.GetStringValue("StudentName"),
                IsAduit = base.ParmJObj.GetInt("IsAduit")
            };
            dmodel.Group_Id = userInfo.Group_Id;
            dmodel.CreateBy = userInfo.Id;
            var list = educationContractModule.GetEducationContractPageListModule(pageModel.PageIndex, pageModel.PageSize, out long count, dmodel);
            pageModel.Count = Convert.ToInt32(count);
            pageModel.PageData = list.Select(x => new
            {
                x.Id,
                x.CType,
                CTypeName = x.CType.ToName(),
                IsStuSign = !string.IsNullOrEmpty(x.Sign) ? 1 : 0,
                x.OrderId,
                x.GuestId,
                x.ContractNo,
                x.StudentName,
                x.SchoolName,
                x.CourseName,
                x.CNYCaps,
                x.Money,
                x.Exam,
                x.Sign,
                x.Status,
                x.StatusStr,
                x.IsCompanySeal,
                x.CreateBy,
                x.CreateByName,
                x.CreateByPhoto,
                CreateTime = x.CreateTime.ToString("yyyy-MM-dd HH:mm")
            });
            return ApiResult.Success("", pageModel);
        }

        /// <summary>
        /// 获取合同分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMyEducationContractPageList()
        {
            var userInfo = base.UserInfo;
            var pageModel = JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var dmodel = new RB_Education_Contract_ViewModel()
            {
                OrderId = base.ParmJObj.GetInt("OrderId"),
                ContractNo = base.ParmJObj.GetStringValue("ContractNo"),
                CType = (ContractTypeEnum)base.ParmJObj.GetInt("CType"),
                Status = base.ParmJObj.GetInt("Status"),
                StudentName = base.ParmJObj.GetStringValue("StudentName"),
                IsAduit = base.ParmJObj.GetInt("IsAduit"),
                IsQueryAll=base.ParmJObj.GetInt("IsQueryAll"),
                QCreateBy=base.ParmJObj.GetInt("QCreateBy"),
            };
            dmodel.Group_Id = userInfo.Group_Id;
            if (dmodel.IsQueryAll == 0)
            {
                dmodel.CreateBy = userInfo.Id;
            }
            var list = educationContractModule.GetEducationContractPageListModule_V3(pageModel.PageIndex, pageModel.PageSize, out long count, dmodel);
            pageModel.Count = Convert.ToInt32(count);
            pageModel.PageData = list.Select(x => new
            {
                x.Id,
                x.CType,
                CTypeName = x.CType.ToName(),
                IsStuSign = !string.IsNullOrEmpty(x.Sign) ? 1 : 0,
                x.OrderId,
                x.GuestId,
                x.ContractNo,
                x.StudentName,
                x.SchoolName,
                x.CourseName,
                x.CNYCaps,
                x.Money,
                x.Exam,
                x.Sign,
                x.Status,
                x.StatusStr,
                x.IsCompanySeal,
                x.CreateBy,
                x.CreateByName,
                x.CreateByPhoto,
                CreateTime = x.CreateTime.ToString("yyyy-MM-dd HH:mm"),
                x.SchoolStatusStr,
                x.AdminStatusStr
            });
            return ApiResult.Success("", pageModel);
        }



        /// <summary>
        /// 获取合同分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetEducationContractPageCodeList()
        {
            var userInfo = base.UserInfo;
            var pageModel = JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var dmodel = new RB_Education_Contract_ViewModel()
            {
                OrderId = base.ParmJObj.GetInt("OrderId"),
                ContractNo = base.ParmJObj.GetStringValue("ContractNo"),
                CType = (ContractTypeEnum)base.ParmJObj.GetInt("CType"),
                StudentName = base.ParmJObj.GetStringValue("StudentName"),
                IsAduit = base.ParmJObj.GetInt("IsAduit")
            };

            List<RB_Education_Contract_ViewModel> list = new List<RB_Education_Contract_ViewModel>();
            dmodel.Group_Id = userInfo.Group_Id;
            dmodel.CreateBy = userInfo.Id;
            int Type = 0;
            if (CheckUserActionAuth(Config.EducationContractSchool))
            {
                dmodel.SelectEexamineStatus = "1";
                Type = 1;
            }
            else if (CheckUserActionAuth(Config.EducationContractAdmin))
            {
                dmodel.SelectEexamineStatus = "5,2";
                Type = 2;
            }
            else
            {
                pageModel.Count = 0;

                pageModel.PageData = new { Type, Result = new List<object>() };
                return ApiResult.Success("您暂无审核权限", pageModel);
            }
            list = educationContractModule.GetEducationContractPageList_V2(pageModel.PageIndex, pageModel.PageSize, out long count, dmodel);
            pageModel.Count = Convert.ToInt32(count);
            var Result = list.Select(x => new
            {
                x.Id,
                x.CType,
                CTypeName = x.CType.ToName(),
                IsStuSign = !string.IsNullOrEmpty(x.Sign) ? 1 : 0,
                x.OrderId,
                x.GuestId,
                x.ContractNo,
                x.StudentName,
                x.SchoolName,
                x.CourseName,
                x.CNYCaps,
                x.Money,
                x.Exam,
                x.Sign,
                x.Status,
                x.StatusStr,
                x.IsCompanySeal,
                x.CreateBy,
                x.CreateByName,
                x.CreateByPhoto,
                CreateTime = x.CreateTime.ToString("yyyy-MM-dd HH:mm"),
                x.SchoolStatusStr,
                x.AdminStatusStr
            });
            pageModel.PageData = new { Type, Result };
            return ApiResult.Success("", pageModel);
        }


        /// <summary>
        /// 获取合同详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetEducationContractInfo()
        {
            int ContractId = base.ParmJObj.GetInt("ContractId", 0);//合同id
            var model = educationContractModule.GetEducationContractModule(ContractId);
            if (model == null)
            {
                return ApiResult.Failed("合同不存在");
            }
            return ApiResult.Success(data: model);
        }

        /// <summary>
        /// 单独新增合同
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetEducationContractInfo()
        {
            var userInfo = base.UserInfo;
            var dmodel = new RB_Education_Contract_ViewModel()
            {
                Id = base.ParmJObj.GetInt("Id"),
                CType = (ContractTypeEnum)base.ParmJObj.GetInt("CType"),
                OrderId = base.ParmJObj.GetInt("OrderId"),
                GuestId = base.ParmJObj.GetInt("GuestId"),
                ContractNo = base.ParmJObj.GetStringValue("ContractNo"),
                StudentName = base.ParmJObj.GetStringValue("StudentName"),
                StuBirth = base.ParmJObj.GetDateTime("StuBirth"),
                StuSex = base.ParmJObj.GetInt("StuSex"),
                StuAddress = base.ParmJObj.GetStringValue("StuAddress"),
                StuTel = base.ParmJObj.GetStringValue("StuTel"),
                StuEmail = base.ParmJObj.GetStringValue("StuEmail"),
                ParentName = base.ParmJObj.GetStringValue("ParentName"),
                ParentRelation = base.ParmJObj.GetStringValue("ParentRelation"),
                ParentTel = base.ParmJObj.GetStringValue("ParentTel"),
                ParentEmail = base.ParmJObj.GetStringValue("ParentEmail"),
                UrgentName = base.ParmJObj.GetStringValue("UrgentName"),
                UrgentRelation = base.ParmJObj.GetStringValue("UrgentRelation"),
                UrgentTel = base.ParmJObj.GetStringValue("UrgentTel"),
                UrgentEmail = base.ParmJObj.GetStringValue("UrgentEmail"),
                GuardianIDCard = base.ParmJObj.GetStringValue("GuardianIDCard"),
                CourseName = base.ParmJObj.GetStringValue("CourseName"),
                SchoolName = base.ParmJObj.GetStringValue("SchoolName"),
                SchoolPrincipal = base.ParmJObj.GetStringValue("SchoolPrincipal"),
                StartLevel = base.ParmJObj.GetStringValue("StartLevel"),
                CourseConsultant = base.ParmJObj.GetStringValue("CourseConsultant"),
                Payee = base.ParmJObj.GetStringValue("Payee"),
                FirstClassHours = base.ParmJObj.GetDecimal("FirstClassHours"),
                FirstCourseFee = base.ParmJObj.GetDecimal("FirstCourseFee"),
                FirstBookFee = base.ParmJObj.GetDecimal("FirstBookFee"),
                FirstClassFee = base.ParmJObj.GetDecimal("FirstClassFee"),
                FirstDiscountMoney = base.ParmJObj.GetDecimal("FirstDiscountMoney"),
                FirstMoney = base.ParmJObj.GetDecimal("FirstMoney"),
                FirstPayDate = base.ParmJObj.GetDateTime("FirstPayDate"),
                SecondClassHours = base.ParmJObj.GetDecimal("SecondClassHours"),
                SecondCourseFee = base.ParmJObj.GetDecimal("SecondCourseFee"),
                SecondBookFee = base.ParmJObj.GetDecimal("SecondBookFee"),
                SecondClassFee = base.ParmJObj.GetDecimal("SecondClassFee"),
                SecondDiscountMoney = base.ParmJObj.GetDecimal("SecondDiscountMoney"),
                SecondMoney = base.ParmJObj.GetDecimal("SecondMoney"),
                SecondPayDate = base.ParmJObj.GetDateTime("SecondPayDate"),
                ThirdClassHours = base.ParmJObj.GetDecimal("ThirdClassHours"),
                ThirdCourseFee = base.ParmJObj.GetDecimal("ThirdCourseFee"),
                ThirdBookFee = base.ParmJObj.GetDecimal("ThirdBookFee"),
                ThirdClassFee = base.ParmJObj.GetDecimal("ThirdClassFee"),
                ThirdDiscountMoney = base.ParmJObj.GetDecimal("ThirdDiscountMoney"),
                ThirdMoney = base.ParmJObj.GetDecimal("ThirdMoney"),
                ThirdPayDate = base.ParmJObj.GetDateTime("ThirdPayDate"),
                CNYCaps = base.ParmJObj.GetStringValue("CNYCaps"),
                Money = base.ParmJObj.GetDecimal("Money"),
                Exam = base.ParmJObj.GetStringValue("Exam"),
                IsSupplement = base.ParmJObj.GetInt("IsSupplement"),
                StuIDCard=base.ParmJObj.GetStringValue("StuIDCard"),
            };
            dmodel.Group_Id = userInfo.Group_Id;
            dmodel.CreateBy = userInfo.Id;
            dmodel.CreateTime = DateTime.Now;
            dmodel.UpdateBy = userInfo.Id;
            dmodel.UpdateTime = DateTime.Now;
            dmodel.Status = 0;
            bool flag = educationContractModule.SetEducationContractModule(dmodel);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 设置合同审核
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetEducationContractAudit()
        {
            var userInfo = base.UserInfo;
            int ContractId = base.ParmJObj.GetInt("ContractId", 0);//合同id
            int State = base.ParmJObj.GetInt("State", 1);// 状态 1提交审核  2通过  3驳回  4取消  5盖章
            if (ContractId <= 0)
            {
                return ApiResult.ParamIsNull("请传递合同id");
            }
            //直接审批通过 (HK2021-12-21修改)
            State = 2;
            bool flag = educationContractModule.SetEducationContractAuditModule(ContractId, State, userInfo);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }



        /// <summary>
        /// 设置合同审核
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetEducationContractAuditCode()
        {
            var userInfo = base.UserInfo;
            int ContractId = base.ParmJObj.GetInt("ContractId", 0);//合同id

            int oldType = 0;

            if (CheckUserActionAuth(Config.EducationContractSchool))
            {
                oldType = 1;
            }
            else if (CheckUserActionAuth(Config.EducationContractAdmin))
            {
                oldType = 2;
            }
            if (oldType == 0)//没有审核权限的
            {
                return ApiResult.ParamIsNull("您暂无审核权限");
            }
            int State = base.ParmJObj.GetInt("State", 1);// 状态 1提交审核  2通过  3驳回  4取消  5盖章,6-学管审核通过
            if (oldType == 1)//学管审核
            {
                if (State == 2 || State == 5)
                {
                    return ApiResult.ParamIsNull("您暂无审核权限");
                }
            }
            else if (oldType == 2)
            {
                if (State == 6)
                {
                    return ApiResult.ParamIsNull("您暂无审核权限");
                }
            }

            if (ContractId <= 0)
            {
                return ApiResult.ParamIsNull("请传递合同id");
            }
            bool flag = educationContractModule.SetEducationContractAuditModule_V2(ContractId, State, oldType, userInfo);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 复制合同
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetEducationContractCopy()
        {
            var userInfo = base.UserInfo;
            int ContractId = base.ParmJObj.GetInt("ContractId", 0);//合同id
            if (ContractId <= 0)
            {
                return ApiResult.ParamIsNull("请传递合同id");
            }
            var model = educationContractModule.GetEducationContractModule(ContractId);
            model.Id = 0;
            model.Group_Id = userInfo.Group_Id;
            model.CreateBy = userInfo.Id;
            model.CreateTime = DateTime.Now;
            model.UpdateBy = userInfo.Id;
            model.UpdateTime = DateTime.Now;
            model.Status = 0;
            bool flag = educationContractModule.SetEducationContractModule(model);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 合同签字
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult SetEducationContractSign()
        {
            int ContractId = base.ParmJObj.GetInt("ContractId", 0);//合同id
            string Sign = base.ParmJObj.GetStringValue("Sign");//签名
            string StuIDCard = base.ParmJObj.GetStringValue("StuIDCard");
            if (ContractId <= 0)
            {
                return ApiResult.ParamIsNull("请传递合同id");
            }
            bool flag = educationContractModule.SetEducationContractSignModule(ContractId, Sign, StuIDCard);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 修改学员合同身份证号码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult SetEducationContractIDCard()
        {
            int ContractId = base.ParmJObj.GetInt("ContractId", 0);//合同id
            string StuIDCard = base.ParmJObj.GetStringValue("StuIDCard");//签名
            if (ContractId <= 0)
            {
                return ApiResult.ParamIsNull("请传递合同id");
            }
            bool flag = educationContractModule.SetEducationContractIDCardModule(ContractId, StuIDCard);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 下载pdf
        /// </summary>
        /// <returns></returns>
        public ApiResult GetDownLoadEducationContract()
        {
            string time = DateTime.Now.Ticks.ToString();
            string path = "/upfile/Temporary/" + time + ".pdf";
            string basepath = AppContext.BaseDirectory;
            string tempPath = basepath + "\\upfile\\Temporary\\" + time + ".pdf";
            var ID = base.ParmJObj.GetInt("ContractId");
            var CType = base.ParmJObj.GetInt("CType");
            string curl = Common.Config.UploadSiteUrl + string.Format(@"/Home/EducationContractInfo?ID={0}&CType={1}", ID, CType);
            var flag = new ToPdfHelper().HtmlWJtoPdf(tempPath, curl);
            return ApiResult.Success("", path);
        }
        #endregion

        /// <summary>
        /// 获取退课分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetBackClassProtocolPage()
        {
            var userInfo = base.UserInfo;
            var pageModel = JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_BackClass_Protocol_ViewModel()
            {
                PartyAName = base.ParmJObj.GetStringValue("PartyAName"),
                AuditStatus = base.ParmJObj.GetInt("AuditStatus"),
                QOrderId = base.ParmJObj.GetInt("QOrderId"),
                ProtocolNum = base.ParmJObj.GetStringValue("ProtocolNum"),
                IsQueryAll=base.ParmJObj.GetInt("IsQueryAll"),
                QCreateBy=base.ParmJObj.GetInt("QCreateBy"),
                Id=base.ParmJObj.GetInt("Id"),
            };
            query.Group_Id = userInfo.Group_Id;
            if (query.IsQueryAll == 0)
            {
                query.CreateBy = userInfo.Id;
            }
            var list = educationContractModule.GetBackClassProtocolPageModule(pageModel.PageIndex, pageModel.PageSize, query, out long count);
            pageModel.Count = Convert.ToInt32(count);
            pageModel.PageData = list.Select(x => new
            {
                x.Id,
                x.ReceiptId,
                x.ProtocolNum,
                x.PartyAName,
                x.OldCourseName,
                CreateByName= UserReidsCache.GetUserLoginInfo((x?.CreateBy??0))?.AccountName??"",
                x.CreateTimeStr,
                x.AuditStatusStr,
                x.AuditStatus,
                IsStuSign = !string.IsNullOrEmpty(x.PartyASign) ? 1 : 0,
                x.IsCompanySeal,
                x.IsSure,
                x.PartyASign,
                x.BackAccount,
                x.BackAccountName,
                x.GuestId,
            });
            return ApiResult.Success("", pageModel);
        }

        /// <summary>
        /// 获取退课协议详情
        /// </summary>
        /// <returns></returns>
       [AllowAnonymous]
       [HttpPost]
        public ApiResult GetBackClassProtocol()
        {
            int Id = base.ParmJObj.GetInt("Id");
            var model = educationContractModule.GetBackClassProtocolModule(Id);
            return ApiResult.Success(data: model);
        }

        /// <summary>
        /// 退课协议学员签字
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ApiResult SetBackClassProtocolSign()
        {
            int Id = base.ParmJObj.GetInt("Id");
            string sign = base.ParmJObj.GetStringValue("sign");
            var flag = educationContractModule.SetBackClassProtocolSignModule(Id, sign);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 退课协议销售确认
        /// </summary>
        /// <returns></returns>
        public ApiResult SetBackClassProtocolSure()
        {
            int Id = base.ParmJObj.GetInt("Id");
            int IsSure = base.ParmJObj.GetInt("IsSure");
            int ClientId = base.ParmJObj.GetInt("ClientId", 0);
            var flag = educationContractModule.SetBackClassProtocolSureModule(Id, IsSure, ClientId,base.UserInfo,out string message);
            return flag ? ApiResult.Success() : ApiResult.Failed(message: message);
        }

        /// <summary>
        /// 生成小程序二维码
        /// </summary>
        /// <returns></returns>
        public ApiResult CreateWeChatCode()
        {
            string url = base.ParmJObj.GetStringValue("url");
            var newUrl = "/pages/webbox/webbox?u="+ HttpUtility.UrlEncode(url);
            int width = base.ParmJObj.GetInt("width");
            if (width <= 0)
            {
                width = 430;
            }
            string tokenKey = "DATA_WeiXinToken_" + Common.Config.AppID;
            string token = Cache.WeChat.WeChatReidsCache2.GetToken(tokenKey);
            if (Config.IsLocal == 1)
            {
                token = Common.Config.TempToken;
            }
            if (string.IsNullOrEmpty(token))
            {
                token = Common.Plugin.WeChatHelper.GetAccessToken(Common.Config.AppID, Common.Config.AppSecret);
                Cache.WeChat.WeChatReidsCache2.Set(tokenKey, token);
            }
            string filePath = Common.Plugin.WeChatHelper.GetWeChatQRCode(token, newUrl, width);
            return ApiResult.Success(data: filePath);
        }

        /// <summary>
        /// 生成小程序二维码（财务收据）
        /// </summary>
        /// <returns></returns>
        public ApiResult CreateWeChatCodeForReceipt()
        {
            string url = base.ParmJObj.GetStringValue("url");
            var newUrl = "/pages/index/index?id=" + HttpUtility.UrlEncode(url) + "&JumpType=20";
            int width = base.ParmJObj.GetInt("width");
            if (width <= 0)
            {
                width = 430;
            }
            string tokenKey = "DATA_WeiXinToken_" + Common.Config.AppID;
            string token = Cache.WeChat.WeChatReidsCache2.GetToken(tokenKey);
            if (Config.IsLocal == 1)
            {
                token = Common.Config.TempToken;
            }
            if (string.IsNullOrEmpty(token))
            {
                token = Common.Plugin.WeChatHelper.GetAccessToken(Common.Config.AppID, Common.Config.AppSecret);
                Cache.WeChat.WeChatReidsCache2.Set(tokenKey, token);
            }
            string filePath = Common.Plugin.WeChatHelper.GetWeChatQRCode(token, newUrl, width);
            return ApiResult.Success(data: filePath);
        }
    }
}
