using APT.BaseData.Domain.Entities.OP;
using APT.BaseData.Domain.Enums.OP;
using APT.Infrastructure.Core;
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/TenantExpiration")]
    public partial class TenantExpirationController : AuthorizeApiController<T_OP_TENANT_EXPIRATION>
    {
        /// <summary>
        ///更新租期
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("UpdateExpiration")]
        public JsonActionResult<bool> UpdateExpiration([FromBody] T_OP_TENANT_EXPIRATION entity)
        {
            return SafeExecute<bool>(() =>
            {
                var orgFilter = new BaseFilter();
                orgFilter.IgnoreOrgRule = true;
                var tenant = this.GetEntities<T_OP_TENANT>(x => x.ID == entity.TENANT_ID, orgFilter).FirstOrDefault();
                var oldTime = tenant.EXPIRATION_TIME;//续费前到期时间
                if (entity.UNIT == (int)OPDateTypeEnum.年)
                {
                    var newTime = oldTime.AddYears(entity.DURATION);
                    tenant.EXPIRATION_TIME = newTime;
                    entity.LAST_TIME = oldTime;
                    entity.EXPIRATION_TIME = newTime;
                }
                else
                {
                    var newTime = oldTime.AddMonths(entity.DURATION);
                    tenant.EXPIRATION_TIME = newTime;
                    entity.LAST_TIME = oldTime;
                    entity.EXPIRATION_TIME = newTime;
                }
                this.UpdateEntity(tenant);
                this.UpdateEntity(entity);
                return true;
            });
        }
    }
}
