using DevExpress.XtraBars.ToolbarForm;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.DXErrorProvider;
using DeviceRepair.Models;
using DeviceRepairAndOptimization.Biz;
using DeviceRepairAndOptimization.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;

namespace DeviceRepairAndOptimization.Pages.Maintain
{
    public partial class pageMaintainEdit : ToolbarForm
    {
        public DeviceWarrantyRequestFormView CurrentRequestForm = null;
        public List<DeviceWarrantyRequestAccessoriesInfo> Accessories = null;

        /// <summary>
        /// 现象区分
        /// </summary>
        int SymptomlDistinction
        {
            get { return Convert.ToInt32(ddlSymptomlDistinction.EditValue); }
        }

        /// <summary>
        /// 维修方式
        /// </summary>
        int Maintenance
        {
            get { return Convert.ToInt32(ddlMaintenance.EditValue); }
        }

        /// <summary>
        /// 开始时间
        /// </summary>
        DateTime StartTime
        {
            get { return Convert.ToDateTime(de_StartDate.EditValue); }
        }

        /// <summary>
        /// 结束时间
        /// </summary>
        DateTime EndTime
        {
            get { return Convert.ToDateTime(de_EndDate.EditValue); }
        }

        /// <summary>
        /// 故障原因
        /// </summary>
        string MaintainCause
        {
            get { return txtCause.EditValue?.ToString()?.Trim(); }
        }

        /// <summary>
        /// 维修内容
        /// </summary>
        string MaintainContent
        {
            get { return txtContent.EditValue?.ToString()?.Trim(); }
        }

        /// <summary>
        /// 是否需要验证
        /// </summary>
        bool NeedValidate
        {

            get { return (bool)ckbNeedValidate.EditValue; }
        }

        /// <summary>
        /// 二次验证的理由
        /// </summary>
        string MaintaionReason
        {
            get { return txtReason.EditValue?.ToString()?.Trim() ?? ""; }
        }

        /// <summary>
        /// 验证编号
        /// </summary>
        string ValidateNo
        {
            get { return txtNo.EditValue?.ToString()?.Trim() ?? ""; }
        }

        /// <summary>
        /// 是否停机（停机状态）
        /// </summary>
        bool IsDown
        {
            get { return (bool)ckbIsDown.EditValue; }
        }

        public pageMaintainEdit(DeviceWarrantyRequestFormView qequestForm)
        {
            InitializeComponent();

            CurrentRequestForm = qequestForm;
            this.Load += PageMaintainEdit_Load;
        }

