using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.BS;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Enums;
using APT.Utility;
using APT.WebApi.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace APT.BS.WebApi.Controllers.Api
{
    [Route("api/BS/BSRiskSubmitContentTemp")]
    public partial class BSRiskSubmitContentTempController : AuthorizeApiController<T_BS_RISK_SUBMIT_CONTENT_TEMP>
    {
        IFMFlowPermitService MFlowPermitService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IPFCodeRuleService CodeRuleService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        public BSRiskSubmitContentTempController(IFMNotificationTaskService notificationTaskService, IFMFlowPermitService mFlowPermitService, IPFCodeRuleService codeRuleService, IPFApproveCallBackService approveCallBackService)
        {
            NotificationTaskService = notificationTaskService;
            MFlowPermitService = mFlowPermitService;
            CodeRuleService = codeRuleService;
            ApproveCallBackService = approveCallBackService;
        }

        /// <summary>
        /// 隐患上报详情待入库
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_BS_RISK_SUBMIT_CONTENT_TEMP entity)
        {
            return SafeExecute<bool>(() =>
            {
                //问题ID 判断检查问题描述 整改建议与措施  
                //如果不完全一致 添加问题 修改问题ID
                //入库
                //给审核人 添加待办
                Guid UserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;
                if (entity.USER_ID_EDIT.HasValue)
                {
                    if (entity.USER_ID_EDIT.Value != UserId)
                    {
                        if (APT.Infrastructure.Api.AppContext.CurrentSession.UserName != "admin")
                        {
                            var userDel = GetEntity<T_FM_USER>(entity.USER_ID_EDIT.Value);
                            throw new Exception("您没有权限处理此隐患，请联系【" + userDel.NAME + "】（安环部负责人）处理!");
                        }
                    }
                }
                else
                {
                    //未指定 就是当前的人
                    entity.USER_ID_EDIT = UserId;
                }

                if (entity.ORDERTYPE == OrderType.Temp)
                {
                    //保存草稿
                    UnifiedCommit(() =>
                    {
                        UpdateEntityNoCommit(entity);
                    });
                }
                else
                {
                    //保存信息
                    //判断是否需要新增问题
                    //如果需要 审批流
                    bool isAdd = false;
                    bool isAddQues = true;
                    T_BS_CHECK_QUESTION ques = null;
                    if (entity.CHECK_QUESTION_ID != null && entity.CHECK_QUESTION_ID.HasValue)
                    {
                        entity.Nav_CheckQuestion = this.GetEntity<T_BS_CHECK_QUESTION>(entity.CHECK_QUESTION_ID.Value);
                    }
                    if (entity.Nav_CheckQuestion != null && (entity.DEMAND != entity.Nav_CheckQuestion.DEMAND || entity.DESCREPTION != entity.Nav_CheckQuestion.DESCREPTION))
                    {
                        ques = GetEntity<T_BS_CHECK_QUESTION>(e => e.DEMAND == entity.DEMAND && e.DESCREPTION == entity.DESCREPTION);// && e.DESCREPTION == entity.Nav_CheckQuestion.DESCREPTION
                        if (ques != null)
                        {
                            isAddQues = false;
                        }
                    }
                    else
                    {
                        isAddQues = false;
                    }

                    if (!isAddQues)
                    {
                        var CheckMain = GetEntity<T_BS_CHECK_MAIN>(e => e.CHECKCONTENT == entity.CHECKCONTENT && e.CHECKCONTENT == entity.CHECKCONTENT && e.CHECK_QUESTION_ID == entity.CHECK_QUESTION_ID);
                        if (CheckMain == null)
                        {
                            isAdd = true;
                        }
                    }
                    else
                    {
                        isAdd = true;
                    }

                    if (isAdd)
                    {
                        //取审批流水码
                        var sysFilter = new SystemCodeFilter();
                        sysFilter.CodeType = (int)PFCodeRuleType.审批流编码;
                        sysFilter.Count = 1;
                        sysFilter.OrgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                        string serialCode = CodeRuleService.NewGenSerial(sysFilter);

                        entity.APPROVE_ID = Guid.NewGuid();
                        MFlowPermitService.InsertApprove(serialCode, "BS048", null, entity.ID, "BS048_SHOWPRINT", entity.TaskID, true, () =>
                         {
                             if (entity != null)
                                 UpdateEntityNoCommit(entity);
                         }, entity.APPROVE_ID.Value);
                    }
                    else
                    {
                        //无需新增问题
                        entity.ISINSERT = true;
                        T_FM_NOTIFICATION_TASK finishNotice = null;
                        if (entity.TaskID != new Guid())
                        {
                            finishNotice = NotificationTaskService.GetTaskFinishModel(entity.TaskID);//wyw 之前方法 巡回安全检查填写会报错
                        }

                        UnifiedCommit(() =>
                        {
                            if (ques != null && ques.IS_DELETED)
                            {
                                //如果是已删除的问题
                                ques.IS_DELETED = false;
                                entity.CHECK_QUESTION_ID = ques.ID;
                                UpdateEntityNoCommit(ques);
                            }
                            UpdateEntityNoCommit(entity);

                            if (finishNotice != null)
                                UpdateEntityNoCommit(finishNotice, "NOTICE_STATUS", "TASK_DT", "MODIFIER_ID");
                        });
                    }
                }
                return true;
            });
        }


        /// <summary>
        /// 隐患上报详情待入库 审批回调
        /// api/BS/BSRiskSubmit/DealEnd
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("ApproveBackBS048")]
        public JsonActionResult<bool> ApproveBackBS048(string id)
        {
            return SafeExecute<bool>(() =>
            {
                return ApproveCallBackService.CallBack("BS/BSRiskSubmitContentTemp/ApproveBackBS048", id);
            });
        }
    }
}
