using System;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DeviceRepairAndOptimization.Pages.FormVersion;
using System.Collections.Generic;
using DeviceRepair.Models;
using DeviceRepairAndOptimization.Common;
using DeviceRepairAndOptimization.Biz;
using DeviceRepair.Utils;
using DeviceRepair.Models.Common;
using Newtonsoft.Json.Linq;

namespace DeviceRepairAndOptimization.Pages.DriveInformation
{
    public partial class Page_DriveInfoEdit : XtraForm
    {
        private string Caption;

        private View_DriveInfomationModel CurrentModel;
        private int FormVerValue = 0;
        private string FormVerName = "";

        public Page_DriveInfoEdit(string caption = null, View_DriveInfomationModel Model = null)
        {
            InitializeComponent();
            Caption = caption ?? "新增";
            CurrentModel = Model ?? new View_DriveInfomationModel();
            layoutControlGroup1.ViewInfo.OwnerILayoutControl.AllowCustomizationMenu = false;
        }

        private void Page_DriveInfoEdit_Load(object sender, EventArgs e)
        {
            this.Text = Caption;
            if (CurrentModel != null && CurrentModel.AutoID > 0)
                BindDatas();
        }

        private void BindDatas()
        {
            // 设备编号
            txt_EquipmentID.Enabled = false;
            txt_EquipmentID.Text = CurrentModel.EquipmentID;

            // 设备名称
            txt_EquipmentName.Text = CurrentModel.EquipmentName;

            // 设备型号规格
            txt_Specification.Text = CurrentModel.Specification;

            // 制造厂家
            txt_Manufacturer.Text = CurrentModel.Manufacturer;

            // 出厂编号
            txt_SerialNumber.Text = CurrentModel.SerialNumber;

            // 投产年月
            if (!string.IsNullOrWhiteSpace(CurrentModel.UsingDate))
            {
                DateTime t;
                if (DateTime.TryParse(CurrentModel.UsingDate, out t))
                    txt_UsingDate.EditValue = t;
            }

            // 设备总容量
            txt_Totalcapacity.Text = CurrentModel.Totalcapacity + "";

            // 设备重量
            txt_Weight.Text = CurrentModel.Weight + "";

            // 设备类别
            txt_EquipmentCategory.Text = CurrentModel.EquipmentCategory;

            // 设备原值
            txt_EquipmentOriginalvalue.Text = CurrentModel.EquipmentOriginalvalue + "";

            // 设备状态
            ck_EquipmentStatus.EditValue = CurrentModel.EquipmentStatus == 1;

            // 保质期
            txt_WarrantyPeriod.Text = CurrentModel.WarrantyPeriod;

            // 安装地点
            txt_InstallationLocation.Text = CurrentModel.InstallationLocation;

            // 所属单元
            txt_OwningUnit.Text = CurrentModel.OwningUnit;

            // 运行参数
            txt_OperatingParameters.Text = CurrentModel.OperatingParameters;

            // 使用的表单
            FormVerValue = CurrentModel.MaintenanceFormVersion;
            //FormVerName = CurrentModel.MaintenanceFormVersionName;
            btn_SelectFormRev.Text = CurrentModel.VersionCode;

            // 备注
            txt_Remarks.Text = CurrentModel.Remarks;
        }

        private void btn_Submit_Click(object sender, EventArgs e)
        {
            try
            {
                if (DataValidata())
                {
                    if (CurrentModel.AutoID == 0)
                    {
                        CurrentModel.CreatUser = GlobalInfo.CurrentUser.AutoID;
                        CurrentModel.ChangeUser = GlobalInfo.CurrentUser.AutoID;
                        APIResponseData apiResponseData = DeviceManager.Instance.UpdateDriveInformation(CurrentModel.ToKeyValuePairs());

                        if (!apiResponseData.IsSuccess)
                            throw new Exception(apiResponseData.Message);
                    }
                    else
                    {
                        //修改
                        APIResponseData apiResponseData = DeviceManager.Instance.GetDataByAutoID(CurrentModel.AutoID); // DeviceInformationInfo t1

                        if (!apiResponseData.IsSuccess)
                            throw new Exception(apiResponseData.Message);

                        DeviceInformationInfo t1 = apiResponseData.ToDeserializeObject<DeviceInformationInfo>();
                        JObject jo = JObject.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(CurrentModel));
                        DeviceInformationInfo Item = jo.ToObject<DeviceInformationInfo>();
                        Dictionary<string, object> paras = t1.GetDifferencesColumn(Item);
                        paras.Add("AutoID", t1.AutoID);

                        if (paras.ContainsKey("CreatDate"))
                            paras.Remove("CreatDate");
                        if (paras.ContainsKey("ChangeUser"))
                            paras["ChangeUser"] = GlobalInfo.CurrentUser.AutoID;
                        else
                            paras.Add("ChangeUser", GlobalInfo.CurrentUser.AutoID);
                        apiResponseData = DeviceManager.Instance.UpdateDriveInformation(paras);

                        if (!apiResponseData.IsSuccess)
                            throw new Exception(apiResponseData.Message);
                    }

                    DialogResult = DialogResult.OK;
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }

        /// <summary>
        /// 选择表单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_SelectFormRev_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            int Value = 0;
            int.TryParse(FormVerValue + "", out Value);

            Page_FormVersionDialog view = new Page_FormVersionDialog(Value);
            if (view.ShowDialog() == DialogResult.OK)
            {
                CurrentModel.MaintenanceFormVersion = view.SelectValue;
                FormVerValue = view.SelectValue;
                FormVerName = view.SelectText + "";
                btn_SelectFormRev.Text = FormVerName;
            }
        }

