using APT.BaseData.Domain.Entities.OP;
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/TenantDomain")]
    public class TenantDomain : AuthorizeApiController<T_OP_TENANT>
    {
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_OP_TENANT entity)
        {
            return SafeExecute<bool>(() =>
            {
                var orgFilter = new BaseFilter();
                orgFilter.IgnoreOrgRule = true;
                T_FM_ORGANIZATION tenantOrg = new T_FM_ORGANIZATION();
                var targetDB = this.GetEntities<T_OP_TENANT_DB_CONN>(x => x.ID == entity.DB_CONN_ID, orgFilter).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 = entity.ENABLE_STATUS;
                        context.UpdateEntity(tenantOrg);
                        context.SaveChanges();
                    }
                }
                var org = this.GetEntities<T_FM_ORGANIZATION>(x => x.ID == entity.ID, orgFilter).FirstOrDefault();
                org.ENABLE_STATUS = entity.ENABLE_STATUS;
                var domains = entity.Nav_Domains;
                entity.Nav_Domains = null;
                this.UnifiedCommit(() =>
                {
                    this.UpdateEntityNoCommit(entity);
                    this.UpdateEntityNoCommit(org);
                    if (domains != null && domains.Any())
                        this.BantchSaveEntityNoCommit(domains);
                });

                return true;
            });
        }
    }
}
