using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EMIS.ViewModel;
using EMIS.Web.Controls;
using Bowin.Web.Controls.Mvc;
using EMIS.CommonLogic.TeachingMaterial;
using Bowin.Common.Utility;
using Bowin.Common.Data;
using EMIS.ViewModel.TeachingMaterial;
using EMIS.ViewModel.Students;
using EMIS.CommonLogic.Students;
using EMIS.CommonLogic.CalendarManage;
using EMIS.Utility;
using EMIS.CommonLogic.SystemServices;

namespace EMIS.Web.Controllers.TeachingMaterial
{
    [Authorization]
    public class StudentDistributeController : Controller
    {
        public IStudentDistributeServices StudentDistributeServices { get; set; }
        public IStudentsServices StudentfileServices { get; set; }
        public ISchoolYearServices SchoolYearServices { get; set; }
        public IStockOutServices StockOutServices { get; set; }

        /// <summary>
        /// 学生发放页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult List()
        {
            //默认当前学年
            var schoolYear = SchoolYearServices.GetSchoolYearIsCurrent(true);
            ViewBag.SchoolYearID = schoolYear == null ? "-1" : schoolYear.SchoolyearID.ToString();
            return View();
        }

        /// <summary>
        /// 列表查询
        /// </summary>
        /// <param name="pararms"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult List(QueryParamsModel pararms)
        {
            ConfiguretView configuretView = ConfiguretExtensions.GetConfiguretermsView(pararms);
            var grademajorID = pararms.getExtraGuid("ComboGridGrademajor");
            Guid? campusID = pararms.getExtraGuid("CampusDropdown");
            Guid? collegeID = pararms.getExtraGuid("CollegeDropdown");
            int? years = pararms.getExtraInt("DictionarySchoolyear") == DropdownList.SELECT_ALL ? null : pararms.getExtraInt("DictionarySchoolyear");
            int? standardID = pararms.getExtraInt("ddlStandard") == DropdownList.SELECT_ALL ? null : pararms.getExtraInt("ddlStandard");
            Guid? coursematerialID = pararms.getExtraGuid("CourseDropdown");
            int? courseCategoryID = pararms.getExtraInt("CourseTypeDropdown") == DropdownList.SELECT_ALL ? null : pararms.getExtraInt("CourseTypeDropdown");
            Guid? teachingMaterialPoolID = pararms.getExtraGuid("TeachingMaterialDropdown");
            Guid? schoolyearID = pararms.getExtraGuid("SchoolyearDropdown");//学年学期
            int? isOrdered = pararms.getExtraInt("OrderedDropdown");
            return base.Json(StudentDistributeServices.GetStudentDistributeViewGrid(configuretView, campusID, collegeID, years, grademajorID,
                 coursematerialID, courseCategoryID, teachingMaterialPoolID, isOrdered, schoolyearID, standardID, (int)pararms.page, (int)pararms.rows));
        }

        /// <summary>
        /// 发放计划生成
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult CreatePlan()
        {
            var schoolYear = SchoolYearServices.GetSchoolYearIsCurrent(true).SchoolyearID;
            ViewData["schoolYear"] = schoolYear;
            return View();
        }

