using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Entities.OP;
using APT.BaseData.Domain.Msg;
using APT.Infrastructure.Api;
using APT.Infrastructure.Api.Redis;
using APT.Infrastructure.Core;
using APT.Migrations;
using APT.Utility;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace APT.OP.WebApi.Controllers.Api
{
    [Route("api/OP/Tenant")]
    public partial class TenantController : AuthorizeApiController<T_OP_TENANT>
    {
        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedTemplate")]
        public PagedActionResult<T_OP_TENANT> OrderPagedTemplate([FromBody] KeywordPageFilter pageFilter)
        {
            return WitOrderPaged(x => x.IS_TEMPLATE == true, pageFilter);
        }
        /// <returns></returns>
        [HttpPost, Route("Enable")]
        public JsonActionResult<bool> Enable([FromBody] T_OP_TENANT entity)
        {
            return SafeExecute<bool>(() =>
            {
                var filter = new BaseFilter();
                filter.IgnoreOrgRule = true;
                var org = this.GetEntities<T_FM_ORGANIZATION>(x => x.ID == entity.ID, filter).FirstOrDefault();
                org.ENABLE_STATUS = 1;
                entity.ENABLE_STATUS = 1;
                T_FM_ORGANIZATION tenantOrg = new T_FM_ORGANIZATION();
                var targetDB = this.GetEntities<T_OP_TENANT_DB_CONN>(x => x.ID == entity.DB_CONN_ID, filter).FirstOrDefault();
                if (targetDB != null && !string.IsNullOrEmpty(targetDB.DB_CONN))
                {
                    var Conn = targetDB.DB_CONN;
                    using (var context = new MigrationContext(Conn))
                    {
                        tenantOrg = context.GetEntities<T_FM_ORGANIZATION>(x => x.ID == entity.ID, null).FirstOrDefault();
                        tenantOrg.ENABLE_STATUS = 1;
                        context.UpdateEntity(tenantOrg);
                        context.SaveChanges();
                    }
                }                
                this.UnifiedCommit(() =>
                {
                    this.UpdateEntityNoCommit(entity);
                    this.UpdateEntityNoCommit(org);
                });

                return true;
            });
        }

        /// <summary>
        /// 新增修改租户信息
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("TenantUpdate")]
        public JsonActionResult<bool> TenantUpdate([FromBody] T_OP_TENANT tenant)
        {
            return SafeExecute<bool>(() =>
            {
                var orgFilter = new BaseFilter();
                orgFilter.IgnoreOrgRule = true;
                #region 更新数据库配置连接
                var tenantDB = this.GetEntity<T_OP_TENANT_DB_CONN>(x => x.ID == tenant.DB_CONN_ID, orgFilter);
                string value = EncryptHelper.AesEncrypt(tenantDB.DB_CONN, ConfigurationManager.AppSettings["ConnDataKey"]);
                var tenantKey = ConfigurationManager.AppSettings["TenantConnKey"] + tenant.CODE;
                var result = CsRedisManager.StringSet(tenantKey, value);
                #endregion
                T_FM_ORGANIZATION org = null;
                bool isupdate = false;
                #region 下发指定数据库
                var targetDB = this.GetEntity<T_OP_TENANT_DB_CONN>(x => x.ID == tenant.DB_CONN_ID, orgFilter);
                if (targetDB != null && !string.IsNullOrEmpty(targetDB.DB_CONN))
                {                  
                    var Conn = targetDB.DB_CONN;
                    using (var context = new MigrationContext(Conn))
                    {                       
                        org = context.GetEntities<T_FM_ORGANIZATION>(x => x.ID == tenant.ID, null).FirstOrDefault();                      
                    }
                }
                #endregion
                #region 租户信息表
                if (org == null)
                {
                    org = new T_FM_ORGANIZATION()
                    {
                        ID = tenant.ID,
                        ORG_ID = tenant.ID,
                        IS_DELETED = false,
                        ENTITY_ORG_TPYE = 2,
                        FLOW_STATUS = 2,
                        FLOW_SEND_STATUS = 0,
                        CREATE_TIME = DateTime.Now
                    };
                    tenant.EXPIRATION_TIME = DateTime.Now.AddYears(1);//默认新租户1年有效期
                }
                else
                    isupdate = true;
                org.TENANT_CODE = tenant.CODE;
                // org.CODE = tenant.CODE;
                org.CODE = "0001";
                org.NAME = tenant.NAME;
                org.ENABLE_STATUS = tenant.ENABLE_STATUS;
                org.MODIFY_TIME = DateTime.Now;
                #endregion

                #region 更新数据
                UnifiedCommit(() =>
                {
                    if (isupdate)
                    {
                        this.UpdateEntityNoCommit(tenant);
                        this.UpdateEntityNoCommit(org);
                    }
                    else
                    {
                        this.AddEntityNoCommit(tenant);
                        this.AddEntityNoCommit(org);
                    }
                });
                var Connnect = targetDB.DB_CONN;
                using (var context = new MigrationContext(Connnect))
                {
                    try
                    {
                        if (ConfigurationManager.ConnectionStrings["default"].ToString() != Connnect)
                        {
                            if (isupdate)
                            {
                                context.UpdateEntity(org);
                                context.SaveChanges();
                            }
                            else
                            {
                                context.AddEntity(org);
                                context.SaveChanges();
                            }
                        }
                        context.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        context.RollbackTransaction();
                        this.ThrowError("010001", ex.Message + ",StackTrace:" + ex.StackTrace + ",Source:" + ex.Source);
                    }
                }
                #endregion
                return true;
            });
            }
        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("ReSetPwd")]
        public JsonActionResult<bool> ReSetPwd([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var orgFilter = new BaseFilter();
                orgFilter.IgnoreOrgRule = true;
                var tenant = this.GetEntities<T_OP_TENANT>(x => x.ID ==new Guid(filter.Keyword), orgFilter).FirstOrDefault();
                var targetDB = this.GetEntities<T_OP_TENANT_DB_CONN>(x => x.ID == tenant.DB_CONN_ID, orgFilter).FirstOrDefault();
                if (targetDB != null && !string.IsNullOrEmpty(targetDB.DB_CONN))
                {
                    var Conn = targetDB.DB_CONN;
                    using (var context = new MigrationContext(Conn))
                    {
                        string userId = tenant.USER_ID.ToString();                      
                        if (string.IsNullOrEmpty(userId))
                            throw new Exception(ErrMsg.CM_NOEXIT_USER);
                        var user = context.GetEntity<T_FM_USER>(x=>x.ID==new Guid(userId),null);
                        user.PASSWORD = "E10ADC3949BA59ABBE56E057F20F883E";//默认密码123456
                        context.UpdateEntity(user);
                        context.SaveChanges();
                    }
                }
                return true;
            });
        }

        /// <summary>
        /// 排序查询所有数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>

        [HttpPost, Route("VersionOrderEntities")]
        public JsonActionResult<IEnumerable<T_OP_TENANT>> VersionOrderEntities([FromBody] KeywordFilter filter)
        {
            var templateId = filter.Parameter10;
            return WitOrderEntities(x => x.TEMPLATE_ID == new Guid(templateId), filter);
        }
    }
}
