using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EMIS.ViewModel;
using Bowin.Web.Controls.Mvc;
using EMIS.CommonLogic.SystemServices;
using EMIS.CommonLogic.AdministrativeOrgan;
using EMIS.Web.Controls;
using Bowin.Common.Data;
using Bowin.Common.Utility;
using EMIS.ViewModel.SystemView;
using EMIS.Utility;
using EMIS.CommonLogic.TeacherManagement;
using EMIS.ViewModel.TeacherManagement;
using EMIS.Utility.FormValidate;
using System.Text.RegularExpressions;

namespace EMIS.Web.Controllers.UserManagement
{
    [Authorization]
    public class UserController : Controller
    {
        public IUserServices UserServices { get; set; }

        public IUserInfoChangeServices UserInfoChangeServices { get; set; }

        public IParameterServices parameterServices { get; set; }

        public Lazy<IStaffServices> staffServices { get; set; }

        /// <summary>
        /// 教师用户页面
        /// </summary>
        /// <returns></returns>
        public ActionResult List()
        {
            return View();
        }

        /// <summary>
        /// 学生用户页面
        /// </summary>
        /// <returns></returns>
        public ActionResult StudentList()
        {
            return View();
        }

        /// <summary>
        /// 教师列表查询
        /// </summary>
        /// <param name="pararms"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult List(QueryParamsModel pararms)
        {
            ConfiguretView configuretView = ConfiguretExtensions.GetConfiguretermsView(pararms);
            //避开全选值
            var campusID = pararms.getExtraGuid("CampusDropdown");
            var collegeID = pararms.getExtraGuid("CollegeDropdown");
            var departmentID = pararms.getExtraGuid("DepartmentDropdown");
            var roleID = pararms.getExtraGuid("Role");
            var dataRange = pararms.getExtraInt("DataRange");
            var stauts = pararms.getExtraInt("Stauts");
            if (dataRange == DropdownList.SELECT_ALL) dataRange = null;
            if (stauts == DropdownList.SELECT_ALL) stauts = null;
            if (configuretView.Attribute == DropdownList.SELECT_ALL.ToString()) configuretView.Attribute = "";
            return base.Json(UserServices.GetUserViewList(configuretView, campusID, collegeID, departmentID, roleID, dataRange, stauts,
                (int)pararms.page, (int)pararms.rows));
        }

        /// <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 educationID = pararms.getExtraInt("Education");
            var schoolYearID = pararms.getExtraInt("SchoolYear");
            var standardID = pararms.getExtraInt("Standard");
            var learnFormID = pararms.getExtraInt("Learningform");
            var classID = pararms.getExtraGuid("ClassmajorDropdown");
            var LearnSystem = pararms.getExtraString("DictionaryLearnSystem");
            if (educationID == DropdownList.SELECT_ALL) educationID = null;
            if (schoolYearID == DropdownList.SELECT_ALL) schoolYearID = null;
            if (standardID == DropdownList.SELECT_ALL) standardID = null;
            if (learnFormID == DropdownList.SELECT_ALL) learnFormID = null;

            if (configuretView.Attribute == DropdownList.SELECT_ALL.ToString()) configuretView.Attribute = "";

            return base.Json(UserServices.GetStudentUserViewList(configuretView, campusID, collegeID, educationID, schoolYearID,
                standardID, learnFormID, classID,LearnSystem, (int)pararms.page, (int)pararms.rows));
        }

        [HttpPost]
        public ActionResult Excel()
        {
            NpoiExcelHelper neh = new NpoiExcelHelper();
            ConfiguretView configuretView = ConfiguretExtensions.GetConfiguretermsView(null);
            //避开全选值
            var campusID = Request.Form["CampusDropdown"].ParseStrTo<Guid>();
            var collegeID = Request.Form["CollegeDropdown"].ParseStrTo<Guid>();
            var departmentID = Request.Form["DepartmentDropdown"].ParseStrTo<Guid>();
            var roleID = Request.Form["Role"].ParseStrTo<Guid>();
            var dataRange = Request.Form["DataRange"].ParseStrTo<int>();
            if (dataRange == DropdownList.SELECT_ALL) dataRange = null;
            if (configuretView.Attribute == DropdownList.SELECT_ALL.ToString()) configuretView.Attribute = "";

            var dt = UserServices.GetUserViewList(configuretView, campusID, collegeID, departmentID, roleID, dataRange)
                .Select(x => new
                {
                    x.LoginID,
                    x.Name,
                    x.SexName,
                    x.CollegeName,
                    x.RoleName,
                    x.DataRangeName,
                    x.RecordStatusDesc,
                    x.CreateTime,
                    x.ModifyTime
                }).ToTable();
            string[] liststring = { "用户名", "姓名", "性别", "院系所", "角色名称", "数据范围", "允许登录", "创建时间", "修改时间" };
            neh.Export(dt, liststring, "用户信息");
            return RedirectToAction("MsgShow", "Common", new
            {
                msg = "导出成功!",
                url = Url.Content("~/User/List").AddMenuParameter()
            });
        }

