using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraSplashScreen;
using DeviceRepair.Models;
using DeviceRepairAndOptimization.Biz;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Windows.Forms;
using DeviceRepairAndOptimization.Common;

namespace DeviceRepairAndOptimization.Pages.Plan
{
    public partial class page_PlanEdit : Form
    {
        private AnnualMaintenancePlan DataSource;

        private string OperationType = "修改";

        List<ComboBoxEdit> controlLst = new List<ComboBoxEdit>();

        public page_PlanEdit(AnnualMaintenancePlan view)
        {
            InitializeComponent();
            controlLst = GetControlsInfo(this);

            if (string.IsNullOrWhiteSpace(view.DisplayEquipmentID))
            {
                OperationType = "新增";
                DataSource = new AnnualMaintenancePlan();
                txt_EquipmentID.ReadOnly = false;
                txt_DeviceName.ReadOnly = true;
                tp_StartMonth.Value = DateTime.Today;
            }
            else
            {
                APIResponseData r = PlanManager.Instance.GetPlanRecordProgress(view.EquipmentID, view.MaintenanceYear);
                if (r.IsSuccess)
                {
                    List<PlanProgress> progList = r.ToDeserializeObject<List<PlanProgress>>();
                    if (progList != null && progList.Count > 0)
                    {

                        foreach (PlanProgress item in progList)
                        {
                            Control con = controlLst.FirstOrDefault(x => string.Equals(x.Properties.Tag + "", item.PlanMonth + ""));
                            if (con != null)
                                con.Enabled = false;
                        }
                    }
                }
            }

            DataSource = view;
        }

        /// <summary>
        /// 历遍指定窗体类的所有控件
        /// </summary>
        /// <param name="AllControl">窗体类控件集合</param>
        private List<ComboBoxEdit> GetControlsInfo(Control AllControl)
        {
            List<ComboBoxEdit> cbe = new List<ComboBoxEdit>();
            foreach (Control con in AllControl.Controls)
            {
                //如果查找到的控件数量大于0,则说明是容器控件,需要将容器作为控件集合进行递归查找
                if (con.Controls.Count > 0)
                {
                    cbe.AddRange(GetControlsInfo(con));//针对容器控 件递归查找 (自己调用自己)
                }

                //根据对应的控件类型进行相应的数据提取操作
                if (con is ComboBoxEdit)
                    cbe.Add((ComboBoxEdit)con);
            }
            return cbe;
        }

        void DataBind()
        {
            foreach (EditorButton item in txt_EquipmentID.Properties.Buttons)
            {
                item.Enabled = false;
            }
            txt_EquipmentID.Text = DataSource.DisplayEquipmentID;
            txt_DeviceName.Text = DataSource.EquipmentName;
            ck_Jan.SelectedItem = DataSource.Jan;
            ck_Feb.SelectedItem = DataSource.Feb;
            ck_Mar.SelectedItem = DataSource.Mar;
            ck_Apr.SelectedItem = DataSource.Apr;
            ck_May.SelectedItem = DataSource.May;
            ck_Jun.SelectedItem = DataSource.Jun;
            ck_Jul.SelectedItem = DataSource.Jul;
            ck_Aug.SelectedItem = DataSource.Aug;
            ck_Sep.SelectedItem = DataSource.Sep;
            ck_Oct.SelectedItem = DataSource.Oct;
            ck_Nov.SelectedItem = DataSource.Nov;
            ck_Dec.SelectedItem = DataSource.Dec;
            tp_StartMonth.Value = Convert.ToDateTime(DataSource.PMStartMonth);
            txt_Remark.Text = DataSource.Remarks;
        }

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

