using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using wispro.sp.entity;

namespace wispro.sp.api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class IPEasyController : ControllerBase
    {
        spDbContext Context;
        public IPEasyController(spDbContext context)
        {
            Context = context;
        }

        #region 将从IPEasy中获得的信息保存到临时文件或从文件中取出已存在的信息
        private PerformanceItem GetFromCache(string CaseNo,string DoItem = null)
        {
            var attachfileSavePath = utility.ConfigHelper.GetSectionValue("AttachFileSavePath");
            string fileName = $"{CaseNo}{(string.IsNullOrEmpty(DoItem) ? "" : $"-{DoItem}")}.json";

            var path = Path.Combine(attachfileSavePath,
                fileName);

            if (System.IO.File.Exists(path))
            {
                if(new FileInfo(path).CreationTime < DateTime.Now.AddDays(-1))
                {
                    return null;
                }

                using (var file = System.IO.File.OpenText(path))
                {
                    string strJson = file.ReadToEnd();

                    JsonSerializerOptions options = new System.Text.Json.JsonSerializerOptions()
                    {
                        IgnoreNullValues = true
                    };
                    return System.Text.Json.JsonSerializer.Deserialize<PerformanceItem>(strJson,options);
                }
                    
            }
            else
            {
                return null;
            }
        }

        private void SaveToCache(PerformanceItem Item)
        {
            var attachfileSavePath = utility.ConfigHelper.GetSectionValue("AttachFileSavePath");
            string fileName = $"{Item.CaseNo}{(string.IsNullOrEmpty(Item.DoItem) ? "" : $"-{Item.DoItem}")}.json";

            var path = Path.Combine(attachfileSavePath,
                fileName);

            if (System.IO.File.Exists(path))
            {
                System.IO.File.Delete(path);
            }

            JsonSerializerOptions options = new System.Text.Json.JsonSerializerOptions() {
                IgnoreNullValues = true
                
            };
            
            string strJson = System.Text.Json.JsonSerializer.Serialize<PerformanceItem>(Item,options);

            using (var file = System.IO.File.CreateText(path))
            {
                file.Write(strJson);
            }
              
        }
        #endregion

        public PerformanceItem GetCaseInfo(string CaseNo)
        {
            var retItem = GetFromCache(CaseNo);
            if (retItem != null)
            {
                return retItem;
            }
            else
            {
                dynamic retObj = wispro.sp.utility.IPEasyUtility.GetCaseInfo(CaseNo);
                PerformanceItem Item = new PerformanceItem();
                Item.CaseName = retObj.CaseName;
                Item.CaseNo = retObj.CaseNo;
                Item.Customer = new Customer();
                Item.Customer.Name = retObj.CustomerName;
                Item.Customer.Name = Item.Customer.Name.Replace("(null)", "");
                Item.ApplicationType = retObj.ApplicationType;
                Item.BusinessType = retObj.BusinessType;
                Item.CaseCoefficient = retObj.CaseCoefficient;
                Item.CaseMemo = retObj.CaseMemo;
                Item.CaseState = retObj.CaseState;
                Item.CaseType = retObj.CaseType;

                SaveToCache(Item);
                return Item;
            }
        }

        public PerformanceItem GetItemInfo(string CaseNo, string DoItem)
        {
            var retItem = GetFromCache(CaseNo,DoItem);
            if (retItem != null)
            {
                return retItem;
            }
            else
            {
                dynamic retObj = wispro.sp.utility.IPEasyUtility.GetPerformanceRecord(CaseNo, DoItem);
                PerformanceItem Item = new PerformanceItem();
                Item.CaseName = retObj.CaseName;
                Item.CaseNo = retObj.CaseNo;
                Item.DoItem = retObj.DoItem;
                Item.CustomerLimitDate = string.IsNullOrEmpty(retObj.CustomerLimitDate) ? null : DateTime.Parse(retObj.CustomerLimitDate);
                Item.Customer = new Customer();
                Item.Customer.Name = retObj.CustomerName;
                Item.Customer.Name = Item.Customer.Name.Replace("(null)", "");
                Item.DoItemCoefficient = retObj.DoItemCoefficient;
                Item.DoItemMemo = retObj.DoItemMemo;
                Item.DoItemState = retObj.DoItemState;
                Item.EntrustingDate = string.IsNullOrEmpty(retObj.EntrustingDate) ? null : DateTime.Parse(retObj.EntrustingDate);
                Item.FinalizationDate = string.IsNullOrEmpty(retObj.FinalizationDate) ? null : DateTime.Parse(retObj.FinalizationDate);
                Item.FinishedDate = string.IsNullOrEmpty(retObj.FinishedDate) ? null : DateTime.Parse(retObj.FinishedDate);
                //Item.FirstDraftDate = string.IsNullOrEmpty(retObj.FirstDraftDate) ? null : DateTime.Parse(retObj.FirstDraftDate);
                Item.InternalDate = string.IsNullOrEmpty(retObj.InternalDate) ? null : DateTime.Parse(retObj.InternalDate);

                if (!string.IsNullOrEmpty(retObj.DoPersons))
                {

                    Item.ItemStaffs = new List<ItemStaff>();
                    string[] names = retObj.DoPersons.ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var name in names)
                    {

                        ItemStaff iStaff = new ItemStaff();
                        iStaff.DoPerson = Context.Staffs.Where<Staff>(s => s.Name == name).FirstOrDefault();
                        if (iStaff.DoPerson == null)
                        {
                            iStaff.DoPerson = new Staff() { Name = name };
                        }
                        else
                        {
                            iStaff.DoPersonId = iStaff.DoPerson.Id;
                        }



                        Item.ItemStaffs.Add(iStaff);
                    }
                }

                Item.ReturnDate = string.IsNullOrEmpty(retObj.ReturnDate) ? null : DateTime.Parse(retObj.ReturnDate);

                if (!string.IsNullOrEmpty(retObj.Reviewer))
                {
                    string name = retObj.Reviewer;
                    var temReviewer = Context.Staffs.Where<Staff>(s => s.Name == name).FirstOrDefault();
                    if (temReviewer == null)
                    {
                        Item.Reviewer = new Staff() { Name = retObj.Reviewer };
                    }
                    else
                    {
                        Item.Reviewer = temReviewer;
                        Item.ReviewerId = temReviewer.Id;
                    }
                }
                Item.ApplicationType = retObj.ApplicationType;
                Item.BusinessType = retObj.BusinessType;
                Item.CaseCoefficient = retObj.CaseCoefficient;
                Item.CaseMemo = retObj.CaseMemo;
                Item.CaseStage = retObj.CaseStage;
                Item.CaseState = retObj.CaseState;
                Item.CaseType = retObj.CaseType;

                SaveToCache(Item);

                return Item;
            }
        }

    }
}
