
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Enums.PF;
using APT.BaseData.Domain.IServices.FM;
using APT.BaseData.Domain.IServices;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.DM;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using NPOI.SS.Formula.Functions;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Services.DomainServices;
using APT.BaseData.Services.Services.FM;
using APT.MS.Domain.Entities.SC.DM;
using APT.MS.Domain.Enums;
using System.Collections.Generic;

namespace APT.SC.WebApi.Controllers.Api.DM
{
    [Route("api/DM/DMDeviceRepair")]
    public class DeviceRepairController : AuthorizeApiController<T_DM_DEVICE_REPAIR>
    {
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMFlowPermitService MFlowPermitService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        public DeviceRepairController(IPFCodeRuleService codeRuleService, IFMNotificationTaskService notificationTaskService, IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService)
        {
            CodeRuleService = codeRuleService;
            NotificationTaskService = notificationTaskService;
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService = approveCallBackService;
            ApproveCallBackService = approveCallBackService;
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_DM_DEVICE_REPAIR entity)
        {
            return SafeExecute<bool>(() =>
            {
                var files = entity.Nav_Files;
                entity.Nav_Files = 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;
                    }
                }
                if (entity.CODE == null)
                {
                    entity.CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                }
                if (entity.USER_ID == null || entity.USER_ID == Guid.Empty)
                {
                    entity.USER_ID = loginUserId;
                }
                if (entity.REPAIR_TIME == DateTime.Parse("0001-01-01 00:00:00"))
                {
                    entity.REPAIR_TIME = DateTime.Now;
                }
                if(entity.STATUS== PFStandardStatus.Archived)
                {
                    throw new Exception("已归档不能编辑");
                }
                if (entity.MineType == 0)
                {
                    var minType = APT.Infrastructure.Api.AppContext.CurrentSession.MineType.ToString();
                    if(!string.IsNullOrEmpty(minType))
                        entity.MineType = int.Parse(minType);
                }
                T_FM_NOTIFICATION_TASK sendNotice = null;
                T_FM_NOTIFICATION_TASK finishNotice = null;
                T_DM_DEVICE_OVERHAUL overhaul = null;
                var deviceBase = this.GetEntity<T_DM_DEVICE_BASE>(t => t.ID == entity.DEVICE_BASE_ID);
                entity.MACHINE_CODE = deviceBase?.MACHINE_CODE;
                entity.MACHINE_NAME = deviceBase?.NAME;
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    if (entity.STATUS == PFStandardStatus.Sign)
                    {
                        entity.STATUS = PFStandardStatus.Archived;
                        overhaul = new T_DM_DEVICE_OVERHAUL
                        {
                            ID = Guid.NewGuid(),
                            OVERHAUL_TIME = DateTime.Now,
                            CODE = DateTime.Now.ToString("yyyyMMddHHmmss"),
                            USER_ID = entity.REPAIR_USER_ID,
                            DEVICE_BASE_ID = entity.DEVICE_BASE_ID,
                            MACHINE_NAME = entity.MACHINE_NAME,
                            SPEC = entity.SPEC,
                            MACHINE_CODE = entity.MACHINE_CODE,
                            POSITION = entity.POSITION,
                            MALFUCTION = entity.DESCRPTION,
                            REPAIR_ID = entity.ID,
                            ORG_ID = entity.ORG_ID,
                            IS_HELP = entity.IS_HELP,
                        };
                    //var userInfo = this.GetEntity<T_FM_USER>(t => t.ID == entity.REPAIR_USER_ID, "Nav_Department");
                    //if (userInfo.Nav_Department !=null && (userInfo.Nav_Department.DEPARTMENT_TYPE == 10 || userInfo.Nav_Department.DEPARTMENT_TYPE == 5))
                    //{
                    //    throw new Exception("维修人员不能是车间级别以上");
                    //}
                    //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], "DM020", "", entity.ID, "DM019_SHOWPRINT", entity.TaskID, true, () =>
                    //{
                    //    if (entity != null)
                    //        this.UpdateEntityNoCommit(entity);
                    //    if (files != null && files.Any())
                    //        this.BantchSaveEntityNoCommit(files);
                    //}, null,entity.REPAIR_USER_ID, null, null, null, "DM019_SHOWPRINT", null);
                    //return true;
                        if (entity.IS_HELP == true)
                        {
                            sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("设备设施检修记录-" + entity.MACHINE_NAME, overhaul.ID, entity.ORG_ID, (Guid)entity.REPAIR_USER_ID, GetEntity<T_FM_USER>(entity.REPAIR_USER_ID.Value).NAME, DateTime.Now, DateTime.Now.AddDays(1), 0, "DM022");
                        }
                        else
                        {
                            sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("设备设施检修记录-" + entity.MACHINE_NAME, overhaul.ID, entity.ORG_ID, (Guid)entity.REPAIR_USER_ID, GetEntity<T_FM_USER>(entity.REPAIR_USER_ID.Value).NAME, DateTime.Now, DateTime.Now.AddDays(1), 0, "DM022");
                        }
                    }
                    if (entity.STATUS == PFStandardStatus.Draft)
                    {
                        entity.STATUS = PFStandardStatus.Sign;
                        var departInfo = this.GetEntity<T_FM_DEPARTMENT>(t => t.ID == entity.DEPARTMENT_ID && t.USER_ID != null, "Nav_User");
                        if (departInfo != null)
                        {
                            sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("设备设施故障报修指定维修人员-" + entity.MACHINE_NAME, entity.ID, entity.ORG_ID, (Guid)departInfo.USER_ID, departInfo.Nav_User.NAME, DateTime.Now, DateTime.Now.AddDays(1), 0, "DM020");
                        }
                    }
                    if (entity.TaskID != Guid.Empty)
                    {
                        finishNotice = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID, entity.ID, "DM019_SHOWPRINT");
                    }
                   
                }
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);
                    if (files != null && files.Any())
                        BantchSaveEntityNoCommit(files);
                    if (sendNotice != null)
                        AddEntityNoCommit(sendNotice);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                    if (overhaul != null)
                        AddEntityNoCommit(overhaul);
                });
                return true;
            });
        }
        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("BackUpdate")]
        public JsonActionResult<bool> BackUpdate(string id)
        {
            return SafeExecute(() =>
            {
                return ApproveCallBackService.CallBack("DM/DMDeviceRepair/BackUpdate", id);
            });
        }
        /// <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_REPAIR>(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.消息, "DM020");

                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);
            });
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetEdit")]
        public JsonActionResult<T_DM_DEVICE_REPAIR> 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_REPAIR>(id, new string[] { "Nav_User", "Nav_Department","Nav_Device","Nav_Repair_Charge_User","Nav_Repair_User",
            "Nav_Files","Nav_Files.Nav_ImgFile.Nav_File"
                });
                if (result != null)
                {
                    if (result.STATUS == PFStandardStatus.Rejected)
                    {
                        result.CONTEXT = ApproveCallBackService.RejectContent(result.ID);
                    }
                }
                return result;
            });
        }
    }
}
