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

namespace DeviceRepairAndOptimization.Pages.AM.Plan
{
    public partial class pageDevicePlanEdit : ToolbarForm
    {
        AnnualMaintenancePlan CurrentModel;

        string EquipmentID { get { return txt_EquipmentID.EditValue + ""; } }

        List<ComboBoxEdit> controlLst = null;

        public pageDevicePlanEdit(AnnualMaintenancePlan annualMaintenancePlan = null)
        {
            InitializeComponent();

            controlLst = new List<ComboBoxEdit>
            {
                cb_Jan,cb_Feb,cb_Mar,cb_Apr,cb_May,cb_Jun,cb_Jul,cb_Aug,cb_Sep,cb_Oct,cb_Nov,cb_Dec
            };

            // 修改模式，赋传入对象值到变量
            if (annualMaintenancePlan != null)
            {
                CurrentModel = annualMaintenancePlan;

            }

            // 新增模式，赋值当前日期到PM起始月份
            if (annualMaintenancePlan == null)
                de_PmStartDate.EditValue = DateTime.Today;
        }

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

            if (CurrentModel.CreatUser != 0)
            {
                txt_EquipmentID.Enabled = false;
                foreach (EditorButton item in txt_EquipmentID.Properties.Buttons)
                {
                    item.Enabled = false;
                }
                txt_EquipmentID.EditValue = CurrentModel.DisplayEquipmentID;
                txt_DeviceName.EditValue = CurrentModel.EquipmentName;

                InitializeControl();
            }
        }

