using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Entities.PF;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;

namespace APT.PF.WebApi.Controllers.Api
{
    /// <summary>
    ///  审批角色
    /// </summary>
    [Route("api/PF/PFApprovalRole")]
    public partial class ApprovalRoleController : AuthorizeApiController<T_PF_APPROVAL_ROLE>
    {
        /// <summary>
        /// 更新或新增数据
        /// </summary>
        /// <param name="entity">对象实体</param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_PF_APPROVAL_ROLE entity)
        {
            return SafeExecute<bool>(() =>
            {
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                //var roleCodes = this.GetEntities<T_PF_APPROVAL_ROLE>(t => true, new BaseFilter(orgId)).Select(x => x.NAME).ToList();
                //if (roleCodes.Contains(entity.NAME))
                //    throw new Exception("系统已存在审批角色编码为" + entity.NAME + "的数据,请勿重复！");
                var departs = entity.Nav_ApproveDeparts.Where(t=>!t.IS_DELETED).ToList();
                entity.Nav_ApproveDeparts = null;
                if (departs != null && departs.Any())
                {
                    departs.ForEach(t =>
                    {
                        t.ORG_ID = orgId;
                        t.APPROVAL_ROLE_ID = entity.ID;
                        t.Nav_Department = null;
                    });
                }
                UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);   //保存主表
                    if (departs != null && departs.Any())
                        BantchSaveEntityNoCommit(departs);    //保存子表
                });
                return true;
            });
        }
    }
}
