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.Infrastructure.Core;
using APT.MS.Domain.Entities.DM;
using APT.MS.Domain.Entities.FO;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Entities.SC.PR;
using APT.MS.Domain.Enums;
using APT.Utility;
using Autofac.Core;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;

namespace APT.SC.WebApi.Controllers.Api.DMController
{
    /// <summary>
    ///  设备设施库采购记录
    /// </summary>
    [Route("api/DM/DMDeviceBasePurchase")]
    public partial class DeviceBasePurchaseController : AuthorizeApiController<T_DM_DEVICE_BASE_PURCHASE>
    {
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        /// <summary>
        /// 设备设施申购
        /// </summary>
        /// <param name="notificationTaskService"></param>
        public DeviceBasePurchaseController(IPFCodeRuleService codeRuleService, IFMNotificationTaskService notificationTaskService, IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService)
        {
            CodeRuleService = codeRuleService;
            NotificationTaskService = notificationTaskService;
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService = approveCallBackService;
        }
        /// <summary>
        /// 新增/编辑
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_DM_DEVICE_BASE_PURCHASE entity)
        {
            return SafeExecute(() =>
            {
                List<T_DM_DEVICE_BASE_PURCHASE_DETAIL_FILE> fileList = new List<T_DM_DEVICE_BASE_PURCHASE_DETAIL_FILE>();
                List<T_DM_DEVICE_BASE_PURCHASE_DETAIL_RECEIPT_FILE> receiptFileList = new List<T_DM_DEVICE_BASE_PURCHASE_DETAIL_RECEIPT_FILE>();
                List<Guid> deletefileList = new List<Guid>();
                List<Guid> deleteReceiptFileList = new List<Guid>();
                List<Guid> deleteDetailList = new List<Guid>();
                if (string.IsNullOrEmpty(entity.CODE))
                    entity.CODE = DateTime.Now.Year.ToString().PadLeft(4, '0') + DateTime.Now.Month.ToString().PadLeft(2, '0') + DateTime.Now.Day.ToString().PadLeft(2, '0') + new Random().Next().ToString();
                var details = entity.Nav_Details;
                entity.Nav_Details = null;
                var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (entity.TaskID != Guid.Empty)
                {
                    var currTask = GetEntity<T_FM_NOTIFICATION_TASK>(t => t.ID == entity.TaskID);
                    if (currTask != null)
                    {
                        loginUserId = currTask.USER_ID;
                    }
                }
                entity.USER_ID = loginUserId;
                entity.DEPARTMENT_ID = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == 0 && t.ID == (Guid)loginUserId)?.DEPARTMENT_ID;
                var mineType = APT.Infrastructure.Api.AppContext.CurrentSession.MineType;
                entity.MineType = int.Parse(mineType.Split(',')[0]);
                if (entity.STATUS != PFStandardStatus.Rejected)
                {
                    entity.STATUS = PFStandardStatus.Draft;
                }
                if (details != null && details.Any())
                {
                    deleteDetailList = details.Select(t => t.ID).ToList();
                    var files = this.GetEntities<T_DM_DEVICE_BASE_PURCHASE_DETAIL_FILE>(t => deleteDetailList.Contains(t.DEVICE_PURCHASE_DETAIL_ID), new BaseFilter(entity.ORG_ID)).ToList();
                    deletefileList = files.Select(t => t.ID).ToList();
                    var receiptFiles = this.GetEntities<T_DM_DEVICE_BASE_PURCHASE_DETAIL_RECEIPT_FILE>(t => deleteDetailList.Contains(t.DEVICE_PURCHASE_DETAIL_ID), new BaseFilter(entity.ORG_ID)).ToList();
                    deleteReceiptFileList = receiptFiles.Select(t => t.ID).ToList();
                    foreach (var item in details)
                    {
                        item.ORG_ID = entity.ORG_ID; item.DEVICE_PURCHASE_ID = entity.ID;
                        if (item.Nav_Files != null && item.Nav_Files.Any())
                        {
                            foreach (var item2 in item.Nav_Files)
                            {
                                T_DM_DEVICE_BASE_PURCHASE_DETAIL_FILE m = new T_DM_DEVICE_BASE_PURCHASE_DETAIL_FILE();
                                m.ORG_ID = entity.ORG_ID; m.DEVICE_PURCHASE_DETAIL_ID = item.ID;
                                m.IMG_FILE_ID = item2.IMG_FILE_ID;
                                m.Nav_ImgFile = null;
                                //deletefileList.Add(m.ID);
                                fileList.Add(m);
                            }
                        }
                        item.Nav_Files = null;
                        if (item.Nav_ReceiptFiles != null && item.Nav_ReceiptFiles.Any())
                        {
                            foreach (var item2 in item.Nav_ReceiptFiles)
                            {
                                T_DM_DEVICE_BASE_PURCHASE_DETAIL_RECEIPT_FILE m = new T_DM_DEVICE_BASE_PURCHASE_DETAIL_RECEIPT_FILE();
                                m.ORG_ID = entity.ORG_ID; m.DEVICE_PURCHASE_DETAIL_ID = item.ID;
                                m.IMG_FILE_ID = item2.IMG_FILE_ID;
                                m.Nav_ImgFile = null;
                                //deletefileList.Add(m.ID);
                                receiptFileList.Add(m);
                            }
                        }
                        item.Nav_ReceiptFiles = null;
                    }
                }
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    entity.STATUS = PFStandardStatus.Approving;
                    //取审批流水码
                    var sysFilter = new SystemCodeFilter();
                    sysFilter.CodeType = (int)PFCodeRuleType.审批流编码;
                    sysFilter.Count = 1;
                    sysFilter.OrgId = entity.ORG_ID;
                    var codes = CodeRuleService.NewGenSerial(sysFilter);
                    var serialCode = codes.Split(new char[] { ',' });
                    MFlowPermitService.InsertApprove(serialCode[0], "DM034", "", entity.ID, "DM034_SHOWPRINT", entity.TaskID, true, () =>
                    {
                        if (deletefileList != null && deletefileList.Any())
                            this.BantchDeleteEntityNoCommit<T_DM_DEVICE_BASE_PURCHASE_DETAIL_FILE>(deletefileList);
                        if (deleteReceiptFileList != null && deleteReceiptFileList.Any())
                            this.BantchDeleteEntityNoCommit<T_DM_DEVICE_BASE_PURCHASE_DETAIL_RECEIPT_FILE>(deleteReceiptFileList);
                        if (entity != null)
                            this.UpdateEntityNoCommit(entity);
                        if (details != null && details.Any())
                            this.BantchSaveEntityNoCommit(details);
                        if (fileList != null && fileList.Any())
                            this.BantchSaveEntityNoCommit(fileList);
                        if (receiptFileList != null && receiptFileList.Any())
                            this.BantchSaveEntityNoCommit(receiptFileList);
                    }, null, null, null, null, null, "DM034_SHOWPRINT", null, "设备设施申购表待审批", FMTASKTYPE.JobSite);
                    return true;

                }
                UnifiedCommit(() =>
                {
                    if (deletefileList != null && deletefileList.Any())
                        this.BantchDeleteEntityNoCommit<T_DM_DEVICE_BASE_PURCHASE_DETAIL_FILE>(deletefileList);
                    if (deleteReceiptFileList != null && deleteReceiptFileList.Any())
                        this.BantchDeleteEntityNoCommit<T_DM_DEVICE_BASE_PURCHASE_DETAIL_RECEIPT_FILE>(deleteReceiptFileList);
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (details != null && details.Any())
                        this.BantchSaveEntityNoCommit(details);
                    if (fileList != null && fileList.Any())
                        this.BantchSaveEntityNoCommit(fileList);
                    if (receiptFileList != null && receiptFileList.Any())
                        this.BantchSaveEntityNoCommit(receiptFileList);
                });
                return true;
            });
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetEdit")]
        public JsonActionResult<T_DM_DEVICE_BASE_PURCHASE> GetEdit([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() => {
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                if (string.IsNullOrEmpty(id))
                    this.ThrowError("030017");
                var result = this.GetEntity<T_DM_DEVICE_BASE_PURCHASE>(id, new string[] { "Nav_User", "Nav_Department","Nav_Details","Nav_Details.Nav_Type",
            "Nav_Details.Nav_Device","Nav_Details.Nav_Department","Nav_Details.Nav_Post","Nav_Details.Nav_Category"
                });
                if (result != null && result.Nav_Details.Any())
                {
                    if (result.STATUS == PFStandardStatus.Rejected)
                    {
                        result.CONTEXT = ApproveCallBackService.RejectContent(result.ID);
                    }
                }
                return result;
            });
        }
        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("BackUpdateNew")]
        public JsonActionResult<bool> BackUpdateNew([FromBody] T_PF_APPROVE entity)
        {
            return SafeExecute(() =>
            {
                return ApproveCallBackService.CallBackNew("DM/DMDeviceBasePurchase/BackUpdateNew", entity);
            });
        }
        /// <summary>
        /// 新增/编辑
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdateChargeUser")]
        public JsonActionResult<bool> FullUpdateChargeUser([FromBody] T_DM_DEVICE_BASE_PURCHASE entity)
        {
            return SafeExecute(() =>
            {
                if (string.IsNullOrEmpty(entity.CODE))
                    entity.CODE = DateTime.Now.Year.ToString().PadLeft(4, '0') + DateTime.Now.Month.ToString().PadLeft(2, '0') + DateTime.Now.Day.ToString().PadLeft(2, '0') + new Random().Next().ToString();
                var details = entity.Nav_Details;
                entity.Nav_Details = null;
                if (details != null && details.Any())
                {
                    details.ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID; t.DEVICE_PURCHASE_ID = entity.ID;
                        t.Nav_Files = null;
                        t.Nav_ReceiptFiles = null;
                    });
                }
                T_FM_NOTIFICATION_TASK task = null;
                List<T_FM_NOTIFICATION_TASK> sendNotices = new List<T_FM_NOTIFICATION_TASK>();
                T_DM_DEVICE_PURCHASE purchase = null;
                List<T_DM_DEVICE_PURCHASE_DETAIL> purchaseDetails = new List<T_DM_DEVICE_PURCHASE_DETAIL>();
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    var userIds = details.Select(t => t.USER_ID).ToList();
                    if (userIds != null && userIds.Any())
                    {
                        purchase = new T_DM_DEVICE_PURCHASE();
                        purchase.ORG_ID = entity.ORG_ID;
                        purchase.CODE = entity.CODE;
                        purchase.REMARK = entity.REMARK;
                        purchase.TPM_ID = entity.TPM_ID;
                        purchase.DEPARTMENT_ID = entity.DEPARTMENT_ID;
                        purchase.USER_ID = entity.USER_ID;
                        purchase.BASE_PURCHASE_ID = entity.ID;
                        purchase.STATUS = PFStandardStatus.Draft;
                        purchase.MineType = entity.MineType;
                        foreach (var item in details)
                        {
                            T_DM_DEVICE_PURCHASE_DETAIL detail = new T_DM_DEVICE_PURCHASE_DETAIL();
                            detail.DEVICE_PURCHASE_ID = purchase.ID;
                            detail.ORG_ID = purchase.ORG_ID;
                            detail.DEVICE_BASE_ID = item.DEVICE_BASE_ID;
                            detail.DEVICE_ID = item.DEVICE_ID;
                            detail.TPM_ID = item.TPM_ID;
                            detail.CATEGORY_ID = item.CATEGORY_ID;
                            detail.TYPE_ID = item.TYPE_ID;
                            detail.IS_EMERGENCY = item.IS_EMERGENCY;
                            detail.SPEC = item.SPEC;
                            detail.REMARK = item.REMARK;
                            detail.QTY = item.QTY;
                            detail.UNIT = item.UNIT;
                            detail.DEVICE_TYPE = item.DEVICE_TYPE;
                            detail.USER_ID = item.USER_ID;
                            purchaseDetails.Add(detail);
                        }
                        var userIdss = new List<Guid>();
                        var userNames=new List<string>();
                        var userInfos = this.GetEntities<T_FM_USER>(t => userIds.Contains(t.ID), new BaseFilter(entity.ORG_ID));
                        foreach (var item in userInfos)
                        {
                            userIdss.Add(item.ID);
                            userNames.Add(item.NAME);
                        }
                        sendNotices = NotificationTaskService.InsertUserNoticeTaskModels("设备设施申购表采购信息完善", purchase.ID, entity.ORG_ID, userIdss, userNames, DateTime.Now,
                                        DateTime.Now.AddDays(1), (int)FMNoticeTypeEnum.消息, "DM036");
                    }
                    if (entity.TaskID != Guid.Empty)
                    {
                        task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                        task.SOURCE_FORMCODE = "DM034_SHOWPRINT";
                    }
                }
                UnifiedCommit(() =>
                {
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (details != null && details.Any())
                        this.BantchSaveEntityNoCommit(details);
                    if (sendNotices != null && sendNotices.Any())
                        this.BantchSaveEntityNoCommit(sendNotices);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                    if (purchase != null)
                        this.UpdateEntityNoCommit(purchase);
                    if (purchaseDetails != null && purchaseDetails.Any())
                        this.BantchSaveEntityNoCommit(purchaseDetails);
                });
                return true;
            });
        }

      
        /// <summary>
        /// 驳回
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("RejectUpdate")]
        public JsonActionResult<bool> RejectUpdate([FromBody] T_PF_APPROVE model)
        {
            return SafeExecute(() =>
            {
                //公共 获取审批流信息
                T_PF_APPROVE modelApp = null;
                List<T_PF_APPROVE_DETAIL> listAppDetail = null;
                T_FM_NOTIFICATION_TASK taskFinish = null;
                string Msg = string.Empty;
                bool ResultGetInfo = ApproveCallBackService.GetApproject(model, ref modelApp, ref listAppDetail, ref taskFinish, ref Msg);
                if (!ResultGetInfo)
                    throw new Exception("驳回失败！");

                if (modelApp == null || listAppDetail == null)
                    throw new Exception("获取驳回信息失败！");
                var entity = this.GetEntity<T_DM_DEVICE_BASE_PURCHASE>(model.DATA_ID, new string[] { "Nav_User"});
                entity.STATUS = PFStandardStatus.Rejected;
                T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
                    //驳回发消息
                    notice = NotificationTaskService.InsertUserNoticeTaskModel("设备设施申购表已被驳回", entity.ID, entity.ORG_ID, (Guid)entity.USER_ID, entity.Nav_User.NAME, DateTime.Now,
               DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "DM034");
               
                UnifiedCommit(() =>
                {
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (notice != null)
                        this.UpdateEntityNoCommit(notice);
                    if (modelApp != null)
                        UpdateEntityNoCommit(modelApp);
                    if (listAppDetail != null && listAppDetail.Count > 0)
                        BantchUpdateEntityNoCommit(listAppDetail);
                    if (taskFinish != null)
                        UpdateEntityNoCommit(taskFinish);
                });
                return true;
                //return ApproveCallBackService.CallReject("HM/HMLicenseAnalysis/RejectUpdate", id);
            });
        }
    }
}
