using DevExpress.XtraBars.ToolbarForm;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DeviceRepair.Models;
using DeviceRepair.Models.Enum;
using DeviceRepair.Models.Plan.View;
using DeviceRepair.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using TsSFCDevice.Client.Biz.Base.Utils;
using TsSFCDevice.Client.Biz.Impl;
using TsSFCDevice.Client.Launch.Plan.AM;

namespace TsSFCDevice.Client.Launch.Plan
{
    public partial class pageDevicePlanEdit : ToolbarForm
    {
        AnnualMaintenancePlan CurrentModel;

        private EnumDeviceBelong Belong = EnumDeviceBelong.PM;

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

        List<ComboBoxEdit> controlLst = null;

        public pageDevicePlanEdit() : this(EnumDeviceBelong.PM, null)
        {

        }

        public pageDevicePlanEdit(EnumDeviceBelong belong, AnnualMaintenancePlan annualMaintenancePlan = null)
        {
            InitializeComponent();
            Belong = belong;
            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
            };

            controlLst.ForEach(control =>
            {
                control.Properties.Items.Clear();
                control.Properties.Items.Add("");
                if (belong == EnumDeviceBelong.AM)
                {
                    control.Properties.Items.Add("Daily");
                    control.Properties.Items.Add("Monthly");
                }
                else if (belong == EnumDeviceBelong.PM)
                {
                    control.Properties.Items.Add("Monthly");
                    control.Properties.Items.Add("Quarterly");
                    control.Properties.Items.Add("Semi-an");
                    control.Properties.Items.Add("Annual");
                }
            });

            // 修改模式，赋传入对象值到变量
            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 ClearControl()
        {
            try
            {
                cb_Jan.SelectedItem = "";
                cb_Feb.SelectedItem = "";
                cb_Mar.SelectedItem = "";
                cb_Apr.SelectedItem = "";
                cb_May.SelectedItem = "";
                cb_Jun.SelectedItem = "";
                cb_Jul.SelectedItem = "";
                cb_Aug.SelectedItem = "";
                cb_Sep.SelectedItem = "";
                cb_Oct.SelectedItem = "";
                cb_Nov.SelectedItem = "";
                cb_Dec.SelectedItem = "";
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
                this.DialogResult = DialogResult.Abort;
            }
        }


