using RMYY_CallCenter_Api.Models.Enum;
using RMYY_CallCenter_Api.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Reflection;
using RMYY_CallCenter_Api.Models.Dto;
using RMYY_CallCenter_Api.DB;

namespace RMYY_CallCenter_Api.Controllers
{
    public class WorkOrderBaseController : BaseController
    {
        private Bll.T_Sys_Department deptbll = new Bll.T_Sys_Department();
        private Bll.T_Sys_UserAccount userbll = new Bll.T_Sys_UserAccount();
        private Bll.T_Wowo_repairyqbll yqbll = new Bll.T_Wowo_repairyqbll();
        private Bll.T_Sys_GongDan gdbll = new Bll.T_Sys_GongDan();
        // GET: WorkOrderBase

      

            /// <summary>
            /// 获取院区
            /// </summary>
            /// <returns></returns>
        public ActionResult GetHosArea()
        {

            List<HosArea> mlist = new List<HosArea>();
           var modelist = yqbll.GetListall();
            return Content(modelist.ToJson());

        }



        /// <summary>
        /// 获取科室部门列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetDept(int HosId)
        {
            //int userId = User.F_UserId;
            //if (userId != 0)
            //{
            if (HosId == 0)
                return Error("请选择院区！");
            List<Model.T_Sys_Department> dmodel = deptbll.GetModelList("T_Woid="+ HosId + " and  F_State=1");
            if (dmodel.Count > 0)
            {
                var obj = new
                {
                    rows = dmodel.Select(p => new
                    {
                        deptid = p.F_DeptId,
                        deptName = p.F_DeptName

                    })
                };
                return Content(obj.ToJson());

            }
            else
                return Success("暂无信息！");
            //}
            //return
            //    Error("无操作权限！");
        }

        /// <summary>
        /// 获取所有部门列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetDeptall()
        {
            //int userId = User.F_UserId;
            //if (userId != 0)
            //{
           
            List<Model.T_Sys_Department> dmodel = deptbll.GetModelList("F_State=1");
            if (dmodel.Count > 0)
            {
                var obj = new
                {
                    rows = dmodel.Select(p => new
                    {
                        deptid = p.F_DeptId,
                        deptName = p.F_DeptName

                    })
                };
                return Content(obj.ToJson());

            }
            else
                return Success("暂无信息！");
            //}
            //return
            //    Error("无操作权限！");
        }

        public ActionResult GetPerson(int deptid = 0)
        {
            string sql = "";
            if (deptid != 0)
            {
                var dmodel = deptbll.GetModel(deptid);
                if (dmodel != null)
                {
                    sql = "F_DeptId=" + deptid;
                    sql += "and F_EnableFlag=1";
                }
            }
            var ua = userbll.GetModelList(sql);
            var obj = new
            {
                state = "success",
                message = "成功",
                rows = ua.Select(p => new
                {

                    usercode = p.F_UserCode,
                    username = p.F_UserName,
                    usertelphone = p.F_Telephone,
                    userworkphone = p.F_WorkPhone

                })
            };
            return Content(obj.ToJson());
        }


      
        /// <summary>
        /// 获取科室人员信息
        /// </summary>
        /// <param name="deptid"></param>
        /// <returns></returns>
        public ActionResult GetPersonByDeptId(int deptid = 0)
        {
            string sql = "";
            if (deptid != 0)
            {
                var dmodel = deptbll.GetModel(deptid);
                if (dmodel != null)
                {
                    sql = "F_DeptId=" + deptid;
                    sql += "and F_EnableFlag=1";
                }
            }

            if (deptid > 0)
            {
                Bll.T_Sys_GroupClass gcbll = new Bll.T_Sys_GroupClass();
                List<Model.T_Sys_GroupClass> grouplist = gcbll.GetModelList(" F_IsDelete=0   and F_Date = CONVERT(varchar, GETDATE(), 120)  and F_ClassCode in ( select F_Id from t_sys_class where F_IsDelete = 0 and CONVERT(varchar, GETDATE(),108) between F_InTime and F_OutTime and F_DeptId ='" + deptid + "' )");

                if (grouplist.Count > 0)
                {
                    var obj = new
                    {
                        state = "success",
                        message = "成功",
                        rows = grouplist.Select(p => new
                        {

                            usercode = p.F_UserCode,
                            username = GetUserModel( p.F_UserCode)

                        })
                    };
                    return Content(obj.ToJson());
                }
                else
                {
                    var ua = userbll.GetModelList(sql);
                    var obj = new
                    {
                        state = "success",
                        message = "成功",
                        rows = ua.Select(p => new
                        {

                            usercode = p.F_UserCode,
                            username = p.F_UserName 
                        })
                    };
                    return Content(obj.ToJson());
                }


              
            }

            return Error("deptid要大于0");

          
    
        }

