using FactorySystemBll;
using FactorySystemCommon;
using FactorySystemModel.BusinessModel;
using FactorySystemModel.ResponseModel;
using FactorySystemModel.SqlSugarModel;
using Microsoft.Ajax.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace FactorySystemApi.Controllers
{
    /// <summary>
    /// 用户接口
    /// </summary>
    [UserLoginFilter]
    public class UserController : BaseController<TUser>
    {
        private readonly UserBll UserBll = new UserBll();
        /// <summary>
        /// 初始化
        /// </summary>
        public UserController()
        {
            //设置可新增、修改字段
            InsertField = UpdateField = "FFactoryID,FUser,FName,FPassword,FRoleID,FRoleName,FSex,FPhone,FEmail,FState,FRemark,FEditUser,FEditDate,FFactoryList,FRoleList";
        }

        /// <summary>
        /// 获取首页数量信息
        /// </summary>
        [HttpPost]
        public ApiResult GetHomeTopCount(Dictionary<string, object> inParam)
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                ApiAuthInfo user = Request.Properties["token"] as ApiAuthInfo;
                apiResult.Data = UserBll.GetHomeTopCount(user.FID);
            }, apiResult, Request, inParam);
        }


        /// <summary>
        /// 获取角色列表分页
        /// </summary>
        [HttpPost]
        public ApiResult GetRolePageList(Dictionary<string, object> pageParam)
        {
            return GetTPageList<TRole>(pageParam);
        }


        /// <summary>
        /// 获取角色集合
        /// </summary>
        [HttpPost]
        public ApiResult GetRoleList(Dictionary<string, object> inParam)
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                apiResult.Data = UserBll.GetRoleList();
            }, apiResult, Request, inParam);
        }

        /// <summary>
        /// 新增角色信息
        /// </summary>
        [HttpPost]
        public ApiResult InsertRoleModel(Dictionary<string, object> insertParam)
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                //设置用户字段
                ApiAuthInfo user = Request.Properties["token"] as ApiAuthInfo;
                insertParam = GetDictByField(insertParam, "FCode,FName,FRemark");
                insertParam.Add("FAddUser", user.FID);
                insertParam.Add("FEditUser", user.FID);
                insertParam.Add("FAddDate", DateTime.Now);
                insertParam.Add("FEditDate", DateTime.Now);
                apiResult.Data = BaseBll.InsertDataModel(insertParam, "TRole");
            }, apiResult, Request, insertParam);
        }

        /// <summary>
        /// 修改角色信息
        /// </summary>
        [HttpPost]
        public ApiResult UpdateRoleModel(Dictionary<string, object> updateParam)
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                ApiAuthInfo user = Request.Properties["token"] as ApiAuthInfo;
                updateParam = GetDictByField(updateParam, "FCode,FName,FRemark");
                updateParam.Add("FEditUser", user.FID);
                updateParam.Add("FEditDate", DateTime.Now);
                apiResult.Data = BaseBll.UpdateDataModel(updateParam, "TRole") > 0 ? 1 : 0;
            }, apiResult, Request, updateParam);
        }

        /// <summary>
        /// 删除角色信息
        /// </summary>
        [HttpPost]
        public ApiResult DeleteRoleModel(Dictionary<string, object> deleteParam)
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                apiResult.Data = BaseBll.DeleteDataById(deleteParam, "TRole");
            }, apiResult, Request, deleteParam);
        }

        /// <summary>
        /// 获取菜单集合
        /// </summary>
        [HttpPost]
        public ApiResult GetMenuList(Dictionary<string, object> selectData)
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                ApiAuthInfo user = Request.Properties["token"] as ApiAuthInfo;
                object roleId = null;
                if (selectData != null) selectData.TryGetValue("FRoleId", out roleId);
                bool wantAll = selectData != null && selectData.ContainsKey("FRoleSet");

                if (roleId != null) 
                {
                    apiResult.Data = UserBll.GetMenuList(user.FID, roleId == null ? "" : roleId.ToString(), wantAll);
                }
                else
                {
                    apiResult.Data = UserBll.GetMenuList(user.FID, wantAll);
                }
                //apiResult.Data = UserBll.GetMenuList(user.FID, roleId == null ? "" : roleId.ToString(), wantAll);
               
            }, apiResult, Request);
        }

        /// <summary>
        /// 获取权限信息（非菜单）
        /// </summary>
        [HttpPost]
        public ApiResult GetBasicRoleList(Dictionary<string, object> selectData)
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                ApiAuthInfo user = Request.Properties["token"] as ApiAuthInfo;
                if (selectData != null)
                {
                    bool wantAll = selectData != null && selectData.ContainsKey("FRoleSet");
                    selectData.TryGetValue("FRoleType", out object roleType);
                    selectData.TryGetValue("FViewType", out object viewType);
                    selectData.TryGetValue("FRoleId", out object roleId);
                    selectData.TryGetValue("TeamId", out object teamId);
                    selectData.TryGetValue("Type", out object type);//判断 0协同，1物料路线，2实验号变更
                    apiResult.Data = UserBll.GetBasicRoleList(roleId, int.Parse(roleType.ToString()), viewType != null ? viewType.ToString() : "", user.FID, wantAll, teamId,type);
                }
                else
                {
                    apiResult.Data = new List<string>();
                }
            }, apiResult, Request);
        }

        /// <summary>
        /// 保存权限信息
        /// </summary>
        [HttpPost]
        public ApiResult SaveRolePower(Dictionary<string, object> saveData)
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                ApiAuthInfo user = Request.Properties["token"] as ApiAuthInfo;
                int result = 0;
                if (saveData != null && saveData.TryGetValue("FRoleId", out object roleId))
                {
                    List<string> menuIds = null;
                    if (saveData.TryGetValue("FMenuId", out object menuId) && menuId != null)
                    {
                        menuIds = menuId.ToString().Trim(',').Split(',').ToList();
                    }
                    List<string> viewIds = null;
                    if (saveData.TryGetValue("FViewId", out object viewId) && viewId!=null)
                    {
                        viewIds = viewId.ToString().Trim(',').Split(',').ToList();
                    }
                    List<string> termIds = null;
                    if (saveData.TryGetValue("FTermId", out object termId) && termId != null)
                    {
                        termIds = termId.ToString().Trim(',').Split(',').ToList();
                    }
                    List<string> editIds = null;
                    if (saveData.TryGetValue("FEditId", out object editId) && editId != null)
                    {
                        editIds = editId.ToString().Trim(',').Split(',').ToList();
                    }
                    List<string> editIds2 = null;
                    if (saveData.TryGetValue("FEditId2", out object editId2) && editId2 != null)
                    {
                        editIds2 = editId2.ToString().Trim(',').Split(',').ToList();
                    }
                    result = UserBll.SaveRolePower(user.FID.ToString(), int.Parse(roleId.ToString()), menuIds, viewIds, termIds, editIds, editIds2);
                }
                apiResult.Data = result;
            }, apiResult, Request);
        }

        /// <summary>
        /// 登录（仅开发测试）
        /// </summary>
        [HttpPost]
        [NoCheckUserLogin]
        public ApiResult Login()
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                ApiAuthInfo apiAuthInfo = new ApiAuthInfo()
                {
                    FID = 4,
                    //FName = "李洪伟",
                    //FUser = "HB1100283",
                    FName = "oatest1",
                    FUser = "Hb12345678",
                    FExpireTime = DateTime.Now.AddDays(100).ToString("yyyy-MM-dd HH:mm:ss")
                };
                apiResult.Data = JWTHelper.Encryption(apiAuthInfo);
            }, apiResult, Request);
        }


        /// <summary>
        /// 登出
        /// </summary>
        [HttpPost]
        public ApiResult LoginOut()
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                apiResult.Data = AppSettingsHelper.GetAppSettingVal("Cas_OAUrl") + "logout?appid=testsso&service=" + AppSettingsHelper.GetAppSettingVal("Cas_ReUrl");
                ExceptionHelper.AddSystemJournal(null, apiResult.Data, "注销退出", -1, "LoginOut");
            }, apiResult, Request);
        }
        /// <summary>
        /// 获取权限配置
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetPower(string userid) 
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() => {
                apiResult.Data = UserBll.GetPower(userid).ToList();
            }, apiResult, Request);
            //return UserBll.GetPower(userid).ToList();
        }

        /// <summary>
        /// 创建角色关系
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult CreatePower(Dictionary<string, List<FPower>> list) 
        {

            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                apiResult.Data = UserBll.CreateFPower(list.Values.ToList()[0].ToList());
            }, apiResult, Request);
        }

        /// <summary>
        /// 获取权限列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetPowerList() 
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                apiResult.Data = UserBll.GetFPowerList();
            }, apiResult, Request);
        }

        /// <summary>
        /// 获取冻结列
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetFreezingColumns()
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                ApiAuthInfo user = Request.Properties["token"] as ApiAuthInfo;
                apiResult.Data = UserBll.GetFreezingColumns(user.FID);
               
            }, apiResult, Request);
        }

        /// <summary>
        /// 修改删除冻结列
        /// </summary>
        /// <param name="freezingColumns"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult EditFreezingColumns(string freezingColumns)
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                ApiAuthInfo user = Request.Properties["token"] as ApiAuthInfo;
                TFS_FreezingColumns fc = (TFS_FreezingColumns)UserBll.GetFreezingColumns(user.FID);

                if (fc == null)
                {
                    fc = new TFS_FreezingColumns();
                    fc.FUserID = user.FID;
                    fc.FFreezingColumns = freezingColumns;
                    fc.FAddDate = DateTime.Now;
                    fc.FAddUser = user.FID;

                    List<TFS_FreezingColumns> fcl = new List<TFS_FreezingColumns>
                    {
                        fc
                    };

                    apiResult.Data = UserBll.CreateFreezingColumns(user.FID, fcl);
                }
                else
                {
                    fc.FFreezingColumns = freezingColumns;
                    fc.FEditUser = user.FID;
                    fc.FEditDate = DateTime.Now;

                    apiResult.Data = UserBll.UpdateFreezingColumns(fc);
                }

            }, apiResult, Request);
        }
    }
}
