using MaxCommunication.DataBase.Document;
using Newtonsoft.Json;
using PmsSecondaryPackaging.Interface.Service;
using ProjectManagementSystem.Model.DataCache;
using ProjectManagementSystem.Model.Models;
using System.Web.Http;
using System.Web.Http.Results;

namespace ProjectManagementSystem.WebApi.Controller
{
    public class PmsController : ApiController
    {
        public TextDocument textDocument { get; set; } = new TextDocument(@"PMS\Log", "WebApiLog_");
        public InterfaceService interfaceService { get; set; } = new InterfaceService();

        //[HttpGet, HttpPost]
        //public JsonResult<int> Test([FromBody] int B)
        //{
        //    return Json(0);
        //}

        [HttpPost]
        public JsonResult<ScaleResponse> SyncScaleData([FromBody] ScaleWeightData weightData)
        {
            textDocument.WriteFile($"SyncScaleData：{JsonConvert.SerializeObject(weightData)}");
            weightData.LastUpdateTime = System.DateTime.Now;
            CacheScaleWeightData.CacheInstance.AddOrUpdate(weightData.scaleName, weightData, (key, value) => weightData);

            bool result = false;
            for (int i = 0; i < 50; i++)
            {
                if(CacheScaleWeightData.CacheInstance[weightData.scaleName].Status > 0)
                {
                    result = CacheScaleWeightData.CacheInstance.TryRemove(weightData.scaleName, out ScaleWeightData scaleWeightData);
                    break;
                }
                System.Threading.Thread.Sleep(100);
            }

            ScaleResponse scaleReturn = new ScaleResponse();
            if (result)
            {
                scaleReturn.CODE = "0000";
                scaleReturn.MSG = "发送成功";
                scaleReturn.DATA = weightData.scaleName;
            }
            else
            {
                scaleReturn.CODE = "0001";
                scaleReturn.MSG = "发送失败";
                scaleReturn.DATA = weightData.scaleName;
            }
            return Json(scaleReturn);
        }
    }
}