        public string GetUserModel(string usercode = "")
        {
            string sql = " 1=1 ";

            if (!string.IsNullOrWhiteSpace(usercode))
            {
                sql += " and F_UserCode='" + usercode + "'";
            }
            if (string.IsNullOrEmpty(usercode))
                return "";

            Model.T_Sys_UserAccount ua = new Bll.T_Sys_UserAccount().GetModelList(sql).FirstOrDefault();
            if (ua != null)
            {
                return ua.F_UserName;

            }

            return "";

        }

        /// <summary>
        /// 获取转运人
        /// </summary>
        /// <param name="deptid"></param>
        /// <param name="rolecode"></param>
        /// <returns></returns>

        public ActionResult GetTransPson(int deptid = 0, string rolecode = "")
        {
            string sql = "1=1";
            if (deptid != 0)
            {
                sql+= $" and F_DeptId="+deptid;
            }
            if (!string.IsNullOrEmpty(rolecode))
            {
                int roldid = new Bll.T_Sys_Role().GetModel(rolecode).F_RoleId;
                if (roldid != 0)
                {
                    sql += $" and F_RoleId=" + roldid;
                }
            }
            var modellist = userbll.GetModelList(sql);
            var obj = new
            {
                state = "success",
                message = "成功",
                rows = modellist.Select(p => new
                {
                    usercode = p.F_UserCode,
                    username = p.F_UserName,
                    userphon = p.F_Telephone
                })
            };
            return Content(obj.ToJson());
        }
        /// <summary>
        /// 获取工单类型
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="typeid"></param>
        /// <returns></returns>
        public ActionResult GetGongDanType(int pid = 0, int typeid = 1)
        {
            var modelist = gdbll.GetModelList("");
            //if (pid != 0)
            //{
                var obj = new
                {
                    rows = modelist.Where(t => t.F_ParentID == pid && t.F_TypeId == typeid).Select(p => new
                    {
                        fid = p.F_GDId,
                        fname = p.F_Name,
                        pid = p.F_ParentID,
                        typeid=p.F_TypeId
                    })
                };
                return Content(obj.ToJson());
            //}
            //else
            //{
            //    var obj = new
            //    {
            //        rows = modelist.Where(t => t.F_TypeId == typeid).Select(p => new
            //        {
            //            fid = p.F_GDId,
            //            fname = p.F_Name,
            //            pid = p.F_ParentID,
            //            typeid = p.F_TypeId
            //        })
            //    };
            //    return Content(obj.ToJson());
            //}

        }