        void InitializeControl()
        {
            APIResponseData r = PlanManager.Instance.GetPlanRecordProgress(CurrentModel.EquipmentID, CurrentModel.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;
                    }
                }
            }

            cb_Jan.SelectedItem = CurrentModel.Jan;
            cb_Feb.SelectedItem = CurrentModel.Feb;
            cb_Mar.SelectedItem = CurrentModel.Mar;
            cb_Apr.SelectedItem = CurrentModel.Apr;
            cb_May.SelectedItem = CurrentModel.May;
            cb_Jun.SelectedItem = CurrentModel.Jun;
            cb_Jul.SelectedItem = CurrentModel.Jul;
            cb_Aug.SelectedItem = CurrentModel.Aug;
            cb_Sep.SelectedItem = CurrentModel.Sep;
            cb_Oct.SelectedItem = CurrentModel.Oct;
            cb_Nov.SelectedItem = CurrentModel.Nov;
            cb_Dec.SelectedItem = CurrentModel.Dec;
            DateTime p;
            if (DateTime.TryParse(CurrentModel.PMStartMonth, out p))
                de_PmStartDate.EditValue = p;
            mm_Remark.EditValue = CurrentModel.Remarks;
        }

        /// <summary>
        /// 设备编号处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txt_EquipmentID_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                if (e.Button.Caption == "清空")
                {
                    txt_EquipmentID.EditValue = "";
                    txt_DeviceName.EditValue = "";
                    txt_EquipmentID.ReadOnly = false;
                }
                else
                {
                    APIResponseData apiResponseData = Biz.DeviceManager.Instance.GetModelByEquipmentID(EquipmentID);
                    if (!apiResponseData.IsSuccess)
                        throw new Exception(apiResponseData.Message);

                    DeviceInformationInfo CurrentDevice = apiResponseData.ToDeserializeObject<DeviceInformationInfo>();
                    if (CurrentDevice == null)
                        throw new Exception($"设备【{EquipmentID}】在台账中不存在或不符合要求，请检查！");

                    AnnualMaintenancePlan vp = Biz.PlanManager.Instance.GetPlanByEquipmentPkAndYear(CurrentModel?.MaintenanceYear ?? DateTime.Now.Year, CurrentDevice.AutoID);
                    if (vp != null)
                    {
                        if (XtraMessageBox.Show($"当前年度下设备编号:{CurrentDevice.EquipmentID}的设备已经存在计划,是否转到编辑？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == DialogResult.Yes)
                        {
                            CurrentModel = vp;
                            txt_EquipmentID.ReadOnly = false;
                            InitializeControl();
                            return;
                        }
                        else
                        {
                            txt_EquipmentID.ReadOnly = false;
                            txt_EquipmentID.Text = "";
                            txt_DeviceName.Text = "";
                            return;
                        }
                    }

                    txt_EquipmentID.ReadOnly = true;
                    txt_EquipmentID.EditValue = CurrentDevice.EquipmentID;
                    txt_DeviceName.EditValue = CurrentDevice.EquipmentName;

                    if (CurrentModel == null)
                        CurrentModel = new AnnualMaintenancePlan();
                    CurrentModel.EquipmentID = CurrentDevice.AutoID;
                    CurrentModel.DisplayEquipmentID = CurrentDevice.EquipmentID;
                    CurrentModel.EquipmentName = CurrentDevice.EquipmentName;
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 查找设备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txt_EquipmentID_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                try
                {
                    if (!string.IsNullOrWhiteSpace(EquipmentID))
                    {

                        APIResponseData apiResponseData = Biz.DeviceManager.Instance.GetModelByEquipmentID(EquipmentID);
                        if (!apiResponseData.IsSuccess)
                            throw new Exception(apiResponseData.Message);

                        DeviceInformationInfo CurrentDevice = apiResponseData.ToDeserializeObject<DeviceInformationInfo>();
                        if (CurrentDevice == null)
                            throw new Exception($"设备【{EquipmentID}】在台账中不存在或不符合要求，请检查！");

                        AnnualMaintenancePlan vp = Biz.PlanManager.Instance.GetPlanByEquipmentPkAndYear(CurrentModel?.MaintenanceYear ?? DateTime.Now.Year, CurrentDevice.AutoID);
                        if (vp != null)
                        {
                            if (XtraMessageBox.Show($"当前年度下设备编号:{CurrentDevice.EquipmentID}的设备已经存在计划,是否转到编辑？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == DialogResult.Yes)
                            {
                                CurrentModel = vp;
                                txt_EquipmentID.ReadOnly = false;
                                InitializeControl();
                                return;
                            }
                            else
                            {
                                txt_EquipmentID.ReadOnly = false;
                                txt_EquipmentID.Text = "";
                                txt_DeviceName.Text = "";
                                return;
                            }
                        }

                        txt_EquipmentID.ReadOnly = true;
                        txt_EquipmentID.EditValue = CurrentDevice.EquipmentID;
                        txt_DeviceName.EditValue = CurrentDevice.EquipmentName;

                        if (CurrentModel == null)
                            CurrentModel = new AnnualMaintenancePlan();
                        CurrentModel.EquipmentID = CurrentDevice.AutoID;
                        CurrentModel.DisplayEquipmentID = CurrentDevice.EquipmentID;
                        CurrentModel.EquipmentName = CurrentDevice.EquipmentName;
                    }
                }
                catch (Exception ex)
                {
                    XtraMessageBoxHelper.Error(ex.Message);
                }
            }
        }

        /// <summary>
        /// 查找设备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txt_EquipmentID_Properties_KeyPress(object sender, KeyPressEventArgs e)
        {
            //增加了自动切换大写，控制只能输入大写字母、数字、回退按钮、复制快捷键(复制的数据没有控制格式)
            e.KeyChar = Convert.ToChar(e.KeyChar.ToString().ToUpper());
        }

        /// <summary>
        /// 数据新增 / 修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (ValidateData())
                {
                    string Description = mm_Remark.EditValue + "";
                    if (Description.Length > 2000)
                        throw new Exception($"备注信息过长，请勿超过2000字！");

                    splashScreenManager1.ShowWaitForm();

                    #region 实体创建

                    List<DriveMaintencePlanInfo> lst2 = new List<DriveMaintencePlanInfo>();
                    foreach (ComboBoxEdit item in controlLst)
                    {
                        if (!item.Enabled)
                            continue;
                        DriveMaintencePlanInfo planItem = new DriveMaintencePlanInfo();
                        planItem.Remarks = Description;
                        planItem.EquipmentID = CurrentModel.EquipmentID;
                        planItem.MaintenanceMonth = (int)item.Properties.Tag;
                        planItem.MaintenanceType = item.SelectedItem + "";
                        planItem.MaintenanceYear = CurrentModel.MaintenanceYear;

                        if (!string.IsNullOrWhiteSpace(de_PmStartDate.EditValue + ""))
                            planItem.PMStartMonth = Convert.ToDateTime(de_PmStartDate.EditValue);
                        lst2.Add(planItem);
                    }

                    #endregion

                    APIResponseData apiResponseData = PlanManager.Instance.InsertDatas(lst2);
                    if (!apiResponseData.IsSuccess)
                        throw new Exception(apiResponseData.Message);

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

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

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