using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.Enums.PF;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.BaseData.Services.DomainServices;
using APT.BaseData.Services.Services.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.FO;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using MySqlX.XDevAPI.Common;
using Org.BouncyCastle.Crypto;
using System;
using System.Linq;

namespace APT.FM.WebApi.Controllers.Api
{
    /// <summary>
    ///  随手拍
    /// </summary>
    [Route("api/FM/FMSnapshot")]
    public partial class SnapshotController : AuthorizeApiController<T_FM_SNAPSHOT>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        public SnapshotController(IFMNotificationTaskService notificationTaskService)
        {
            NotificationTaskService = notificationTaskService;
        }
        /// <summary>
        /// 新增/编辑
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_FM_SNAPSHOT entity)
        {
            return SafeExecute(() =>
            {
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                var files = entity.Nav_Files;
                entity.Nav_Files = null;
                entity.ORG_ID = orgId;
                entity.STATUS = PFStandardStatus.Sign;
                if (files != null && files.Any())
                {
                    files.ForEach(t =>
                    {
                        t.ORG_ID = orgId; t.SNAPSHOT_ID = entity.ID;
                    });
                }
                T_FM_NOTIFICATION_TASK task = null;
                //生成待办给接收人
                if (entity.ACCEPT_ID != null)
                {
                    var userInfo = this.GetEntity<T_FM_USER>(entity.ACCEPT_ID.ToString());
                    task = NotificationTaskService.InsertUserNoticeTaskModel("随手拍问题反馈待确认", entity.ID, orgId, (Guid)entity.ACCEPT_ID, userInfo?.NAME, DateTime.Now,
                                    DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "FM202_SHOWPRINT");
                }
                UnifiedCommit(() =>
                {
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (files != null && files.Any())
                        this.BantchSaveEntityNoCommit(files);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                });
                return true;
            });
        }
        /// <summary>
        /// 接收人确认
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("PersonalAgree")]
        public JsonActionResult<bool> PersonalAgree([FromBody] T_FM_SNAPSHOT entity)
        {
            return SafeExecute(() =>
            {
                var snapshot = this.GetEntity<T_FM_SNAPSHOT>(entity.ID);
                if(snapshot != null)
                    snapshot.STATUS = PFStandardStatus.Archived;
                T_FM_NOTIFICATION_TASK task = null;
                if (entity.TaskID != Guid.Empty)
                {
                    task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                    task.SOURCE_FORMCODE = "FM202_SHOWPRINT";
                }
                UnifiedCommit(() =>
                {
                    if (snapshot != null)
                        this.UpdateEntityNoCommit(snapshot);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                });
                return true;
            });
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetEdit")]
        public JsonActionResult<T_FM_SNAPSHOT> GetEdit([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() => {
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                if (string.IsNullOrEmpty(id))
                    this.ThrowError("060010");
                var result = this.GetEntity<T_FM_SNAPSHOT>(id, new string[] { "Nav_User", "Nav_Files", "Nav_Files.Nav_ImgFile.Nav_File"});
                if (result.CREATER_ID != null)
                {
                    var userInfo = this.GetEntity<T_FM_USER>(result.CREATER_ID.ToString());
                    result.CREATER_NAME = userInfo?.NAME;
                }
                return result;
            });
        }
        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("FullOrderPaged")]
        public PagedActionResult<T_FM_SNAPSHOT> FullOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            var result = this.GetOrderPageEntities<T_FM_SNAPSHOT>(t => true, pageFilter);
            if (result.TotalCount > 0)
            {
                var userIds = result.Data.Select(t => t.CREATER_ID).Distinct().ToList();
                var userInfos = this.GetEntities<T_FM_USER>(t => userIds.Contains(t.ID) && t.ENABLE_STATUS == 0, new BaseFilter(pageFilter.OrgId));
                result.Data.ForEach(t =>
                {
                    var first = userInfos.FirstOrDefault(m => m.ID == t.CREATER_ID);
                    t.CREATER_NAME = first?.NAME;
                });
            }
            return result;
        }
    }
}