        /// <summary>
        /// 上传附件
        /// </summary>
        /// <returns></returns>
        //[Authority]
        public ActionResult UploadFile()
        {
            #region 多个上传
            HttpFileCollectionBase files = Request.Files;
            if (files.Count > 0)
            {
                List<Model.T_Sys_Accessories> acs = new List<Model.T_Sys_Accessories>();
                string path = "/Upload/Files/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/" + DateTime.Now.ToString("dd") + "/";
                for (int i = 0; i < files.Count; i++)
                {
                    HttpPostedFileBase file = files[i];
                    string name = FileHelper.Upload(file, path);

                    Model.T_Sys_Accessories model_T_Sys_Accessories = new Model.T_Sys_Accessories();
                    model_T_Sys_Accessories.F_AddTime = DateTime.Now;//上传时间
                    model_T_Sys_Accessories.F_FileName = name;//附件名称
                    model_T_Sys_Accessories.F_FileType = Path.GetExtension(file.FileName);//附件类型
                    model_T_Sys_Accessories.F_FileUrl = path + name;//附件地址
                    model_T_Sys_Accessories.F_Size = file.ContentLength;
                    model_T_Sys_Accessories.F_UserCode = User.F_UserCode;//上传人  
                    int id = new Bll.T_Sys_Accessories().Add(model_T_Sys_Accessories);
                    model_T_Sys_Accessories.F_FileId = id;
                    acs.Add(model_T_Sys_Accessories);
                }
                return Success("成功", acs);
            }
            else
            {
                return Error("请选择要上传的文件");
            }
            #endregion

        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns></returns>
        public ActionResult UploadImage()
        {
            string path = string.Empty;
            HttpPostedFileBase _upfile = Request.Files["upFile"];
            if (_upfile != null)
            {
                path = "/Upload/Pic/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/" + DateTime.Now.ToString("dd") + "/";
                ImageHelper iu = new ImageHelper();
                iu.SavePath = path;
                iu.PostFile = _upfile;
                iu.Upload();
                path = path + iu.OutFileName;
                return Success("成功", path);
            }
            else
                return Error("请选择要上传的文件");
        }

        /// <summary>
        /// 上传图片表单
        /// </summary>
        /// <returns></returns>
        public ActionResult UploadImage64()
        {
            string path = string.Empty;
            //HttpPostedFile _upfile = RequestString.GetFile("upFile");
            string dataurl = HttpUtility.UrlDecode(Request["dataurl"]);
            string filename = Request["filename"];
            if (!string.IsNullOrEmpty(dataurl))
            {
                path = "/Upload/Pic/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/" + DateTime.Now.ToString("dd") + "/";
                ImageHelper iu = new ImageHelper();
                iu.SavePath = path;
                iu.DataUrl = dataurl;
                if (!string.IsNullOrEmpty(filename))
                {

                    iu.SaveType = 1;
                    iu.InFileName = filename;
                }
                iu.Upload64();

                //var configfj = new Bll.T_Sys_SystemConfig().GetModelList(" F_ParamCode='FileUrlPath' ").FirstOrDefault();

                int n = iu.Error;
                if (n == 0)
                {
                    path = path + iu.OutFileName;

                    Model.T_Sys_Accessories model_T_Sys_Accessories = new Model.T_Sys_Accessories();
                    model_T_Sys_Accessories.F_AddTime = DateTime.Now;//上传时间
                    model_T_Sys_Accessories.F_FileName = iu.OutFileName;//附件名称
                    model_T_Sys_Accessories.F_FileType = ".jpg";//附件类型
                    model_T_Sys_Accessories.F_FileUrl = path;//附件地址
                    model_T_Sys_Accessories.F_Size = iu.FileSize;
                    //model_T_Sys_Accessories.F_UserCode = User.F_UserCode;//上传人  
                    int id = new Bll.T_Sys_Accessories().Add(model_T_Sys_Accessories);
                    model_T_Sys_Accessories.F_FileId = id;

                    return Success("成功", model_T_Sys_Accessories);
                }
                else
                {
                    string msg = string.Empty;
                    switch (n)
                    {
                        case 1: msg = "请选择要上传的文件"; break;
                        case 2: msg = "上传的文件类型不支持"; break;
                        case 3: msg = "上传的文件过大"; break;
                        case 4: msg = "未知错误"; break;
                    }
                    return Error(msg);
                }
            }
            else
            {
                return Error("请选择要上传的文件");
            }

        }


        public class HosArea
        {
            /// <summary>
            /// 院区id
            /// </summary>
            public int hosid { get; set; }
            /// <summary>
            /// 院区名称
            /// </summary>
            public string hosname { get; set; }
        }


        public object  CreateInstance()
        {

            //用传递参数来得到一个类的实例

            string itemType = "T_Sys_GongDan";
            string assembleyName = this.GetType().Assembly.GetName().Name;//Net.BLL
            string nameSpace = this.GetType().Namespace;

            Type type = Type.GetType($"RMYY_CallCenter_Api.Bll.{itemType},RMYY_CallCenter_Api.Bll");
            //用Activator .CreateInstance创建函数实例,默认的不带参数的构造函数
            object obj = (object)Activator.CreateInstance(type, null);
            return obj;      
        }
            
    }
}