        private void PageMaintainEdit_Load(object sender, EventArgs e)
        {
            InitializeLookupControl();

            try
            {
                layoutControlItem9.Enabled = !NeedValidate;
                layoutControlItem10.Enabled = NeedValidate;

                de_StartDate.EditValue = CurrentRequestForm.CreatOn.Value;
                de_EndDate.EditValue = DateTime.Now;

                if (CurrentRequestForm != null && CurrentRequestForm.MaintaionItems != null)
                {
                    // 现象区分
                    ddlSymptomlDistinction.EditValue = CurrentRequestForm.MaintaionItems.SymptomlDistinction;

                    // 维修方式
                    ddlMaintenance.EditValue = CurrentRequestForm.MaintaionItems.Maintenance;

                    // 开始时间
                    de_StartDate.EditValue = CurrentRequestForm.MaintaionItems.MaintainStartTime;

                    // 结束时间
                    de_EndDate.EditValue = CurrentRequestForm.MaintaionItems.MaintainEndTime;

                    // 故障原因
                    txtCause.EditValue = CurrentRequestForm.MaintaionItems.MaintainCause;

                    // 故障内容
                    txtContent.EditValue = CurrentRequestForm.MaintaionItems.MaintainContent;

                    // 配件
                    if (CurrentRequestForm.MaintaionItems.AccessoriesItems != null && CurrentRequestForm.MaintaionItems.AccessoriesItems.Count > 0)
                    {
                        Accessories = CurrentRequestForm.MaintaionItems.AccessoriesItems;
                        string[] AccessoriesLst = Accessories.Select(x => x.FieldName).ToArray();
                        txt_Accessories.EditValue = string.Join(";", AccessoriesLst);
                    }

                    // 是否需要再验证
                    ckbNeedValidate.EditValue = CurrentRequestForm.MaintaionItems.BeValidate;

                    // 理由
                    txtReason.EditValue = CurrentRequestForm.MaintaionItems.Reason ?? "";

                    // 验证编码
                    txtNo.EditValue = CurrentRequestForm.MaintaionItems.ValidateNo ?? "";

                    // 是否停机
                    ckbIsDown.EditValue = CurrentRequestForm.IsDown;
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        void InitializeLookupControl()
        {
            try
            {
                splashScreenManager1.ShowWaitForm();

                APIResponseData apiResponseData = FieldsManager.Instance.GetQuery("SymptomlDistinction,Maintenance");
                if (!apiResponseData.IsSuccess)
                    throw new Exception(apiResponseData.Message);

                List<FieldsInfo> SelectionDatas = apiResponseData.ToDeserializeObject<List<FieldsInfo>>();

                ddlSymptomlDistinction.Properties.DataSource = SelectionDatas.Where(x => x.FieldCode == "SymptomlDistinction" && x.Status).ToList();
                ddlSymptomlDistinction.Properties.DisplayMember = "FieldText";
                ddlSymptomlDistinction.Properties.ValueMember = "AutoID";
                ddlSymptomlDistinction.Properties.BestFitMode = DevExpress.XtraEditors.Controls.BestFitMode.BestFitResizePopup;
                if (ddlSymptomlDistinction.Properties.DataSource != null && (ddlSymptomlDistinction.Properties.DataSource as List<FieldsInfo>).Count > 0)
                {
                    ddlSymptomlDistinction.EditValue = (ddlSymptomlDistinction.Properties.DataSource as List<FieldsInfo>)[0].AutoID;
                }

                ddlMaintenance.Properties.DataSource = SelectionDatas.Where(x => x.FieldCode == "Maintenance" && x.Status).ToList();
                ddlMaintenance.Properties.DisplayMember = "FieldText";
                ddlMaintenance.Properties.ValueMember = "AutoID";
                ddlMaintenance.Properties.BestFitMode = DevExpress.XtraEditors.Controls.BestFitMode.BestFitResizePopup;
                if (ddlMaintenance.Properties.DataSource != null && (ddlMaintenance.Properties.DataSource as List<FieldsInfo>).Count > 0)
                {
                    ddlMaintenance.EditValue = (ddlMaintenance.Properties.DataSource as List<FieldsInfo>)[0].AutoID;
                }

                splashScreenManager1.TryCloseWait();
            }
            catch (Exception ex)
            {
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 初始化验证控件
        /// </summary>
        private void InitializeValidationProvider()
        {
            try
            {
                List<BaseEdit> param = new List<BaseEdit> { ddlSymptomlDistinction, ddlMaintenance, de_StartDate, de_EndDate, txtCause, txtContent };
                foreach (var item in param)
                {
                    dxValidationProvider1.RemoveControlError(item);
                }
                dxValidationProvider1.RemoveControlError(txtNo);
                dxValidationProvider1.RemoveControlError(txtReason);


                dxValidationProvider1 = new DXValidationProvider();

                //实例化一个必填规则，错误提示为：该字段不能为空
                ConditionValidationRule required = new ConditionValidationRule("RequiredRule", ConditionOperator.IsNotBlank) { ErrorText = $"字段不能为空" };

                if (NeedValidate)
                {
                    param.Add(txtNo);
                }
                else
                {
                    param.Add(txtReason);
                }

                for (int i = 0; i < param.Count; i++)
                {
                    string FieldName = Root.Items.FirstOrDefault(x => (x as DevExpress.XtraLayout.LayoutControlItem).Control == param[i])?.Text;


                    required.ErrorText = $"字段：{FieldName.Replace("：", "")} 不能为空";

                    dxValidationProvider1.SetValidationRule(param[i], required);
                    dxValidationProvider1.SetIconAlignment(param[i], ErrorIconAlignment.MiddleRight);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 配件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_AccessoriesEdit_Click(object sender, EventArgs e)
        {
            using (dlgAccessoriesEdit dlg = new dlgAccessoriesEdit(CurrentRequestForm?.MaintaionItems?.AccessoriesItems))
            {
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    Accessories = dlg.CurrentAccessories;
                    string[] AccessoriesLst = dlg.CurrentAccessories.Select(x => x.FieldName).ToArray();
                    txt_Accessories.EditValue = string.Join(";", AccessoriesLst);
                }
            }
        }

        private void ckbNeedValidate_SelectedIndexChanged(object sender, EventArgs e)
        {
            layoutControlItem9.Enabled = !NeedValidate;
            layoutControlItem10.Enabled = NeedValidate;

            if (NeedValidate)
            {
                txtNo.EditValue = "";
                txtReason.EditValue = "N/A";
            }
            else
            {
                txtReason.EditValue = "";
                txtNo.EditValue = "N/A";
            }
        }

        /// <summary>
        /// 关闭窗体前 先保存数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pageMaintainEdit_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (DialogResult == DialogResult.OK)
                return;

            try
            {
                DeviceWarrantyRequestMaintaionView Entity = new DeviceWarrantyRequestMaintaionView
                {
                    AccessoriesItems = Accessories,
                    BeValidate = NeedValidate,
                    FormID = CurrentRequestForm.AutoID,
                    MaintainCause = MaintainCause,
                    MaintainContent = MaintainContent,
                    MaintainStartTime = StartTime,
                    MaintainEndTime = EndTime,
                    Maintenance = Maintenance,
                    SymptomlDistinction = SymptomlDistinction,
                    Reason = MaintaionReason,
                    ValidateNo = ValidateNo,
                    IsSubmit = false
                };

                if (CurrentRequestForm.MaintaionItems != null)
                {
                    Entity.AutoID = CurrentRequestForm.MaintaionItems.AutoID;
                }

                APIResponseData apiResponseData = MaintenanceManager.Instance.DeviceMaintion(Entity);
                if (!apiResponseData.IsSuccess)
                    throw new Exception(apiResponseData.Message);
            }
            catch (Exception ex)
            {

                throw;
            }
        }

        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                InitializeValidationProvider();
                if (dxValidationProvider1.Validate())
                {
                    if (StartTime > EndTime)
                    {
                        throw new Exception($"修理结束时间在修理开始时间之后！");
                    }

                    DeviceWarrantyRequestMaintaionView Entity = new DeviceWarrantyRequestMaintaionView
                    {
                        AccessoriesItems = Accessories,
                        BeValidate = NeedValidate,
                        FormID = CurrentRequestForm.AutoID,
                        MaintainCause = MaintainCause,
                        MaintainContent = MaintainContent,
                        MaintainStartTime = StartTime,
                        MaintainEndTime = EndTime,
                        Maintenance = Maintenance,
                        SymptomlDistinction = SymptomlDistinction,
                        Reason = MaintaionReason,
                        ValidateNo = ValidateNo,
                        IsSubmit = true
                    };

                    if (CurrentRequestForm.MaintaionItems != null)
                    {
                        Entity.AutoID = CurrentRequestForm.MaintaionItems.AutoID;
                    }

                    APIResponseData apiResponseData = MaintenanceManager.Instance.DeviceMaintion(Entity);
                    if (!apiResponseData.IsSuccess)
                        throw new Exception(apiResponseData.Message);

                    this.DialogResult = DialogResult.OK;

                    //List<DeviceWarrantyRequestForm> lst = apiResponseData.ToDeserializeObject<List<DeviceWarrantyRequestForm>>();

                    //string info = Newtonsoft.Json.JsonConvert.SerializeObject(Entity);
                    //XtraMessageBoxHelper.Info(info);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }
    }
}