using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Autofac;
using EMIS.Utility.OnlinePay;
using Bowin.Common.JSON;
using EMIS.Entities;
using Bowin.Common.Linq.Entity;
using EMIS.CommonLogic.AdministrativeOrgan;
using EMIS.ViewModel;
using EMIS.CommonLogic.SystemServices;
using Bowin.Web.Controls.Mvc;
using Bowin.Common.Utility;
using System.Data;
using EMIS.Utility;
using EMIS.ViewModel.SystemView;
using System.Text;
using EMIS.CommonLogic.Specialtyclass;
using System.IO;
using System.Drawing.Imaging;
using System.Reflection;

namespace EMIS.Web.Controllers
{
    [Authorization]
    public class CommonController : Controller
    {
        public IConfiguretermsInfoServices ConfiguretermsInfoServices { get; set; }
        public IBatchModifyServices BatchModifyServices { get; set; }
        public IMailVerifyServices MailVerifyServices { get; set; }
        public IUserServices UserServices { get; set; }
        public IContextMenuServices ContextMenuServices { get; set; }
        public IClassmajorServices ClassmajorServices { get; set; }
        public IControlItemServices ControlItemServices { get; set; }
        public IAnnouncementServices AnnouncementServices { get; set; }
        public IWechatMPServices WechatMPServices { get; set; }

        [HttpPost]
        [AllowAnonymous]
        public ActionResult DictionaryDropDown(DropdownListBindType? bindType, string dictionaryCode)
        {
            List<DropdownListItem> list = DictionaryHelper.GetDictionaryValue(dictionaryCode)
                .Where(x => x.RecordStatus > (int)SYS_STATUS.UNUSABLE)
                .Select(x => new DropdownListItem { Text = x.Name, Value = x.Value.ToString() }).ToList();
            DropdownListBindType dbt = bindType == null ? DropdownListBindType.SelectAll : bindType.Value;

            DropdownList.FormatDropdownItemList(dbt, list);

            return base.Json(list);
        }

        [HttpPost]
        public ActionResult SchoolYearDropDown(DropdownListBindType? bindType)
        {
            List<DropdownListItem> list = DictionaryHelper.GetDictionaryValue(typeof(EMIS.ViewModel.CF_Schoolyear).Name)
                .Select(x => new DropdownListItem { Text = x.Name, Value = x.Value.ToString() })
                .OrderByDescending(x => x.Value).ToList();
            DropdownListBindType dbt = bindType == null ? DropdownListBindType.SelectAll : bindType.Value;

            DropdownList.FormatDropdownItemList(dbt, list);

            return base.Json(list);
        }

        [HttpPost]
        public ActionResult DynamicConditionDropDown(DropdownListBindType? bindType, string menuNo, string formClass)
        {
            if (menuNo == "")
            {
                menuNo = null;
            }
            var listAttribute = ConfiguretermsInfoServices.GetConfiguretermsInfo(menuNo, formClass);
            List<DropdownListItem> listdl = new List<DropdownListItem>();
            foreach (var item in listAttribute)
            {
                if (item.ControlType == "DictionaryDropDownList")
                {
                    item.PostUrl = Url.Action("DictionaryDropDown") + "?dictionaryCode=" + item.DictionaryCode + "&bindType=" + (int)DropdownListBindType.SelectAll;
                    item.ControlTextFiled = "Text";
                    item.ControlValueFiled = "Value";
                }
                else if (!string.IsNullOrEmpty(item.PostUrl))
                {
                    var temp = item.PostUrl.Split('?');

                    if (temp.Length > 1)
                    {
                        item.PostUrl = item.PostUrl + "&bindType=" + (int)DropdownListBindType.SelectAll;
                    }
                    else
                    {
                        item.PostUrl = item.PostUrl + "?bindType=" + (int)DropdownListBindType.SelectAll;
                    }

                    item.PostUrl = Url.Content(item.PostUrl);
                }

                DropdownListItem ddl = new DropdownListItem { Text = item.Name, Value = item.ToJson() };
                listdl.Add(ddl);
            }
            DropdownListBindType dbt = bindType == null ? DropdownListBindType.SelectAll : bindType.Value;

            DropdownList.FormatDropdownItemList(dbt, listdl);

            return base.Json(listdl);
        }