        void InitializeControl()
        {
            try
            {
                IList<View_PM_Plan_ProgressInfo> ProgList;
                if (Belong == EnumDeviceBelong.PM)
                {
                    ProgList = PlanRepository.Instance.Get_PM_PLAN_ProgressInfo(CurrentModel.EquipmentID, CurrentModel.MaintenanceYear);
                }
                else
                {
                    ProgList = PlanRepository.Instance.Get_AM_PLAN_ProgressInfo(CurrentModel.EquipmentID, CurrentModel.MaintenanceYear);
                }

                if (ProgList != null && ProgList.Count > 0)
                {
                    ProgList.ToList().ForEach(item =>
                    {
                        if (item.RecordAutoID > 0)
                        {
                            System.Windows.Forms.Control con = controlLst.FirstOrDefault(x => string.Equals(x.Properties.Tag + "", item.PlanMonth + ""));
                            if (con != null)
                                con.Enabled = false;
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
                this.DialogResult = DialogResult.Abort;
            }

            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, ButtonPressedEventArgs e)
        {
            try
            {
                if (e.Button.Caption == "清空")
                {
                    txt_EquipmentID.EditValue = "";
                    txt_DeviceName.EditValue = "";
                    txt_EquipmentID.ReadOnly = false;
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(EquipmentID))
                        throw new ArgumentException($"设备编号不可为空！");

                    DeviceInformationInfo CurrentDevice = Utility.SystemRuntimeInfo.CurrentDeviceCaches.FirstOrDefault(x => x.EquipmentID.Equals(EquipmentID, StringComparison.CurrentCultureIgnoreCase));
                    if (CurrentDevice == null)
                        throw new ArgumentException($"设备【{EquipmentID}】在台账中不存在或不符合要求，请检查！");

                    AnnualMaintenancePlan vp = PlanRepository.Instance.PM_PLAN_Single(CurrentDevice.AutoID, CurrentModel?.MaintenanceYear ?? DateTime.Now.Year, Belong.ToString());

                    if (vp != null)
                    {
                        if (XtraMessageBoxHelper.AskYesNo($"当前年度下设备编号:{CurrentDevice.EquipmentID}的设备已经存在计划,是否转到编辑？") == DialogResult.Yes)
                        {
                            CurrentModel = vp;
                            txt_EquipmentID.ReadOnly = true;
                            InitializeControl();
                            return;
                        }
                        else
                        {
                            txt_EquipmentID.ReadOnly = false;
                            txt_EquipmentID.Text = "";
                            txt_DeviceName.Text = "";
                            return;
                        }
                    }
                    else
                    {
                        ClearControl();
                    }

                    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);
            }
        }

        private void txt_EquipmentID_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                try
                {
                    if (!string.IsNullOrWhiteSpace(EquipmentID))
                    {
                        DeviceInformationInfo CurrentDevice = Utility.SystemRuntimeInfo.CurrentDeviceCaches.FirstOrDefault(x => x.EquipmentID.Equals(EquipmentID, StringComparison.CurrentCultureIgnoreCase));
                        if (CurrentDevice == null)
                            throw new ArgumentException($"设备【{EquipmentID}】在台账中不存在或不符合要求，请检查！");

                        AnnualMaintenancePlan vp = PlanRepository.Instance.PM_PLAN_Single(CurrentDevice.AutoID, CurrentModel?.MaintenanceYear ?? DateTime.Now.Year, Belong.ToString());

                        if (vp != null)
                        {
                            if (XtraMessageBoxHelper.AskYesNo($"当前年度下设备编号:{CurrentDevice.EquipmentID}的设备已经存在计划,是否转到编辑？") == DialogResult.Yes)
                            {
                                CurrentModel = vp;
                                txt_EquipmentID.ReadOnly = true;
                                InitializeControl();
                                return;
                            }
                            else
                            {
                                txt_EquipmentID.ReadOnly = false;
                                txt_EquipmentID.Text = "";
                                txt_DeviceName.Text = "";
                                return;
                            }
                        }
                        else
                        {
                            ClearControl();
                        }

                        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;
                    }
                    else
                    {
                        throw new ArgumentException($"设备编号不可为空！");
                    }
                }
                catch (Exception ex)
                {
                    XtraMessageBoxHelper.Error(ex.Message);
                }
            }
        }

        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;
                        planItem.Belong = Belong.ToString().Trim();

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

                    #endregion

                    if (lst2.All(x => x.MaintenanceType.IsNull()))
                    {
                        /* 计划的内容为空 */
                        if (CurrentModel.CreatUser > 0)
                        {
                            splashScreenManager1.TryCloseWait();
                            /* 计划修改为空 */
                            if (XtraMessageBoxHelper.AskYesNo($"当前的保养计划为空，是否删除设备【{CurrentModel.EquipmentName}({CurrentModel.DisplayEquipmentID})】的{CurrentModel.MaintenanceYear}年度计划") == DialogResult.Yes)
                            {
                                splashScreenManager1.ShowWaitForm();
                                if (!Utility.SystemRuntimeInfo.AuthValidate(OperationAuthConstValue.PM_PLAN_DELETE))
                                {
                                    XtraMessageBoxHelper.Error("当前账号缺少此操作的权限！");
                                    return;
                                }

                                APIResponseData resRtn = PlanRepository.Instance.Del_PM_PLAN(CurrentModel.EquipmentID, CurrentModel.MaintenanceYear, Belong.ToString());
                                if (!resRtn.IsSuccess)
                                {
                                    throw new Exception(resRtn.Message);
                                }


                                foreach (Form form in Application.OpenForms)
                                {
                                    if (Belong == EnumDeviceBelong.AM)
                                    {
                                        if (form.GetType() == typeof(pageDeviceAMPlanView))
                                        {
                                            (new Action(((pageDeviceAMPlanView)form).InitializeGridData)).Invoke();
                                            splashScreenManager1.TryCloseWait();
                                            DialogResult = DialogResult.OK;
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        if (form.GetType() == typeof(pageDevicePlanView))
                                        {
                                            (new Action(((pageDevicePlanView)form).InitializeGridData)).Invoke();
                                            splashScreenManager1.TryCloseWait();
                                            DialogResult = DialogResult.OK;
                                            break;
                                        }
                                    }
                                }
                            }
                            return;
                        }
                        else
                        {
                            /*新增的计划为空*/
                            splashScreenManager1.TryCloseWait();
                            XtraMessageBoxHelper.Warn($"不允许添加空的保养计划！");
                            return;
                        }
                    }

                    APIResponseData apiResponseData = PlanRepository.Instance.Insert_OR_Edit_PM_PLAN(lst2, Belong.ToString());
                    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;
            }
        }
    }
}