using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using wispro.sp.api.Controllers;
using wispro.sp.entity;
using wispro.sp.share;

namespace wispro.sp.api.AppealHandler
{
    public class MissingCaseReviewHandler : 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 strCaseNo="";
                string strDoItem="";
                string strCaseStage = "";
                foreach (var iv in result)
                {
                    if (iv.InputField == null)
                    {
                        iv.InputField = ((spDbContext)spContext).InputFields.FirstOrDefault(s => s.Id == iv.InputFieldId);
                    }

                    if (iv.InputField.FieldName == "我方文号")
                    {
                        strCaseNo = iv.Value;
                        continue;
                    }

                    if (iv.InputField.FieldName == "处理事项")
                    {
                        strDoItem=iv.Value;
                        continue;
                    }

                    if (iv.InputField.FieldName == "案件阶段")
                    {
                        strCaseStage = iv.Value;
                        continue;
                    }
                }

                var itemControler = new PerformanceItemController((spDbContext)spContext,new Services.FileTaskCacheService());
                PerformanceItem Item = itemControler.GetItemInfoByCaseStage(strCaseNo,strDoItem, strCaseStage);
                CalMonth calMonth = ((spDbContext)spContext).CalMonths.FirstOrDefault(c=>c.Status == 0);

                if (calMonth != null )
                {
                    if (Item.Id == 0 || Item.CalMonthId != calMonth.Id)
                    {
                        Item.Id = 0;
                        SaveToDb(Item, (spDbContext)spContext, calMonth);

                        itemControler.RefreshPoint(Item);
                    }
                }
            }
        }

        private void SaveToDb(PerformanceItem item,spDbContext Context,CalMonth calMonth)
        {
            try
            {
                item.CalMonthId = calMonth.Id;
                var results = Context.PerformanceItems.Where<PerformanceItem>(x =>
                   x.CaseNo == item.CaseNo && x.DoItem == item.DoItem && x.DoItem != "提出报告" && x.CaseStage == item.CaseStage);

                var items = results.Include(pi => pi.CalMonth).FirstOrDefault<PerformanceItem>();

                if (items != null)
                {
                    item.AgentFeedbackMemo = "已算绩效";
                    item.DoItemMemo = $"{items.DoItemMemo}\r\n{items.CalMonth.Year}-{items.CalMonth.Month}已计算！";
                    item.BasePoint = 0;
                }

                if (item.Customer != null && !string.IsNullOrEmpty(item.Customer.Name))
                {
                    var temCustomer = Context.Customers.Where<Customer>(c => c.Name == item.Customer.Name).FirstOrDefault();

                    if (temCustomer == null)
                    {
                        temCustomer = new Customer() { Name = item.Customer.Name };
                        //item.Customer.Id = 0;

                        Context.Customers.Add(temCustomer);
                        Context.SaveChanges();
                        item.Customer = temCustomer;
                        //item.CustomerId = item.Customer.Id;
                    }
                    else
                    {
                        item.Customer = temCustomer;
                    }

                    item.CustomerId = item.Customer.Id;
                    item.Customer = null;
                }
                else
                {
                    item.Customer = null;
                }


                var ItemStaffs = item.ItemStaffs;
                item.ItemStaffs = null;

                if (item.ReviewerId != null)
                {
                    var Reviewer = item.Reviewer;
                    item.Reviewer = null;
                }

                Context.PerformanceItems.Add(item);
                Context.SaveChanges();

                foreach (ItemStaff itemStaff in ItemStaffs)
                {
                    itemStaff.ItemId = item.Id;
                    itemStaff.Item = null;

                    if (itemStaff.DoPersonId == 0 && itemStaff.DoPerson != null)
                    {
                        var temStaff = Context.Staffs.FirstOrDefault<Staff>(s => s.Name == itemStaff.DoPerson.Name);

                        if (temStaff != null)
                        {
                            itemStaff.DoPersonId = temStaff.Id;
                            itemStaff.DoPerson = null;
                        }
                        else
                        {
                            Context.Staffs.Add(itemStaff.DoPerson);
                            Context.SaveChanges();
                            itemStaff.DoPersonId = itemStaff.DoPerson.Id;
                            itemStaff.DoPerson = null;
                        }
                    }
                    else
                    {
                        itemStaff.DoPerson = null;
                    }
                }

                Context.ItemStaffs.AddRange(ItemStaffs);
                Context.SaveChanges();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

    }
}