        [HttpPost]
        public JsonResult GetPositionConditionData(string menuClass, string mnu)
        {
            //var user = EMIS.Utility.FormValidate.CustomPrincipal.Current;
            if (mnu == "")
            {
                mnu = null;
            }
            var configuretermsInfos = ConfiguretermsInfoServices.GetConfiguretermsInfo(mnu, menuClass);

            var result = new
            {
                Url = Url.Action("DynamicConditionDropDown") + "?menuNo=" + mnu + "&formClass=" + menuClass + "&bindType=" + (int)DropdownListBindType.None,
                TextField = "Text",
                ValueField = "Value",
                Condition = configuretermsInfos[0].listControl,
            };

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult GetPositionConditionComboGrid(string controlName, string dataCondition, string textField, string valueFiled, 
            string url, string configuretermsExpandJson)
        { 
            var configuretermsExpandList = configuretermsExpandJson.JsonToObject<List<Sys_ConfiguretermsExpand>>();
            List<DataGridColumn> columList = new List<DataGridColumn>();
            foreach (var configuretermsExpand in configuretermsExpandList)
            {
                BoundFieldColumn bfc = new BoundFieldColumn { FieldName = configuretermsExpand.ColumnValue, HeaderText = configuretermsExpand.ColumnName, Width = 0.1, Align = AlignStyle.Center };
                columList.Add(bfc);
            }
            ComboGridOptions comboGridOptions = new ComboGridOptions
            {
                TextField = textField,
                ValueField = valueFiled,
                ID = controlName,
                Name = controlName,
                EmptyText = "全部",
                GridOptions = new DataGridOptions
                {
                    Columns = columList,
                    IsCheckOnSelect = true,
                    DataSourceUrl = Url.Content(url),
                    IsPagination = true,
                    IsShowRowNumbers = true,
                    IsSingleSelect = false
                }
            };
            IDictionary<string, string> htmlAttributes = new Dictionary<string, string>() { { "data-condition", dataCondition } };

            return Json(MvcHtmlString.Create(Bowin.Web.Controls.Mvc.ComboGrid.CreateControl(comboGridOptions, htmlAttributes).Render()).ToHtmlString());
        }

        [HttpPost]
        public ActionResult BatchUpdateDropDown(DropdownListBindType? bindType, string menuNo)
        {
            List<DropdownListItem> listdl = new List<DropdownListItem>();
            string columnName = string.Empty;
            var listAttribute = BatchModifyServices.GetBatchModifyList(menuNo);
            foreach (var item in listAttribute)
            {
                DropdownListItem ddl = new DropdownListItem { Text = item.Name, Value = item.ToJson() };
                listdl.Add(ddl);
            }
            DropdownListBindType dbt = bindType == null ? DropdownListBindType.SelectAll : bindType.Value;

            DropdownList.FormatDropdownItemList(dbt, listdl);

            return base.Json(listdl);
        }

        public ActionResult MsgShow(string msg, string url, string windowId = "")
        {
            ViewBag.msg = msg;
            ViewBag.url = url;
            ViewBag.WindowID = string.IsNullOrEmpty(windowId) ? Request["WindowID"] : windowId;
            return View();
        }

        public ActionResult Messager(string msg)
        {
            ViewBag.msg = msg;
            return View();
        }
        //弹出提示并关闭上级弹窗
        public ActionResult MsgShowAndClose(string msg, string WindowID) 
        {
            ViewBag.msg = msg;
            ViewBag.WindowID = string.IsNullOrEmpty(WindowID) ? Request["WindowID"] : WindowID;
            return View();
        }
        //弹出提示并打开原先弹窗
        public ActionResult MsgShowAndOpen(string msg, string WindowID)
        {
            ViewBag.msg = msg;
            ViewBag.WindowID = string.IsNullOrEmpty(WindowID) ? Request["WindowID"] : WindowID;
            return View();
        }
        //弹出提示并打开原先弹窗
        public ActionResult MsgShowAndOpenAddUrl(string msg,string url, string WindowID,string title = "", int? height = null, int? width = null)
        {
            ViewBag.newtitle = title;
            ViewBag.msg = msg;
            ViewBag.WindowID = string.IsNullOrEmpty(WindowID) ? Request["WindowID"] : WindowID;
            ViewBag.url = url;
            ViewBag.Height = height;
            ViewBag.Width = width;
            return View();
        }
        /// <summary>
        /// 批量修改
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult BatchModify()
        {
            string batchModifyName = Request["DropdownBatchModify"];
            var BatchModify = batchModifyName.JsonToObject<Sys_BatchModify>();
            string batchModifyValue = string.Empty;
            string hidBatchModify = Request["PL_hiddenBatchModify"];
            try
            {
                if (BatchModify.ControlType == "TextBox")
                    batchModifyValue = Request[BatchModify.Value + "_TextBox"];
                else if (BatchModify.ControlType == "DropdownList")
                    batchModifyValue = Request[BatchModify.Value + "_DropdownList"];
                else if (BatchModify.ControlType == "DictionaryDropDownList")
                    batchModifyValue = Request[BatchModify.Value + "_DictionaryDropDownList"];
                else if (BatchModify.ControlType == "CheckBox")
                    batchModifyValue = Request[BatchModify.Value + "_CheckBox"].Split(',').Length > 1 ? Request[BatchModify.Value + "_CheckBox"].Split(',')[0] : Request[BatchModify.Value + "_CheckBox"];
                else if (BatchModify.ControlType == "ComboGrid")
                    batchModifyValue = Request[BatchModify.Value + "_ComboGrid"];
                else if (BatchModify.ControlType == "TextBoxDate")
                    batchModifyValue = Request[BatchModify.Value + "_TextBoxDate"];
                else if (BatchModify.ControlType == "TextBoxDateTime")
                    batchModifyValue = Request[BatchModify.Value + "_TextBoxDateTime"];
                else if (BatchModify.ControlType == "NumberBox")
                    batchModifyValue = Request[BatchModify.Value + "_NumberBox"];

                if (BatchModify.ControlType != "TextBox")
                {
                    if (batchModifyValue == "")
                    {
                        batchModifyValue = null;
                    }
                    else if (BatchModify.ControlType == "DropdownList" || BatchModify.ControlType == "DictionaryDropDownList")
                    {
                        if (batchModifyValue == DropdownList.PLEASE_SELECT.ToString())
                        {
                            batchModifyValue = null;
                        }
                    }
                }

                //获取修改的ID 转换成数组
                List<Guid> listID = new List<Guid>();
                for (int i = 0; i < hidBatchModify.Split(',').Length; i++)
                {
                    string batchmodify = hidBatchModify.Split(',')[i];
                    if (!string.IsNullOrEmpty(batchmodify))
                    {
                        listID.Add(new Guid(batchmodify));
                    }
                }
                //List<string> funcationstringlist = BatchModifyServices.GetBatchModifyEvents(BatchModify.MNUID, BatchModify.MUNClass, BatchModify.Value);

                BatchModifyServices.BatchUpdate(BatchModify.MNUID, BatchModify.MUNClass, BatchModify.Value, (object)batchModifyValue, listID);

                return Json(new ReturnMessage { IsSuccess = true, Message = "批量修改成功。" });
                //return RedirectToAction("MsgShow", "Common", new
                //{
                //    WindowID = "none",
                //    msg = "批量修改成功。",
                //    url = Url.Content(BatchModify.ReturnUrl).AddMenuParameter()
                //});
            }
            catch (Exception ex)
            {
                return Json(new ReturnMessage { IsSuccess = false, Message = "批量修改失败,原因:" + ex.Message });
                //return RedirectToAction("MsgShow", "Common", new
                //{
                //    WindowID = "none",
                //    msg = "批量修改失败,原因:" + ex.Message,
                //    url = Url.Content(BatchModify.ReturnUrl).AddMenuParameter()
                //});
            }
        }

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

        public ActionResult RoleSelector()
        {
            return View();
        }

        public ActionResult CollegeSelector()
        {
            return View();
        }

        public ActionResult DepartmentSelector() 
        {
            return View();
        }

        public ActionResult Uploader(string n, Guid? v, int? t)
        {
            string sessionCookieName = Const.LOCAL_SETTING_LOGIN_COOKIENAME;
            if (Request.Cookies[sessionCookieName] != null)
                ViewBag.hfcookieName = Request.Cookies[sessionCookieName].Value;

            if (v.HasValue)
            {
                ViewBag.name = n;
                ViewBag.value = v;
                ViewBag.type = t;
            }
            return View();
        }

        public ActionResult UploaderInit(Guid? id, string n)
        {
            Response.Cache.SetNoStore();

            List<FileUploadView> result = new List<FileUploadView>();
            string sessionName = FileUploadHelper.GetFileUploadSessionName(id.Value);

            if (Session[sessionName] == null)
            {
                Session[sessionName] = new List<FileUploadView>();
            }

            using (var scope = AutofacHelper.RequestLifetimeScope.BeginLifetimeScope())
            {
                IFileUploadServices uploadService = scope.ResolveNamed<IFileUploadServices>(n);

                result = uploadService.GetFileList(id);
                Session[sessionName] = result;
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public ActionResult UploaderSave(FormCollection form)
        {
            Response.Cache.SetNoStore();

            try
            {
                FileUploadView upfile = new FileUploadView();
                var files = Request.Files;
                var formID = (!string.IsNullOrEmpty(Request["v"])) ? new Guid(Request["v"]) : (Guid?)null;
                string sessionName = FileUploadHelper.GetFileUploadSessionName(formID.Value);

                //检查文件扩展名字
                var postedFile = files["Filedata"]; //得到要上传文件
                if (postedFile.FileName == null)
                {
                    return Json(new FileUploadView(), JsonRequestBehavior.AllowGet);
                }

                upfile.FileID = Function.NewPKGuid();

                string fileUrl = FileUploadHelper.UploadFile(postedFile);
                upfile.FileUrl = fileUrl;
                upfile.FileName = postedFile.FileName;
                upfile.FormID = formID;

                if (Session[sessionName] == null)
                {
                    Session[sessionName] = new List<FileUploadView>();
                }
                ((List<FileUploadView>)Session[sessionName]).Add(upfile);

                return Json(upfile, JsonRequestBehavior.AllowGet);
            }
            catch
            {

            }

            return Json(new FileUploadView(), JsonRequestBehavior.AllowGet);
        }

        public ActionResult UploaderDel(Guid? id, Guid? fileid)
        {
            string result = "";

            if (id.HasValue)
            {
                List<FileUploadView> fileList = new List<FileUploadView>();
                string sessionName = FileUploadHelper.GetFileUploadSessionName(id.Value);

                if (Session[sessionName] == null)
                {
                    Session[sessionName] = new List<FileUploadView>();
                }

                fileList = (List<FileUploadView>)Session[sessionName];
                var file = fileList.Where(x => x.FileID == fileid).FirstOrDefault();

                if (file != null)
                {
                    fileList.Remove(file);
                    FileUploadHelper.DeleteFile(file.FileUrl);
                }
                else
                {
                    result = "删除文件失败!";
                }

            }
            else
            {
                result = "文件ID为空,删除文件失败!";
            }

            return Content(result);
        }

        public ActionResult UserVerify(Guid UserID, string Code)
        {
            if (MailVerifyServices.Verify(UserID, Code))
            {
                return View();
            }
            else
            {
                return RedirectToAction("MsgShow", "Common", new
                {
                    msg = "邮件连接已失效或不正确,请重新申请。",
                    url = Url.Content("~/Account/Login")
                });
            }
        }

        [HttpPost]
        public ActionResult UserVerify(ChangePasswordView changeView)
        {
            var userID = new Guid(Request["UserID"]);

            UserServices.ChangePassword(changeView, userID);

            return RedirectToAction("MsgShow", "Common", new
            {
                msg = "密码已经修改,请重新登录验证修改结果。",
                url = Url.Content("~/Account/Login")
            });
        }

        /// <summary>
        /// 添加教师
        /// </summary>
        /// <returns></returns>
        public ActionResult TeacherSelect()
        {
            return View();
        }

        /// <summary>
        /// 添加学生
        /// </summary>
        /// <returns></returns>
        public ActionResult StudentViewSelect() {
            return View();
        }

        /// <summary>
        /// 添加专业
        /// </summary>
        /// <returns></returns>
        public ActionResult SpecialtySelect()
        {
            return View();
        }

        /// <summary>
        /// 添加班级
        /// </summary>
        /// <returns></returns>
        public ActionResult ClassmajorSelect()
        {
            ViewBag.GrademajorID = Request.Params["GrademajorID"];
            return View();
        }

        /// <summary>
        /// 添加班级
        /// </summary>
        /// <returns></returns>
        public ActionResult ClassmajorViewSelect()
        {
            ViewBag.CollegeID = Request.Params["CollegeID"];
            ViewBag.GradeYearID = Request.Params["GradeYearID"];
            ViewBag.StandardID = Request.Params["StandardID"];
            return View();
        }

        /// <summary>
        /// 添加学生(学生发放专用)
        /// </summary>
        /// <returns></returns>
        public ActionResult StudentSelect()
        {
            ViewBag.studentDistributeID = Request.Params["studentDistributeID"];
            ViewBag.GrademajorID = Request.Params["GrademajorID"];
            return View();
        }

        public ActionResult ClassroomSelect()
        {
            return View();
        }

        public ActionResult CoursematerialSelect()
        {
            return View();
        }

        public ActionResult StudentBatchSelect()
        {
            return View();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="formClass"></param>
        /// <param name="mnu"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetContextMenuList(string formClass, string mnu)
        {
            var user = EMIS.Utility.FormValidate.CustomPrincipal.Current;
            //以后好好想想怎么控制按钮
            //var controlContextMenuList = ControlItemServices.GetNeedControlContextMenuNo().Where(x => x.MenuNo == mnu).ToList();

            var contextMenuList = ContextMenuServices.GetContextMenuListByUserAndRoleID((mnu == "" ? null : mnu), formClass, user.UserID, user.RoleID);

            var result = contextMenuList.OrderBy(x => x.SeqNo).Select(x => new
            {
                Name = x.ContextMnuNo,
                Text = x.Title,
                Icon = x.IconName,
                OnClick = x.Scripts
            })
            .ToList();

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 审核历史页面
        /// </summary>
        /// <returns></returns>
        public ActionResult ApproveStatus()
        {
            return View();
        }

        /// <summary>
        /// 审批页面
        /// </summary>
        /// <returns></returns>
        public ActionResult ApproveHandler()
        {
            return View();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult ReportViewer()
        {
            return View();
        }

        public ActionResult UserAnnouncementSend()
        {
            return View(new AnnouncementView());
        }

        [HttpPost]
        public ActionResult UserAnnouncementSend(AnnouncementView announcementView)
        {
            var userIDList = (Request.Form["UserIDs"] ?? "").Split(',').Where(x => !string.IsNullOrEmpty(x)).Select(x => (Guid?)new Guid(x)).ToList();
            try
            {
                var msg = "";
                Sys_Announcement Announcement = AnnouncementServices.UserAnnouncementSave(announcementView, userIDList);
                if (announcementView.IsSendWXEdit)
                {
                    var openIDList = WechatMPServices.GetOpenIDList(null, userIDList);
                    if (openIDList.Count() < userIDList.Count())
                    {
                        msg = "但有部分学生未在微信端登陆或未关注公众号,无法发送消息给他们!";
                    }
                    WechatHelper.SendAnnouncement(announcementView.Title, announcementView.textContent, openIDList, null, Announcement.CreateTime);
                }
                return Json(new ReturnMessage()
                {
                    IsSuccess = true,
                    Message = "发送成功。"+ msg
                });
            }
            catch (Exception ex)
            {
                return Json(new ReturnMessage()
                {
                    IsSuccess = false,
                    Message = "发送失败:" + ex.Message
                });
            }
        }

        public ActionResult UserAnnouncementSendGDCX()
        {
            return View(new AnnouncementView());
        }

        [HttpPost]
        public ActionResult UserAnnouncementSendGDCX(AnnouncementView announcementView)
        {
            var userIDList = (Request.Form["UserIDs"] ?? "").Split(',').Where(x => !string.IsNullOrEmpty(x)).Select(x => (Guid?)new Guid(x)).ToList();
            try
            {
                var msg = "";
                Sys_Announcement Announcement = AnnouncementServices.UserAnnouncementSave(announcementView, userIDList);
                if (announcementView.IsSendWXEdit)
                {
                    var ann = AnnouncementServices.GetAnnouncementViewInfo(Announcement.AnnouncementID);
                    var openIDList = WechatMPServices.GetOpenIDList(null, userIDList);
                    if (openIDList.Count() < userIDList.Count())
                    {
                        msg = "但有部分学生未在微信端登陆或未关注公众号,无法发送消息给他们!";
                    }
                    WechatHelper.SendAnnouncementGDCX(announcementView.Title, announcementView.textContent, ann.CreateUserName, openIDList, null, Announcement.CreateTime);
                }
                return Json(new ReturnMessage()
                {
                    IsSuccess = true,
                    Message = "发送成功。" + msg
                });
            }
            catch (Exception ex)
            {
                return Json(new ReturnMessage()
                {
                    IsSuccess = false,
                    Message = "发送失败:" + ex.Message
                });
            }
        }

        [AllowAnonymous]
        public ActionResult ResImage(string key)
        {
            var context = this.HttpContext;
            var image = RSI.Get(key);

            context.Response.Buffer = true;
            context.Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
            context.Response.Expires = 0;
            context.Response.CacheControl = "no-cache";
            context.Response.AppendHeader("Pragma", "No-Cache");
            image.Save(context.Response.OutputStream, image.RawFormat);

            Type imageFormatType = typeof(ImageFormat);
            System.Reflection.PropertyInfo[] _ImageFormatList = imageFormatType.GetProperties(BindingFlags.Static | BindingFlags.Public);
            for (int i = 0; i != _ImageFormatList.Length; i++)
            {
                ImageFormat _FormatClass = (ImageFormat)_ImageFormatList[i].GetValue(null, null);
                if (_FormatClass.Guid.Equals(image.RawFormat.Guid))
                {
                    context.Response.ContentType = "image/" + _ImageFormatList[i].Name.ToLower();
                }
            }
            context.Response.End();

            return new EmptyResult();
        }
    }
}