        /// <summary>
        /// 数据验证
        /// </summary>
        private bool DataValidata()
        {
            try
            {
                dxErrorProvider1.ClearErrors();
                View_DriveInfomationModel t2 = new View_DriveInfomationModel
                {
                    AutoID = CurrentModel.AutoID,
                    EquipmentID = txt_EquipmentID.Text,
                    EquipmentName = txt_EquipmentName.Text,
                    Specification = txt_Specification.Text,
                    Manufacturer = txt_Manufacturer.Text,
                    SerialNumber = txt_SerialNumber.Text,
                    Totalcapacity = Convert.ToDouble(txt_Totalcapacity.Text),
                    Weight = Convert.ToDouble(txt_Weight.Text),
                    EquipmentCategory = txt_EquipmentCategory.Text,
                    EquipmentOriginalvalue = Convert.ToDecimal(txt_EquipmentOriginalvalue.Text),
                    EquipmentStatus = (bool)ck_EquipmentStatus.EditValue ? 1 : 0,
                    WarrantyPeriod = txt_WarrantyPeriod.Text,
                    InstallationLocation = txt_InstallationLocation.Text,
                    OwningUnit = txt_OwningUnit.Text,
                    OperatingParameters = txt_OperatingParameters.Text,
                    MaintenanceFormVersion = FormVerValue,
                    Remarks = txt_Remarks.Text
                };

                #region 设备编号
                if (CurrentModel.AutoID == 0)
                {
                    if (string.IsNullOrWhiteSpace(t2.EquipmentID))
                    {
                        dxErrorProvider1.SetError(txt_EquipmentID, "设备编号字段不允许为空！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                        return false;
                    }

                    if (t2.EquipmentID.Length > 50)
                    {
                        dxErrorProvider1.SetError(txt_EquipmentID, "设备编号字段长度超限,最大字数不能超出50！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                        return false;
                    }

                    APIResponseData apiResponseData = DeviceManager.Instance.GetModelByEquipmentID(t2.EquipmentID + "");

                    if (apiResponseData.IsSuccess && apiResponseData.Data != null)
                    {
                        dxErrorProvider1.SetError(txt_EquipmentID, $"设备编号 - {t2.EquipmentID}已经存在！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                        return false;
                    }
                }
                #endregion

                #region 设备名称
                if (string.IsNullOrWhiteSpace(t2.EquipmentName))
                {
                    dxErrorProvider1.SetError(txt_EquipmentName, "设备名称字段不允许为空！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else if (t2.EquipmentName.Length > 200)
                {
                    dxErrorProvider1.SetError(txt_EquipmentName, "设备名称字段长度超限,最大字数不能超出200！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else
                {
                    dxErrorProvider1.SetError(txt_EquipmentName, "");
                }
                #endregion

                #region 设备型号规格
                if (t2.Specification.Length > 200)
                {
                    dxErrorProvider1.SetError(txt_Specification, "设备型号规格字段长度超限,最大字数不能超出200！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else
                {
                    dxErrorProvider1.SetError(txt_Specification, "");
                }
                #endregion

                #region 制造厂家
                if (t2.Manufacturer.Length > 200)
                {
                    dxErrorProvider1.SetError(txt_Manufacturer, "制造厂家字段长度超限, 最大字数不能超出200！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else
                {
                    dxErrorProvider1.SetError(txt_Manufacturer, "");
                }
                #endregion

                #region 出厂编号
                if (t2.SerialNumber.Length > 200)
                {
                    dxErrorProvider1.SetError(txt_SerialNumber, "出厂编号字段长度超限, 最大字数不能超出200！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else
                {
                    dxErrorProvider1.SetError(txt_SerialNumber, "");
                }
                #endregion

                #region 投产年月

                // 投产年月
                if (!string.IsNullOrWhiteSpace(txt_UsingDate.EditValue + ""))
                {
                    DateTime t;
                    if (DateTime.TryParse(txt_UsingDate.EditValue + "", out t))
                    {
                        DateTime CurrentDate = Convert.ToDateTime(ApiHelper.Instance.GetServiceTime());
                        if (t.Date > CurrentDate.Date)
                        {
                            dxErrorProvider1.SetError(txt_UsingDate, "投产年月字段不能超过当前时间！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                            return false;
                        }
                        else
                        {
                            dxErrorProvider1.SetError(txt_UsingDate, "");
                            t2.UsingDate = t.ToString("yyyy.MM.dd");
                        }
                    }
                }
                else
                {
                    dxErrorProvider1.SetError(txt_UsingDate, "投产年月字段的格式不正确！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }

                #endregion

                #region 设备类别
                if (t2.EquipmentCategory.Length > 20)
                {
                    dxErrorProvider1.SetError(txt_EquipmentCategory, "设备类别字段长度超限,最大字数不能超出20！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else
                {
                    dxErrorProvider1.SetError(txt_EquipmentCategory, "");
                }
                #endregion

                #region 质保期
                if (t2.WarrantyPeriod.Length > 50)
                {
                    dxErrorProvider1.SetError(txt_WarrantyPeriod, "质保期字段长度超限,最大字数不能超出50！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else
                {
                    dxErrorProvider1.SetError(txt_WarrantyPeriod, "");
                }
                #endregion

                #region 安装地点
                if (t2.InstallationLocation.Length > 200)
                {
                    dxErrorProvider1.SetError(txt_InstallationLocation, "安装地点字段长度超限,最大字数不能超出200！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else
                {
                    dxErrorProvider1.SetError(txt_InstallationLocation, "");
                }
                #endregion

                #region 所属单元
                if (t2.OwningUnit.Length > 200)
                {
                    dxErrorProvider1.SetError(txt_OwningUnit, "所属单元字段长度超限, 最大字数不能超出200！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else
                {
                    dxErrorProvider1.SetError(txt_OwningUnit, "");
                }
                #endregion

                #region 运行参数
                if (t2.OperatingParameters.Length > 200)
                {
                    dxErrorProvider1.SetError(txt_OperatingParameters, "运行参数字段长度超限, 最大字数不能超出200！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else
                {
                    dxErrorProvider1.SetError(txt_OperatingParameters, "");
                }
                #endregion

                #region 设备总容量

                if (t2.Totalcapacity < 0)
                {
                    dxErrorProvider1.SetError(txt_Totalcapacity, "设定值不能小于零！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else if (t2.Totalcapacity > 9999999999)
                {
                    dxErrorProvider1.SetError(txt_Totalcapacity, $"设定值不能超出最大值9999999999！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else
                {
                    dxErrorProvider1.SetError(txt_Totalcapacity, "");
                }

                #endregion

                #region 设备重量

                if (t2.Weight < 0)
                {
                    dxErrorProvider1.SetError(txt_Weight, "设定值不能小于零！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else if (t2.Weight > 9999999999)
                {
                    dxErrorProvider1.SetError(txt_Weight, $"设定值不能超出最大值9999999999！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else
                {
                    dxErrorProvider1.SetError(txt_Weight, "");
                }

                #endregion

                #region 设备原值

                if (t2.EquipmentOriginalvalue < 0)
                {
                    dxErrorProvider1.SetError(txt_EquipmentOriginalvalue, "设定值不能小于零！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                if (t2.EquipmentOriginalvalue > 9999999999)
                {
                    dxErrorProvider1.SetError(txt_EquipmentOriginalvalue, $"设定值不能超出最大值9999999999！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else
                {
                    dxErrorProvider1.SetError(txt_Weight, "");
                }

                #endregion

                #region 备注
                if (t2.Remarks.Length > 2000)
                {
                    dxErrorProvider1.SetError(txt_Remarks, "备注字段长度超限,最大字数不能超出2000！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else
                {
                    dxErrorProvider1.SetError(txt_Remarks, "");
                }
                #endregion

                CurrentModel = t2;
                return true;
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
                return false;
            }
        }
    }
}