        private void btn_Submit_Click(object sender, EventArgs e)
        {
            try
            {
                if (ValidateData())
                {
                    if (txt_Remark.Text.Length > 2000)
                    {
                        XtraMessageBoxHelper.Error($"备注信息过长，请勿超过2000字！");
                        return;
                    }

                    SplashScreenManager.ShowDefaultWaitForm("数据正在提交", "请稍等...");

                    #region 实体创建
                    List<DriveMaintencePlanInfo> lst2 = new List<DriveMaintencePlanInfo>();
                    foreach (ComboBoxEdit item in controlLst)
                    {
                        if (!item.Enabled)
                            continue;
                        DriveMaintencePlanInfo planItem = new DriveMaintencePlanInfo();
                        planItem.Remarks = txt_Remark.Text;
                        planItem.EquipmentID = DataSource.EquipmentID;
                        planItem.MaintenanceMonth = (int)item.Properties.Tag;
                        planItem.MaintenanceType = item.SelectedItem + "";
                        planItem.MaintenanceYear = DataSource.MaintenanceYear;
                        planItem.PMStartMonth = tp_StartMonth.Value;
                        lst2.Add(planItem);
                    }

                    #endregion

                    APIResponseData apiResponseData = PlanManager.Instance.InsertDatas(lst2);
                    if (apiResponseData.IsSuccess)
                    {
                        // 关闭等待窗口
                        SplashScreenManager.CloseDefaultWaitForm();
                        DialogResult = DialogResult.OK;
                        return;
                    }
                    // 关闭等待窗口
                    SplashScreenManager.CloseDefaultWaitForm();
                }
                else
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.DialogResult = DialogResult.Abort;
            }
            this.DialogResult = DialogResult.OK;
        }

        private void page_PlanEdit_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(DataSource.DisplayEquipmentID))
                DataBind();
        }

        private void txt_EquipmentID_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (e.Button.Caption.Equals("确定"))
            {
                QueryEquipmentData();
            }
            else
            {
                txt_EquipmentID.ReadOnly = false;
                txt_EquipmentID.Text = "";
                txt_DeviceName.Text = "";
            }
        }

        private void txt_EquipmentID_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                QueryEquipmentData();
            }
        }

        void QueryEquipmentData()
        {
            if (!string.IsNullOrEmpty(txt_EquipmentID.Text))
            {
                splashScreenManager1.ShowWaitForm();

                try
                {
                    APIResponseData apiResponseData = DeviceManager.Instance.GetModelByEquipmentID(txt_EquipmentID.Text.Trim());
                    if (!apiResponseData.IsSuccess)
                        throw new Exception(apiResponseData.Message);
                    DeviceInformationInfo dim = apiResponseData.ToDeserializeObject<DeviceInformationInfo>();
                    if (dim == null)
                    {
                        string eid = txt_EquipmentID.Text;
                        txt_EquipmentID.Text = "";
                        txt_DeviceName.Text = "";
                        splashScreenManager1.TryCloseWait();
                        XtraMessageBoxHelper.Warn($"当前设备编号:{eid}不存在！");
                        return;
                    }
                    else
                    {
                        AnnualMaintenancePlan vp = PlanManager.Instance.GetPlanByEquipmentPkAndYear(DataSource.MaintenanceYear, dim.AutoID);
                        if (vp != null)
                        {
                            splashScreenManager1.TryCloseWait();
                            if (XtraMessageBox.Show($"当前年度下设备编号:{dim.EquipmentID}的设备已经存在计划,是否转到编辑？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == DialogResult.Yes)
                            {
                                DataSource = vp;
                                txt_EquipmentID.Enabled = false;
                                DataBind();
                                return;
                            }
                            else
                            {
                                txt_EquipmentID.ReadOnly = false;
                                txt_EquipmentID.Text = "";
                                txt_DeviceName.Text = "";
                                return;
                            }
                        }

                        txt_EquipmentID.Text = dim.EquipmentID;
                        txt_DeviceName.Text = dim.EquipmentName;
                        DataSource.DisplayEquipmentID = dim.EquipmentID;
                        DataSource.EquipmentID = dim.AutoID;
                        DataSource.EquipmentName = dim.EquipmentName;
                        txt_EquipmentID.ReadOnly = true;
                        ck_Jan.Focus();
                    }
                }
                catch (Exception ex)
                {
                    splashScreenManager1.TryCloseWait();
                    XtraMessageBoxHelper.Error(ex.Message);
                }
                splashScreenManager1.TryCloseWait();
            }
        }

        private bool ValidateData()
        {
            try
            {
                if (string.IsNullOrWhiteSpace(DataSource.DisplayEquipmentID) || string.IsNullOrWhiteSpace(DataSource.EquipmentName))
                {
                    dxErrorProvider1.SetError(txt_EquipmentID, "设备信息不允许为空！");
                    return false;
                }
                else
                {
                    dxErrorProvider1.SetError(txt_EquipmentID, "");
                }





                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}
