using HighWayIot.Repository.service;
using Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HighWayIot.Winform.UserControlPages.RecipeConfigPages
{
    public partial class AddRecipeForm : Form
    {
        ZxRecipeService zxRecipeService = ZxRecipeService.Instance;

        /// <summary>
        /// 关闭窗体时传值
        /// </summary>
        public ZxRecipeEntity CloseValue { get; set; }

        public AddRecipeForm()
        {
            InitializeComponent();
            Init();
        }

        private void Init()
        {
            //string recipeCode = DateTime.Now.ToString("yyyyMMddHHmmss");
            //RecipeCodeTextBox.Text = recipeCode;
        }

        private void ConfrimAddButton_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(RecipeCodeTextBox.Text.Trim()))
            {
                MessageBox.Show("配方编号不能为空！");
                return;
            }

            string s = RecipeCodeTextBox.Text.Trim();

            if (zxRecipeService.GetRecipeInfosByRecipeCode(s).Count > 0)
            {
                MessageBox.Show("配方编号重复！");
                return;
            }

            ZxRecipeEntity zxRecipeEntity = new ZxRecipeEntity()
            {
                RecipeCode = s,
                RecipeName = RecipeNameTextBox.Text.Trim(),
                RecipeSpecCode = SpecCodeTextBox.Text.Trim(),
                RecipeSpecName = SpecNameTextBox.Text.Trim(),
                IsDeleted = false,
                IsUse = IsUseCheckBox.Checked,
            };
            if (!int.TryParse(SizeKindTextBox.Text.Trim(), out int sizeKind))
            {
                MessageBox.Show("寸别请填入整数阿拉伯数字");
                return;
            }
            zxRecipeEntity.SizeKind = sizeKind;
            if (!decimal.TryParse(FixedWidthTextBox.Text.Trim(), out decimal fixedWidth))
            {
                MessageBox.Show("固定胶宽度请填入可带小数点的阿拉伯数字");
                return;
            }
            zxRecipeEntity.FixedWidth = fixedWidth;
            if (!int.TryParse(WeightErrorTextBox.Text.Trim(), out int weightError))
            {
                MessageBox.Show("重量公差请填入整数阿拉伯数字");
                return;
            }
            zxRecipeEntity.WeightError = weightError;

            if(zxRecipeService.InsertRecipeInfo(zxRecipeEntity))
            {
                MessageBox.Show("配方信息添加成功");
                this.CloseValue = zxRecipeEntity;
                this.Close();
                this.Dispose();
            }
            else
            {
                MessageBox.Show("请检查配方编号是否重复或者为空");
                return;
            }
        }

        private void AddRecipeForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.DialogResult = DialogResult.OK;
        }
    }
}