        /// <summary>
        /// 发放计划生成
        /// </summary>
        /// <param name="schoolyearID"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CreatePlan(Guid schoolyearID)
        {
            try
            {
                schoolyearID = new Guid(Request.Form["SchoolyearDropdown"]);
                var user = HttpContext.User as EMIS.Utility.FormValidate.CustomPrincipal;
                StudentDistributeServices.CreateStudentDistribute(schoolyearID, user.UserID);
                return Json(new ReturnMessage()
                {
                    IsSuccess = true,
                    Message = "生成成功。"
                });
            }
            catch (Exception ex)
            {
                return Json(new ReturnMessage()
                {
                    IsSuccess = false,
                    Message = "生成失败,原因:" + ex.Message
                });
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="roleID"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Delete(string studentDistributeIDs)
        {
            try
            {
                var studentDistributeIDList = studentDistributeIDs.Split(',').Select(x => Guid.Parse(x)).ToList();

                StudentDistributeServices.DeleteStudentDistribute(studentDistributeIDList);
                return base.Json("删除成功。");
            }
            catch (Exception ex)
            {
                return base.Json("删除失败,原因:" + ex.Message);
            }
        }

        /// <summary>
        /// Excel
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Excel()
        {
            ConfiguretView configuretView = ConfiguretExtensions.GetConfiguretermsView(null);
            //避开全选值
            int? isOrdered = null;
            var grademajorID = Request.Form["ComboGridGrademajor"].ParseStrTo<Guid>();
            Guid? campusID = Request.Form["CampusDropdown"].ParseStrTo<Guid>();
            Guid? collegeID = Request.Form["CollegeDropdown"].ParseStrTo<Guid>();
            int? years = Request.Form["DictionarySchoolyear"].ParseStrTo<int>() == DropdownList.SELECT_ALL ? null : Request.Form["DictionarySchoolyear"].ParseStrTo<int>();
            int? standardID = Request.Form["StandardDropdown"].ParseStrTo<int>() == DropdownList.SELECT_ALL ? null : Request.Form["StandardDropdown"].ParseStrTo<int>();
            Guid? coursematerialID = Request.Form["CourseDropdown"].ParseStrTo<Guid>();
            int? courseCategoryID = Request.Form["CourseTypeDropdown"].ParseStrTo<int>() == DropdownList.SELECT_ALL ? null : Request.Form["CourseTypeDropdown"].ParseStrTo<int>();
            Guid? schoolyearID = Request.Form["SchoolYearDropdown"].ParseStrTo<Guid>();
            if (Request.Form["OrderedDropdown"].ParseStrTo<int>() != DropdownList.SELECT_ALL && Request.Form["OrderedDropdown"].ParseStrTo<int>() != null)
            {
                isOrdered = Request.Form["OrderedDropdown"].ParseStrTo<int>();
            }
            if (configuretView.Attribute == DropdownList.SELECT_ALL.ToString()) configuretView.Attribute = "";
            Guid? teachingMaterialPoolID = Request.Form["TeachingMaterialDropdown"].ParseStrTo<Guid>();
            NpoiExcelHelper neh = new NpoiExcelHelper();

            var dt = StudentDistributeServices.GetStudentDistributeViewList(configuretView, campusID, collegeID, years, grademajorID,
                 coursematerialID, courseCategoryID, teachingMaterialPoolID, isOrdered, schoolyearID, standardID).Select(x => new
                 {
                     x.SchoolyearCode,
                     x.CollegeName,
                     x.GradeSpecialtyName,
                     x.CourseName,
                     x.TeachingMaterialName,
                     x.TeachingMaterialCode,
                     x.Price,
                     x.DiscountStr,
                     x.DiscountPriceStr,
                     x.StudentQty,
                     x.OrderQty,
                     x.PresentInventory,
                     x.DistributeQty,
                     x.RemainingQty,
                     x.IsDistributeName
                 }).ToTable();
            string[] liststring = { "学年学期", RSL.Get("College"), "年级专业", "课程名称", "教材名称", "教材编号","单价",
                                   "折扣率", "折合价","学生人数","征订数量","库存数量","发放人数","未发人数","发放状态"};
            neh.Export(dt, liststring, "学生发放信息");
            return RedirectToAction("MsgShow", "Common", new
            {
                msg = "导出成功!",
                url = Url.Content("~/StudentDistribute/List").AddMenuParameter()
            });
        }

        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="roleID"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ComfirmOrder(string studentDistributeIDs)
        {
            try
            {
                var user = HttpContext.User as EMIS.Utility.FormValidate.CustomPrincipal;
                var studentDistributeIDList = studentDistributeIDs.Split(',').Select(x => Guid.Parse(x)).ToList();
                StudentDistributeServices.ComfirmStudentDistribute(studentDistributeIDList, user.UserID);
                return base.Json("提交成功。");
            }
            catch (Exception ex)
            {
                return base.Json("提交失败,原因:" + ex.Message);
            }
        }

        /// <summary>
        /// 学生信息列表查询
        /// </summary>
        /// <param name="pararms"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult StudentList(QueryParamsModel pararms)
        {
            ConfiguretView configuretView = ConfiguretExtensions.GetConfiguretermsView(pararms);
            //避开全选值
            var campusID = pararms.getExtraGuid("CampusDropdown");
            var collegeID = pararms.getExtraGuid("CollegeDropdown");
            var classmajorID = pararms.getExtraGuid("ClassmajorDropdown");
            var standardID = pararms.getExtraInt("StandardDictionaryDropDown") == DropdownList.SELECT_ALL ? null : pararms.getExtraInt("StandardDictionaryDropDown");
            var learningformID = pararms.getExtraInt("LearningformDictionaryDropDown") == DropdownList.SELECT_ALL ? null : pararms.getExtraInt("LearningformDictionaryDropDown");
            var yearID = pararms.getExtraInt("SchoolyearDictionaryDropDown") == DropdownList.SELECT_ALL ? null : pararms.getExtraInt("SchoolyearDictionaryDropDown");
            var inSchoolStatusID = pararms.getExtraInt("InSchoolStatusDictionaryDropDown") == DropdownList.SELECT_ALL ? null : pararms.getExtraInt("InSchoolStatusDictionaryDropDown");
            var generalPurposeID = pararms.getExtraInt("GeneralPurposeDictionaryDropDown") == DropdownList.SELECT_ALL ? null : pararms.getExtraInt("GeneralPurposeDictionaryDropDown");
            var GrademajorID = Request.Params["GrademajorID"].ParseStrTo<Guid>();
            var studentDistributeID = Request.Params["studentDistributeID"].ParseStrTo<Guid>();
            return base.Json(StudentDistributeServices.GetStudentDistributeByUserViewList(configuretView, campusID, collegeID, yearID, standardID,
                learningformID, studentDistributeID, generalPurposeID, inSchoolStatusID, GrademajorID, (int)pararms.page, (int)pararms.rows));
            //ConfiguretView configuretView = ConfiguretExtensions.GetConfiguretermsView(pararms);
            //var result = StudentDistributeServices.GetStudentViewGrid(configuretView, (int)pararms.page, (int)pararms.rows);
            //return Json(result); 
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="studentDistributeID"></param>
        /// <param name="studentQty"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Edit(Guid? studentDistributeID, string studentQty)
        {
            StudentDistributeView studentDistributeView = new StudentDistributeView();
            if (studentDistributeID != null && studentDistributeID != Guid.Empty)
            {
                studentDistributeView = StudentDistributeServices.GetSingleStudentDistribute(studentDistributeID.Value);
            }
            else
            {
                studentDistributeView = new StudentDistributeView()
                {
                    StudentDistributeID = Guid.Empty
                };
            }
            return View(studentDistributeView);
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(StudentDistributeView studentDistributeView)
        {
            try
            {
                var user = HttpContext.User as EMIS.Utility.FormValidate.CustomPrincipal;//获取当前登录用户信息
                var studentList = DataGrid.GetTableData<StudentsView>("dgStudentList");//获取底部列表数据、
                StudentDistributeServices.SaveStudentUnpublishedInventory(studentDistributeView, studentList, user.UserID);//保存未发人数信息
                return Json(new ReturnMessage()
                {
                    IsSuccess = true,
                    Message = "保存成功。"
                });
            }
            catch (Exception ex)
            {
                return Json(new ReturnMessage()
                {
                    IsSuccess = false,
                    Message = "保存失败:" + ex.Message
                });
            }
        }

        /// <summary>
        /// 未发放学生信息
        /// </summary>
        /// <param name="studentDistributeID"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetStudentList(Guid? studentDistributeID)
        {
            if (studentDistributeID.HasValue)
            {
                var studentList = StudentDistributeServices.GetStudentDistributeByStudentViewList(studentDistributeID.Value);

                return Json(new JsonDataGridResult<StudentDistribute_UserView> { rows = studentList, total = studentList.Count });
            }
            else
            {
                return Json(new JsonDataGridResult<StudentDistribute_UserView>());
            }
        }

        /// <summary>
        /// 提交确定
        /// </summary>
        /// <param name="studentDistributeID"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult SubmitStudentDistribute(Guid? studentDistributeID)
        {
            StudentDistributeView studentDistributeView = new StudentDistributeView();
            if (studentDistributeID != null && studentDistributeID != Guid.Empty)
            {
                studentDistributeView = StudentDistributeServices.GetSingleStudentDistribute(studentDistributeID.Value);
            }
            else
            {
                studentDistributeView = new StudentDistributeView()
                {
                    StudentDistributeID = Guid.Empty
                };
            }
            studentDistributeView.StudentDistributeNo = StockOutServices.GetStockOutNo(CF_StockOutType.StudentBook);
            return View(studentDistributeView);
        }

        /// <summary>
        /// 提交确定
        /// </summary>
        /// <param name="studentDistributeView"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SubmitStudentDistribute(StudentDistributeView studentDistributeView)
        {
            try
            {
                var user = HttpContext.User as EMIS.Utility.FormValidate.CustomPrincipal;//获取当前登录用户信息
                var studentDistributeIDList = Request.Params["studentDistributeID"].Split(',').Select(x => Guid.Parse(x)).ToList();
                StudentDistributeServices.Save(studentDistributeIDList, studentDistributeView);//保存提交
                return Json(new ReturnMessage()
                {
                    IsSuccess = true,
                    Message = "保存成功。"
                });
            }
            catch (Exception ex)
            {
                return Json(new ReturnMessage()
                {
                    IsSuccess = false,
                    Message = "保存失败:" + ex.Message
                });
            }
        }

        /// <summary>
        /// 发放学生信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult StudentDistributeDetail()
        {
            ViewBag.StudentDistributeID = Request.Params["StudentDistributeID"];
            return View();
        }

        /// <summary>
        /// 发放学生信息列表查询
        /// </summary>
        /// <param name="pararms"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult StudentDistributeDetail(QueryParamsModel pararms)
        {
            Guid? studentDistributeID = Request.Params["studentDistributeID"].ParseStrTo<Guid>();
            ConfiguretView configuretView = ConfiguretExtensions.GetConfiguretermsView(null);

            return base.Json(StudentDistributeServices.GetStudentDistributeDetailViewList(studentDistributeID, (int)pararms.page, (int)pararms.rows));
        }

        /// <summary>
        /// 发放学生明细Excel
        /// </summary>
        /// <param name="pararms"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult StudentDistributeDetailExcel()
        {
            Guid? studentDistributeID = Request.Params["studentDistributeID"].ParseStrTo<Guid>();
            NpoiExcelHelper neh = new NpoiExcelHelper();
            ConfiguretView configuretView = ConfiguretExtensions.GetConfiguretermsView(null);

            var dt = StudentDistributeServices.GetStudentDistributeDetailQuery(studentDistributeID).Select(x => new
                {
                    x.StandardName,
                    x.TeachingMaterialCode,
                    x.TeachingMaterialName,
                    x.StudentDistributeNo,
                    x.DistributeQty,
                    x.Price,
                    x.DiscountStr,
                    x.DiscountPriceStr,
                    x.TotalPriceStr,
                    x.TotalDollarStr,
                    x.RecipientUser,
                    ModifyTime = (x.ModifyTime.HasValue ? x.ModifyTime.Value.ToString("yyyy-MM-dd") : ""),
                    x.StockOutUserName,
                    CreateTime = (x.CreateTime.HasValue ? x.CreateTime.Value.ToString("yyyy-MM-dd") : ""),
                    x.Remark
                }).ToTable();
            string[] liststring = { "学号", "教材编号", "教材名称", "出库编号", "数量", "单价",
                                   "折扣率", "折合价","码洋","总价","签收人","签收日期","出库人","出库日期","备注"};
            neh.Export(dt, liststring, "学生发放明细信息");
            return RedirectToAction("MsgShow", "Common", new
            {
                msg = "导出成功!",
                url = Url.Content("~/StudentDistribute/List").AddMenuParameter()
            });
        }
    }
}