        [HttpPost]
        public ActionResult StudentExcel()
        {
            NpoiExcelHelper neh = new NpoiExcelHelper();
            ConfiguretView configuretView = ConfiguretExtensions.GetConfiguretermsView(null);
            //避开全选值
            var campusID = Request.Form["CampusDropdown"].ParseStrTo<Guid>();
            var collegeID = Request.Form["CollegeDropdown"].ParseStrTo<Guid>();
            var educationID = Request.Form["Education"].ParseStrTo<int>();
            var schoolYearID = Request.Form["SchoolYear"].ParseStrTo<int>();
            var standardID = Request.Form["Standard"].ParseStrTo<int>();
            var learnFormID = Request.Form["Learningform"].ParseStrTo<int>();
            var classID = Request.Form["ClassmajorDropdown"].ParseStrTo<Guid>();
            var LearnSystem = Request.Form["DictionaryLearnSystem"].ToString();
            if (educationID == DropdownList.SELECT_ALL) educationID = null;
            if (schoolYearID == DropdownList.SELECT_ALL) schoolYearID = null;
            if (standardID == DropdownList.SELECT_ALL) standardID = null;
            if (learnFormID == DropdownList.SELECT_ALL) learnFormID = null;

            if (configuretView.Attribute == DropdownList.SELECT_ALL.ToString()) configuretView.Attribute = "";

            var dt = UserServices.GetStudentUserViewList(configuretView, campusID, collegeID, educationID, schoolYearID,
                standardID, learnFormID, classID, LearnSystem)
                .Select(x => new
                {
                    x.LoginID,
                    x.Name,
                    x.RoleName,
                    x.ClassmajorName,
                    x.RecordStatusDesc,
                    x.Remarks,
                    x.CreateTime,
                    x.CreateUserName
                }).ToTable();
            string[] liststring = { "用户名", "用户名称", "角色类型", "在校班级", "是否可用", "备注", "创建时间", "创建人" };
            neh.Export(dt, liststring, "学生用户信息");
            return RedirectToAction("MsgShow", "Common", new
            {
                msg = "导出成功!",
                url = Url.Content("~/User/StudentList").AddMenuParameter()
            });
        }
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult BatchInitPassword(string userID,int type)
        {
            BatchInitPasswordView batchInitPasswordView = new BatchInitPasswordView();
            batchInitPasswordView.User = userID;
            var parameter=parameterServices.GetParameterValue(ViewModel.CF_ParameterType.TeacherInitPassword);
             if(type==1){
                 parameter = parameterServices.GetParameterValue(ViewModel.CF_ParameterType.StudentInitPassword);
             }
             if (parameter == null)
             {
                 batchInitPasswordView.BatchInt = false;
             }
             else 
             {
                 batchInitPasswordView.BatchInt = true;
             }
                batchInitPasswordView.type = type;
            return View(batchInitPasswordView);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="batchInitPasswordView"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult BatchInitPassword(string userID, BatchInitPasswordView batchInitPasswordView)
        {
            //由于历史原因,目前先采取这种做法,后期再调整
            //batchInitPasswordView.User = userID;

            if (batchInitPasswordView.User != null && batchInitPasswordView.User != "student" && batchInitPasswordView.User != "staff")
            {
                try
                {
                    List<Guid?> userid = batchInitPasswordView.User.SplitIDString();
                    bool isChange = false;
                    if (batchInitPasswordView.BatchInt == true)
                    {
                        isChange = true;
                    }
                    var pwd = batchInitPasswordView.Password;
                    UserServices.BatchInitPassword(userid, isChange, pwd);

                    return Json(new ReturnMessage
                    {
                        IsSuccess = true,
                        Message = "初始化成功"
                    });
                }
                catch (Exception ex)
                {
                    return Json(new ReturnMessage
                    {
                        IsSuccess = false,
                        Message = "初始化失败!" + ex.Message
                    });
                }
            }
            else 
            {
                try
                {
                    string pwd = batchInitPasswordView.Password;
                    if (pwd != null && batchInitPasswordView.BatchInt == true)
                    {
                        if (!(new Regex("^(?=.*?[0-9])(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[#?!@$%^&*-]).{8,}$").IsMatch(pwd)))
                        {
                            return Json(new ReturnMessage()
                            {
                                IsSuccess = true,
                                Message = "保存失败,原因:密码须包含大小写英文、特殊字符、数字且长度大于或等于8位!"
                            });
                        }
                        pwd = pwd.MD5();
                    }
                    if (batchInitPasswordView.type == 0)
                    {
                        parameterServices.SaveTo(ViewModel.CF_ParameterType.TeacherInitPassword, pwd);
                    }
                    if (batchInitPasswordView.type == 1)
                    {
                        parameterServices.SaveTo(ViewModel.CF_ParameterType.StudentInitPassword, pwd);
                    }
                    return Json(new ReturnMessage()
                    {
                        IsSuccess = true,
                        Message = "保存成功!"
                    });
                }
                catch (Exception ex)
                {
                    return Json(new ReturnMessage()
                    {
                        IsSuccess = true,
                        Message = "保存失败,原因:" + ex.Message + "!"
                    });
                }
            }
        }
        [HttpPost]
        public ActionResult Usable(string userIDList)
        {
            try
            {
                UserServices.Usable(userIDList.SplitIDString());

                return Json(new ReturnMessage
                {
                    IsSuccess = true,
                    Message = "启用成功"
                });
            }
            catch (Exception ex)
            {
                return Json(new ReturnMessage
                {
                    IsSuccess = false,
                    Message = "启用失败!" + ex.Message
                });
            }
        }
        [HttpPost]
        public ActionResult UnUsable(string userIDList)
        {
            try
            {
                UserServices.UnUsable(userIDList.SplitIDString());

                return Json(new ReturnMessage
                {
                    IsSuccess = true,
                    Message = "禁用成功"
                });
            }
            catch (Exception ex)
            {
                return Json(new ReturnMessage
                {
                    IsSuccess = false,
                    Message = "禁用失败!" + ex.Message
                });
            }
        }
        public ActionResult ModifyRole(Guid userID)
        {
            return View();
        }

        public ActionResult DataRange(Guid userID)
        {
            return View();
        }

        /// <summary>
        /// 教师用户页面修改角色
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="roleIDs"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveRoles(Guid userID, string roleIDs)
        {
            try
            {
                UserServices.SaveUserRoles(userID, roleIDs.SplitIDString());

                return Json(new ReturnMessage
                {
                    IsSuccess = true,
                    Message = "保存成功"
                });
            }
            catch (Exception ex)
            {
                return Json(new ReturnMessage
                {
                    IsSuccess = false,
                    Message = "保存失败!" + ex.Message
                });
            }
        }

        [HttpPost]
        public ActionResult SaveUserCampus(Guid userID, string campusIDList)
        {
            try
            {
                UserServices.SaveUserCampus(userID, campusIDList.SplitIDString());

                return Json(new ReturnMessage
                {
                    IsSuccess = true,
                    Message = "保存成功"
                });
            }
            catch (Exception ex)
            {
                return Json(new ReturnMessage
                {
                    IsSuccess = false,
                    Message = "保存失败!" + ex.Message
                });
            }
        }

        [HttpPost]
        public ActionResult SaveUserCollege(Guid userID, string collegeIDList)
        {
            try
            {
                UserServices.SaveUserCollege(userID, collegeIDList.SplitIDString());

                return Json(new ReturnMessage
                {
                    IsSuccess = true,
                    Message = "保存成功"
                });
            }
            catch (Exception ex)
            {
                return Json(new ReturnMessage
                {
                    IsSuccess = false,
                    Message = "保存失败!" + ex.Message
                });
            }
        }

        [HttpPost]
        public ActionResult SaveUserDepartment(Guid userID, string departmentIDList)
        {
            try
            {
                UserServices.SaveUserDepartment(userID, departmentIDList.SplitIDString());

                return Json(new ReturnMessage
                {
                    IsSuccess = true,
                    Message = "保存成功"
                });
            }
            catch (Exception ex)
            {
                return Json(new ReturnMessage
                {
                    IsSuccess = false,
                    Message = "保存失败!" + ex.Message
                });
            }
        }

        [HttpPost]
        public ActionResult GetUserRoleList(Guid userID)
        {
            var roleViewList = UserServices.GetUserRolesView(userID);
            return Json(new JsonDataGridResult<RoleView> { rows = roleViewList, total = roleViewList.Count });
        }

        [HttpPost]
        public ActionResult GetUserRoleDropdownList(DropdownListBindType? bindType)
        {
            var user = CustomPrincipal.Current;
            var list = UserServices.GetUserRolesView(user.UserID)
                        .Select(x => new DropdownListItem { Text = x.RoleName, Value = x.RoleID.ToString() }).ToList();
            DropdownListBindType dbt = bindType == null ? DropdownListBindType.SelectAll : bindType.Value;

            DropdownList.FormatDropdownItemList(dbt, list);

            return base.Json(list);
        }


        [HttpGet]
        public ActionResult UserInfoChange()
        {
            Guid? userID = null;
            var query = UserInfoChangeServices.GetStaffView(userID);
            return View(query);
        }

        [HttpPost]
        public ActionResult UserInfoChange(StaffView staffView)
        {
            try
            {
                //string photoUrl = FileUploadHelper.UploadFile(Request.Files["PhotoUrl"]);
                staffServices.Value.UpdateForSelf(staffView);
                return RedirectToAction("MsgShow", "Common", new
                {
                    WindowID = Request["WindowID"],
                    msg = "保存成功!",
                    url = Url.Action("UserInfoChange").AddMenuParameter()
                });
            }
            catch (Exception ex)
            {
                return RedirectToAction("MsgShow", "Common", new
                {
                    WindowID = Request["WindowID"],
                    msg = "保存失败,原因:" + ex.Message + "!",
                    url = Url.Action("UserInfoChange").AddMenuParameter()
                });
            }
        }

        public object staffView { get; set; }
    }
}