using DevExpress.XtraEditors;
using DeviceRepair.Models;
using DeviceRepair.Models.Device;
using DeviceRepair.Models.Enum;
using DeviceRepair.Utils;
using DeviceRepairAndOptimization.Common;
using DeviceRepairAndOptimization.Pages.DriveMaintenance;
using DeviceRepairAndOptimization.Pages.Maintenance;
using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace DeviceRepairAndOptimization.Pages.AM.Plan
{
    public partial class PagePlanDetail : XtraForm
    {
        public AnnualMaintenancePlan CurrentPlan;
        int m_SelectedCurrentRowIndex = 0;

        int CurrentEquipmentID
        {
            get
            {
                return CurrentPlan?.EquipmentID ?? 0;
            }
        }

        int CurrentYear = 0;
        DeviceAnnPlanView CurrentData = null;


        public PagePlanDetail(AnnualMaintenancePlan m_CurrentPlan, int Year)
        {
            InitializeComponent();

            CurrentPlan = m_CurrentPlan;
            CurrentYear = Year;

            this.Load += PagePlanDetail_Load;
        }

        private void PagePlanDetail_Load(object sender, EventArgs ee)
        {
            try
            {
                // 关闭列头右键菜单
                gridView1.OptionsMenu.EnableColumnMenu = false;

                BindData();
                // 自增长行号
                gridView1.CustomDrawRowIndicator += (s, e) =>
                {
                    if (e.Info.IsRowIndicator && e.RowHandle >= 0)
                    {
                        e.Info.DisplayText = (e.RowHandle + 1).ToString();
                        e.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                        e.Appearance.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center;
                        SizeF size = e.Graphics.MeasureString((e.RowHandle + 1).ToString(), e.Appearance.Font);
                    }
                };
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
                this.Close();
            }

        }

        void BindData()
        {
            try
            {
                APIResponseData apiResponseData = Biz.PlanManager.Instance.GetDeviceInformationPlans(CurrentYear, CurrentEquipmentID);
                if (!apiResponseData.IsSuccess)
                    throw new Exception(apiResponseData.Message);

                CurrentData = apiResponseData.ToDeserializeObject<DeviceAnnPlanView>();

                foreach (DriveMaintencePlanInfo item in CurrentData.Plans)
                {
                    MaintenanceRecordInfo record = CurrentData.Records?.FirstOrDefault(x => x.PlanPrimaryID == item.AutoID);
                    item.CompleteDate = record?.CreateDate ?? null;
                    item.EquipmentDisplayID = CurrentData.Dev.EquipmentID;
                    item.FormDisplayCode = CurrentData.CurrentFormCode;
                }

                gridView1.IndicatorWidth = 50;
                gridControl1.DataSource = CurrentData.Plans;
                gridView1.BestFitColumns();
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
                this.Close();
            }
        }

        private void repositoryItemButtonEdit1_Click(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                m_SelectedCurrentRowIndex = gridView1.FocusedRowHandle;
                if (!gridView1.IsValidRowHandle(m_SelectedCurrentRowIndex))
                {
                    throw new Exception("请先选择计划所在行！");
                }

                DriveMaintencePlanInfo CurrentSelectRowData = gridView1.GetRow(m_SelectedCurrentRowIndex) as DriveMaintencePlanInfo;
                if (CurrentSelectRowData == null)
                {
                    throw new Exception("请先选择计划所在行！");
                }

                if (e.Button.Caption.Equals("查看"))
                {
                    if (!GlobalInfo.HasRole(AuthCodeConstValue.BIZ_PRESERVE_LOG_AM_01))
                    {
                        throw new Exception($"当前账号缺少此操作的权限");
                    }

                    if (CurrentSelectRowData.CompleteDate.HasValue)
                    {
                        MaintenanceRecordInfo record = CurrentData.Records?.FirstOrDefault(x => x.PlanPrimaryID == CurrentSelectRowData.AutoID);
                        if (record == null)
                            throw new Exception("未查询到设备保养记录信息，请重试！");
                        page_MaintenancePdfView view = new page_MaintenancePdfView("查看", new int[] { record.PlanPrimaryID }, false);
                        view.ShowDialog(this);
                    }
                    else
                    {
                        throw new Exception("当前计划不存在保养信息！");
                    }
                }
                else if (e.Button.Caption.Equals("保养记录修改"))
                {
                    if (!GlobalInfo.HasRole(AuthCodeConstValue.BIZ_PRESERVE_LOG_AM_02))
                    {
                        throw new Exception($"当前账号缺少此操作的权限");
                    }

                    page_DriveMaintenance view = null;
                    if (CurrentSelectRowData.MaintenanceType == EnumMaintenanceType.Daily.ToString())
                    {
                        //CurrentSelectRowData.MaintenanceMonth
                        Pages.Plan.pageMaintenanceRecord v2 = new Pages.Plan.pageMaintenanceRecord();
                        v2.filter = new DeviceRepair.Models.Record.MaintenanceFilterModel
                        {
                            PlanID = CurrentSelectRowData.AutoID,
                            EquipmentId = CurrentData.Dev.AutoID,
                            StartDate = new DateTime(CurrentSelectRowData.MaintenanceYear, 1, 1),
                            EndDate = new DateTime(CurrentSelectRowData.MaintenanceYear, 12, 31, 23, 59, 59),
                            Banci = EnumMaintenanceBanciType.None,
                            EquipmentName = string.Empty,
                            MaintenanceType = EnumMaintenanceType.Daily
                        };

                        if (v2.ShowDialog() == DialogResult.OK && v2.CurrentModel != null)
                        {
                            view = new page_DriveMaintenance(CurrentData.Dev, CurrentSelectRowData.AutoID, v2.CurrentModel.AutoID, true);
                        }
                    }
                    else
                    {
                        MaintenanceRecordInfo record = CurrentData.Records?.FirstOrDefault(x => x.PlanPrimaryID == CurrentSelectRowData.AutoID);
                        if (record == null)
                            throw new Exception("未查询到设备保养记录信息，请重试！");

                        view = new page_DriveMaintenance(CurrentData.Dev, CurrentSelectRowData.AutoID, record.AutoID, true);
                    }

                    if (view != null)
                    {
                        if (view.ShowDialog(this) == DialogResult.OK)
                        {
                            XtraMessageBoxHelper.Info("操作成功!");
                        }
                        else
                        {
                            if (!string.IsNullOrWhiteSpace(view.apiResponseData.Message))
                                throw new Exception(view.apiResponseData.Message);
                        }
                    }
                }
                else if (e.Button.Caption.Equals("设备保养"))
                {
                    if (!GlobalInfo.HasRole(AuthCodeConstValue.BIZ_PRESERVE_AM))
                    {
                        throw new Exception($"当前账号缺少此操作的权限");
                    }

                    if (CurrentSelectRowData.FormDisplayCode.IsNull())
                    {
                        throw new Exception("当前设备未绑定点检表表单！");
                    }

                    if (CurrentSelectRowData.MaintenanceType == EnumMaintenanceType.Daily.ToString())
                    {
                        if (CurrentSelectRowData.FormDisplayCode != Biz.PreserveTemplate.TemplateConstValue.DailyTemplateV1
                            && CurrentSelectRowData.FormDisplayCode != Biz.PreserveTemplate.TemplateConstValue.DailyTemplateV2
                            )
                        {
                            throw new Exception($"当前保养类型与绑定的点检表不匹配!");
                        }

                        string MonthName = (new System.Globalization.CultureInfo("en-US")).DateTimeFormat.MonthNames[CurrentSelectRowData.MaintenanceMonth - 1].Substring(0, 3);
                        if (CurrentPlan.GetType().GetProperty(($"{MonthName}Status")) == null)
                        {
                            throw new Exception("获取当前计划状态失败！");
                        }

                        EnumPlanCompleteStatus value = (EnumPlanCompleteStatus)CurrentPlan.GetType().GetProperty(($"{MonthName}Status")).GetValue(CurrentPlan, null);
                        if (value == EnumPlanCompleteStatus.TimeOut || value == EnumPlanCompleteStatus.Current || value == EnumPlanCompleteStatus.Future)
                        {

                        }
                        else
                        {
                            throw new Exception("获取当前计划状态出错！");
                        }
                    }
                    else
                    {
                        if (CurrentSelectRowData.CompleteDate.HasValue)
                        {
                            throw new Exception("当前计划已保养！");
                        }

                        if (CurrentSelectRowData.FormDisplayCode != Biz.PreserveTemplate.TemplateConstValue.MonthTemplateV1)
                        {
                            throw new Exception($"当前保养类型与绑定的点检表不匹配!");
                        }
                    }

                    DateTime? MaintenanceDate = null;
                    // 每日保养类型
                    if (CurrentSelectRowData.MaintenanceType == EnumMaintenanceType.Daily.ToString())
                    {


                        using (Common.XtraCalendarShow selData = new Common.XtraCalendarShow(CurrentSelectRowData.AutoID, new DateTime(CurrentSelectRowData.MaintenanceYear, CurrentSelectRowData.MaintenanceMonth, 1)))
                        {
                            if (selData.ShowDialog(this) == DialogResult.OK)
                            {
                                MaintenanceDate = selData.Value;
                            }
                            else
                            {
                                return;
                            }
                        }
                    }
                    else
                    {
                        if (new DateTime(CurrentSelectRowData.MaintenanceYear, CurrentSelectRowData.MaintenanceMonth, 1) > DateTime.Today)
                        {
                            throw new Exception("不允许提前保养");
                        }
                    }

                    page_DriveMaintenance view = new page_DriveMaintenance(CurrentData.Dev, CurrentSelectRowData.AutoID);
                    if (MaintenanceDate.HasValue)
                        view.DaylyMaintenanceDate = MaintenanceDate.Value;

                    if (view.ShowDialog(this) == DialogResult.OK)
                    {
                        XtraMessageBoxHelper.Info("操作成功!");
                        foreach (Form form in Application.OpenForms)
                        {
                            if (form.GetType() == typeof(page_MaintenancePlan))
                                (new Action(((page_MaintenancePlan)form).InitializeGridData)).Invoke();
                        }
                        BindData();
                    }
                    else
                    {
                        if (!string.IsNullOrWhiteSpace(view.apiResponseData.Message))
                            throw new Exception(view.apiResponseData.Message);
                    }
                }
                else if (e.Button.Caption.Equals("打印"))
                {
                    if (!GlobalInfo.HasRole(AuthCodeConstValue.BIZ_PRESERVE_LOG_AM_03))
                    {
                        throw new Exception($"当前账号缺少此操作的权限");
                    }

                    if (CurrentSelectRowData.CompleteDate.HasValue)
                    {
                        MaintenanceRecordInfo record = CurrentData.Records?.FirstOrDefault(x => x.PlanPrimaryID == CurrentSelectRowData.AutoID);
                        page_MaintenancePdfView view = new page_MaintenancePdfView("打印", new int[] { record.PlanPrimaryID }, true);
                        view.ShowDialog(this);
                    }
                    else
                    {
                        throw new Exception("当前计划不存在保养信息！");
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }
    }
}