using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using wispro.sp.entity;
using wispro.sp.share;

namespace wispro.sp.api.AppealHandler
{
    public class ChangeReviewerReviewer : IDoAppealObject
    {
        public void DoAppeal(AppealObject appeal, int appealRecordId, DbContext spContext)
        {
            bool isAggree = false;
            foreach (var iv in appeal.inputFieldValues)
            {
                if (iv.InputField == null)
                {
                    iv.InputField = ((spDbContext)spContext).InputFields.FirstOrDefault(s => s.Id == iv.InputFieldId);
                }

                if (iv.InputField.FieldName == "审核意见" && iv.Value == "确认变更")
                {
                    isAggree = true;
                    break;
                }
                else
                {
                    if (iv.InputField.FieldName == "审核意见" && string.IsNullOrEmpty(iv.Value))
                    {
                        throw (new ApplicationException("请填写审核意见!"));
                    }
                }

            }
            if (isAggree)
            {
                var result = ((spDbContext)spContext).InputFieldValues.Where<InputFieldValue>(f => 
                        f.AppealRecordId == appealRecordId && f.InputField.AppealState == 0)
                    .ToList();

                string strReviewerName = "";
                foreach (var iv in result)
                {
                    if (iv.InputField == null)
                    {
                        iv.InputField = ((spDbContext)spContext).InputFields.FirstOrDefault(s => s.Id == iv.InputFieldId);
                    }

                    if (iv.InputField.FieldName == "实际核稿人")
                    {
                        strReviewerName = iv.Value;
                        break;
                    }
                }

                var appRecord = ((spDbContext)spContext).AppealRecords.Include(a=>a.Item).FirstOrDefault(f => f.Id == appealRecordId);
                
                if (appRecord != null && appRecord.Item != null)
                {
                    var newStaff = ((spDbContext)spContext).Staffs.FirstOrDefault(s => s.Name == strReviewerName.Trim());

                    if(newStaff != null)
                    {
                        appRecord.Item.ReviewerId = newStaff.Id;
                    }
                    else
                    {
                        throw new ApplicationException("输入的【实际核稿人】不存在！");
                    }

                }


            }
        }
    }
}
