using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MECF.Framework.UI.Client.TrayThickness
{
    public class PMDataViewManager
    {
        PMCoatingThickness PMData;
        PMDataViewSqlHelp pmDataHelp = new PMDataViewSqlHelp();
        private string PMGuid;
        public PMDataViewManager(PMCoatingThickness pmData, string pmGuid)
        {
            PMData = pmData;
            PMGuid = pmGuid;
        }
        public void UpTrayCoatingThickness()
        {
            PMCoatingThickness _pmCoatingThickness = pmDataHelp.GetTrayCoatingThickness(PMGuid);
            if (_pmCoatingThickness != null )
            {
                PMData.MinorCycle.Update(_pmCoatingThickness.MinorCycle);
                PMData.MajorCycle.Update(_pmCoatingThickness.MajorCycle);
            }
        }
        /// <summary>
        /// 界面数据设置到数据库
        /// </summary>
        public bool SET(out string reason)
        {
            reason = "";

            // 校验托盘组件数据
            if (!PMData.Validate(out reason))
                return false;

            List<CoatingData> coatingDataList = new List<CoatingData>()
            {
                PMData.MinorCycle,
                PMData.MajorCycle, 
            };

            //检查单个环对象是否存在空数据
            foreach (var item in coatingDataList)
            {
                if (item.GetType().GetProperties()
                          .Where(pi => pi.PropertyType == typeof(string))
                          .Select(pi => (string)pi.GetValue(item))
                          .Any(string.IsNullOrEmpty))
                {
                    reason = $"Please check empty value";
                    return false;
                }
            }
            var ret = pmDataHelp.UpTrayNumberData(PMData, PMGuid, coatingDataList);
            if (!ret)
                reason = "Failed to write tray Info. to database.";
            return ret;
        }

        /// <summary>
        /// 用户输入数据时，去数据库查询更新到界面
        /// </summary>
        /// <param name="part"></param>
        public void LoadCoatingData(string part)
        {

            switch (part)
            {
                case "MinorCycle":
                    ForUpCoatingData(PMData.MinorCycle.SerialNumber, PMData.MinorCycle);
                    break;
                case "MajorCycle":
                    ForUpCoatingData(PMData.MajorCycle.SerialNumber, PMData.MajorCycle);
                    break;
                default:
                    break;
            }

        }

        private void ForUpCoatingData(string number, CoatingData data)
        {
            var coatingData = pmDataHelp.GetCoatingData(number, out var isExistedInDb);
            if (isExistedInDb)
            {
                data.Update(coatingData);
            }
        }
    }
}
