using DevExpress.XtraBars.ToolbarForm;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.DXErrorProvider;
using DeviceRepair.Models;
using DeviceRepairAndOptimization.Biz;
using DeviceRepairAndOptimization.Common;
using System;
using System.Collections.Generic;

namespace DeviceRepairAndOptimization.Pages.CustomField
{
    public partial class pageFieldEdit : ToolbarForm
    {
        /// <summary>
        /// 窗体标题
        /// </summary>
        private string _Caption = "";
        public string Caption
        {
            get { return _Caption; }
            set { _Caption = value; Text = value; }
        }

        /// <summary>
        /// 编码
        /// </summary>
        public string FieldCode = string.Empty;

        /// <summary>
        /// 当前字段对象
        /// </summary>
        private FieldsInfo CurrentEntity = null;

        /// <summary>
        /// 字段显示值
        /// </summary>
        private string FieldText
        {
            get { return txt_FieldText.Text.Trim(); }
            set { txt_FieldText.Text = value; }
        }

        /// <summary>
        /// 字段值
        /// </summary>
        private string FieldValue
        {
            get { return txt_FieldValue.Text.Trim(); }
            set { txt_FieldValue.Text = value; }
        }

        /// <summary>
        /// 字段值类型
        /// </summary>
        private string FieldType
        {
            get { return lup_FieldType.EditValue + ""; }
            set { lup_FieldType.EditValue = value; }
        }

        public string ErrorMsg = "操作失败！";


        public pageFieldEdit(string Code, FieldsInfo entity = null)
        {
            InitializeComponent();

            lup_FieldType.Properties.Columns.Clear();
            lup_FieldType.Properties.DataSource = FieldsTypeCollect;//绑定数据源
            lup_FieldType.Properties.DisplayMember = "Name";    //=>要显示的字段名 
            lup_FieldType.Properties.ValueMember = "TypeValue";//=>获取或设置值的字段名 
            lup_FieldType.Properties.Columns.AddRange(new LookUpColumnInfo[] { new LookUpColumnInfo { Caption = "字段值类型", FieldName = "Name" } });//增加列
            lup_FieldType.Properties.BestFitMode = BestFitMode.BestFit;//列宽自适应 
            lup_FieldType.Properties.NullText = "请选择"; //value为null是显示"请选择"
            lup_FieldType.EditValue = "NVarChar";

            // 验证控件初始化
            InitializeValidationProvider();

            FieldCode = Code;
            if (entity != null)
            {
                CurrentEntity = entity;
                Caption = "编辑";

                FieldText = entity.FieldText;
                FieldType = entity.FieldType;
                FieldValue = entity.FieldValue;
                btn_Save.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                btn_SaveAndClose.Caption = "保存";
            }
            else
            {
                Caption = "新增";
            }

            this.Load += PageFieldEdit_Load;
        }

        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PageFieldEdit_Load(object sender, System.EventArgs e)
        {
            layoutControl1.AllowCustomization = false;

        }

        List<dynamic> _FieldsTypeCollect;
        public List<dynamic> FieldsTypeCollect
        {
            get
            {
                if (_FieldsTypeCollect == null)
                    _FieldsTypeCollect = new List<dynamic>() {
                    new { TypeValue = "NVarChar", Name = "文本值" },
                    new { TypeValue = "double", Name = "数值" },
                    new { TypeValue = "decimal", Name = "货币" }
                };
                return _FieldsTypeCollect;
            }
        }

        /// <summary>
        /// 初始化验证控件
        /// </summary>
        private void InitializeValidationProvider()
        {
            try
            {
                //实例化一个必填规则，错误提示为：该字段不能为空
                ConditionValidationRule required = new ConditionValidationRule("RequiredRule", ConditionOperator.IsNotBlank) { ErrorText = $"字段不能为空！" };

                BaseEdit[] param = new BaseEdit[] { txt_FieldText, txt_FieldValue };
                for (int i = 0; i < param.Length; i++)
                {
                    dxValidationProvider1.SetValidationRule(param[i], required);
                    dxValidationProvider1.SetIconAlignment(param[i], System.Windows.Forms.ErrorIconAlignment.MiddleRight);
                }
            }
            catch (Exception ex)
            {
                ErrorMsg = ex.Message;
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Save_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (dxValidationProvider1.Validate())
                {
                    splashScreenManager1.ShowWaitForm();
                    APIResponseData apiResponseData = null;

                    bool hasWhiteSpace = false;
                    if (string.IsNullOrWhiteSpace(FieldText))
                    {
                        dxErrorProvider1.SetIconAlignment(txt_FieldText, System.Windows.Forms.ErrorIconAlignment.MiddleRight);
                        dxErrorProvider1.SetError(txt_FieldText, "字段不能为空！", ErrorType.Critical);
                        hasWhiteSpace = true;
                    }

                    if (string.IsNullOrWhiteSpace(FieldValue))
                    {
                        dxErrorProvider1.SetIconAlignment(txt_FieldValue, System.Windows.Forms.ErrorIconAlignment.MiddleRight);
                        dxErrorProvider1.SetError(txt_FieldValue, "字段不能为空！", ErrorType.Critical);
                        hasWhiteSpace = true;
                    }


                    if (FieldType == "double")
                    {
                        double val = 0;
                        if (!double.TryParse(FieldValue, out val))
                        {
                            dxErrorProvider1.SetIconAlignment(txt_FieldValue, System.Windows.Forms.ErrorIconAlignment.MiddleRight);
                            dxErrorProvider1.SetError(txt_FieldValue, "输入的值不正确！", ErrorType.Critical);
                            hasWhiteSpace = true;
                        }
                    }
                    else if (FieldType == "decimal")
                    {
                        decimal val = 0;
                        if (!decimal.TryParse(FieldValue, out val))
                        {
                            dxErrorProvider1.SetIconAlignment(txt_FieldValue, System.Windows.Forms.ErrorIconAlignment.MiddleRight);
                            dxErrorProvider1.SetError(txt_FieldValue, "输入的值不正确！", ErrorType.Critical);
                            hasWhiteSpace = true;
                        }
                    }

                    if (hasWhiteSpace)
                    {
                        splashScreenManager1.TryCloseWait();
                        return;
                    }

                    // 校验Text是否存在
                    apiResponseData = FieldsManager.Instance.Exists(FieldCode, FieldText);
                    if (!apiResponseData.IsSuccess)
                        throw new Exception(apiResponseData.Message);

                    if (apiResponseData.ToInt() > 0)
                    {
                        dxErrorProvider1.SetIconAlignment(txt_FieldText, System.Windows.Forms.ErrorIconAlignment.MiddleRight);
                        dxErrorProvider1.SetError(txt_FieldText, "字段名称重复！", ErrorType.Warning);
                        splashScreenManager1.TryCloseWait();
                        return;
                    }

                    FieldsInfo f = new FieldsInfo
                    {
                        FieldCode = FieldCode,
                        FieldText = FieldText,
                        FieldValue = FieldValue,
                        FieldType = FieldType,
                    };

                    apiResponseData = FieldsManager.Instance.InsertOrEdit(f);
                    if (!apiResponseData.IsSuccess)
                        throw new Exception(apiResponseData.Message);

                    splashScreenManager1.TryCloseWait();
                    XtraMessageBoxHelper.Info("操作成功！");
                }
                else
                {
                    XtraMessageBoxHelper.Info("校验失败！");
                }
                splashScreenManager1.TryCloseWait();
            }
            catch (Exception ex)
            {
                ErrorMsg = ex.Message;
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 保存并且关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_SaveAndClose_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (dxValidationProvider1.Validate())
                {
                    splashScreenManager1.ShowWaitForm();
                    APIResponseData apiResponseData = null;

                    bool hasWhiteSpace = false;
                    if (string.IsNullOrWhiteSpace(FieldText))
                    {
                        dxErrorProvider1.SetIconAlignment(txt_FieldText, System.Windows.Forms.ErrorIconAlignment.MiddleRight);
                        dxErrorProvider1.SetError(txt_FieldText, "字段不能为空！", ErrorType.Critical);
                        hasWhiteSpace = true;
                    }

                    if (string.IsNullOrWhiteSpace(FieldValue))
                    {
                        dxErrorProvider1.SetIconAlignment(txt_FieldValue, System.Windows.Forms.ErrorIconAlignment.MiddleRight);
                        dxErrorProvider1.SetError(txt_FieldValue, "字段不能为空！", ErrorType.Critical);
                        hasWhiteSpace = true;
                    }

                    if (FieldType == "double")
                    {
                        double val = 0;
                        if (!double.TryParse(FieldValue, out val))
                        {
                            dxErrorProvider1.SetIconAlignment(txt_FieldValue, System.Windows.Forms.ErrorIconAlignment.MiddleRight);
                            dxErrorProvider1.SetError(txt_FieldValue, "输入的值不正确！", ErrorType.Critical);
                            hasWhiteSpace = true;
                        }
                    }
                    else if (FieldType == "decimal")
                    {
                        decimal val = 0;
                        if (!decimal.TryParse(FieldValue, out val))
                        {
                            dxErrorProvider1.SetIconAlignment(txt_FieldValue, System.Windows.Forms.ErrorIconAlignment.MiddleRight);
                            dxErrorProvider1.SetError(txt_FieldValue, "输入的值不正确！", ErrorType.Critical);
                            hasWhiteSpace = true;
                        }
                    }

                    if (hasWhiteSpace)
                    {
                        splashScreenManager1.TryCloseWait();
                        return;
                    }

                    if (CurrentEntity == null || (CurrentEntity != null && !CurrentEntity.FieldText.Equals(FieldText, StringComparison.CurrentCultureIgnoreCase)))
                    {
                        // 校验Text是否存在
                        apiResponseData = FieldsManager.Instance.Exists(FieldCode, FieldText);
                        if (!apiResponseData.IsSuccess)
                            throw new Exception(apiResponseData.Message);

                        if (apiResponseData.ToInt() > 0)
                        {
                            dxErrorProvider1.SetIconAlignment(txt_FieldText, System.Windows.Forms.ErrorIconAlignment.MiddleRight);
                            dxErrorProvider1.SetError(txt_FieldText, "字段名称重复！", ErrorType.Warning);
                            splashScreenManager1.TryCloseWait();
                            return;
                        }
                    }

                    FieldsInfo f = CurrentEntity ?? new FieldsInfo();
                    f.FieldCode = FieldCode;
                    f.FieldText = FieldText;
                    f.FieldValue = FieldValue;
                    f.FieldType = FieldType;

                    apiResponseData = FieldsManager.Instance.InsertOrEdit(f);
                    if (!apiResponseData.IsSuccess)
                        throw new Exception(apiResponseData.Message);

                    splashScreenManager1.TryCloseWait();
                    XtraMessageBoxHelper.Info("操作成功！");
                    DialogResult = System.Windows.Forms.DialogResult.OK;
                }
                else
                {
                    XtraMessageBoxHelper.Info("校验失败！");
                }
                splashScreenManager1.TryCloseWait();
            }
            catch (Exception ex)
            {
                ErrorMsg = ex.Message;
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }


        private void lup_FieldType_Properties_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                string FieldType = ((ChangingEventArgs)e).NewValue + "";

                switch (FieldType)
                {
                    case "NVarChar":
                        txt_FieldValue.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.None;
                        txt_FieldValue.Properties.ResetMaskSettings();
                        txt_FieldValue.Properties.NullValuePromptShowForEmptyValue = true;
                        txt_FieldValue.Properties.NullValuePrompt = "请输入文本值";
                        txt_FieldValue.ToolTip = "请输入文本值";
                        break;
                    case "double":
                        txt_FieldValue.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.RegEx;
                        txt_FieldValue.Properties.Mask.IgnoreMaskBlank = true;
                        txt_FieldValue.Properties.Mask.AutoComplete = DevExpress.XtraEditors.Mask.AutoCompleteType.None;
                        txt_FieldValue.Properties.Mask.EditMask = @"-?(\d|[1-9]\d*)(\.\d+)?";
                        txt_FieldValue.Properties.NullValuePromptShowForEmptyValue = true;
                        txt_FieldValue.Properties.NullValuePrompt = "请输入数字";
                        txt_FieldValue.ToolTip = "请输入数字";
                        break;
                    case "decimal":
                        txt_FieldValue.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.RegEx;
                        txt_FieldValue.Properties.Mask.IgnoreMaskBlank = true;
                        txt_FieldValue.Properties.Mask.AutoComplete = DevExpress.XtraEditors.Mask.AutoCompleteType.None;
                        txt_FieldValue.Properties.Mask.EditMask = @"-?(\d|[1-9]\d*)(\.\d+)?";
                        txt_FieldValue.Properties.NullValuePromptShowForEmptyValue = true;
                        txt_FieldValue.Properties.NullValuePrompt = "请输入货币数值";
                        txt_FieldValue.ToolTip = "请输入货币数值";
                        break;
                    default:
                        break;
                }

                txt_FieldValue.EditValue = "";
                txt_FieldValue.Text = "";
            }
            catch (Exception ex)
            {
                ErrorMsg = ex.Message;
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }
    }
}