using DevExpress.XtraBars.Docking2010.Customization;
using DevExpress.XtraBars.Docking2010.Views.WindowsUI;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Tile;
using DeviceRepairAndOptimization.Data;
using DeviceRepairAndOptimization.Models;
using DeviceRepairAndOptimization.Pages.DriveMaintenance;
using DeviceRepairAndOptimization.Utils;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;

namespace DeviceRepairAndOptimization.Pages
{
    /// <summary>
    /// 设备类型 - 设备信息 - 列表信息及操作
    /// </summary>
    public partial class page_DriveTypeLst : FormBase
    {
        #region 属性

        /// <summary>
        /// 全部数据
        /// </summary>
        DataSet Datas { get; set; }

        /// <summary>
        /// GridContol主列表
        /// </summary>
        TileView MainView
        {
            get { return TypeView; }
        }

        #endregion 属性

        #region 函数

        /// <summary>
        /// 函数
        /// </summary>
        /// <param name="Caption"></param>
        public page_DriveTypeLst(string Caption)
        {
            InitializeComponent();
            this.lb_title.Text = Caption;
        }

        #endregion 函数

        #region 事件

        /// <summary>
        /// 窗体加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void page_DriveTypeLst_Load(object sender, EventArgs e)
        {
            try
            {
                splashScreenManager1.ShowWaitForm();
                InitializeGridData();
                this.tb_pnl_Content.RowStyles[0].Height = 45f;
                this.EditSearch.Height = 31;

                //获取Windows显示的缩放比例
                if (ComputerHelper.ScaleX > 1)
                    flowLayoutPanel1.Width = (int)(this.Width / ComputerHelper.ScaleX);

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

        /// <summary>
        /// 搜索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void EditSearch_TextChanged(object sender, EventArgs e)
        {
            string filter = EditSearch.Text.Trim();
            if (gridControl.MainView == MainView)
            {
                DataTable table = Datas.Tables[0].Clone();
                IEnumerable<DataRow> dataRows = Datas.Tables[0].AsEnumerable()
                    .Where(x => (x["TypeName"] + "").Contains(filter))?.Cast<DataRow>();
                if (dataRows != null && dataRows.Count() > 0)
                {
                    table = dataRows.CopyToDataTable();
                }
                gridControl.DataSource = table;
            }
            else
            {
                DataTable table = Datas.Tables[1].Clone();
                IEnumerable<DataRow> dataRows = Datas.Tables[1].AsEnumerable().Where(x =>
                    x.Field<string>("EquipmentName") == lb_title.Text.Trim() &&
                    x.Field<string>("EquipmentID").Contains(filter))?.Cast<DataRow>();
                if (dataRows != null && dataRows.Count() > 0)
                    table = dataRows.CopyToDataTable();

                gridControl.DataSource = table;
            }
        }

        /// <summary>
        /// 设备类型 - 双击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TypeView_ItemDoubleClick(object sender, TileViewItemClickEventArgs e)
        {
            string dType = TypeView.GetRowCellValue(e.Item.RowHandle, "TypeName") + "";
            DataRow dr = Datas.Tables[0].Select($"TypeName='{dType}'").FirstOrDefault();
            if (dr != null)
            {
                DataRow[] rows = dr.GetChildRows(Datas.Relations[0]);
                gridControl.MainView = DriveItemView;
                lb_title.Text = dType;
                lb_toBack.Visible = true;
                gridControl.DataSource = rows.Cast<DataRow>().CopyToDataTable();
            }
        }

        /// <summary>
        /// 返回按钮 - 点击时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lb_toBack_Click(object sender, EventArgs e)
        {
            gridControl.MainView = MainView;
            lb_title.Text = "设备类型";
            lb_toBack.Visible = false;

            string filter = EditSearch.Text.Trim();
            if (string.IsNullOrWhiteSpace(filter))
            {
                gridControl.DataSource = Datas.Tables[0];
            }
            else
            {
                DataTable table = Datas.Tables[0].Clone();
                IEnumerable<DataRow> dataRows = Datas.Tables[0].AsEnumerable()
                    .Where(x => (x["TypeName"] + "").Contains(filter))?.Cast<DataRow>();
                if (dataRows != null && dataRows.Count() > 0)
                {
                    table = dataRows.CopyToDataTable();
                }
                gridControl.DataSource = table;
            }
        }

        /// <summary>
        /// 设备列表 - 列文本Format
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DriveItemView_CustomColumnDisplayText(object sender,
            DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Value != null && e.Column.FieldName == "MaintenanceFormVersion")
                e.DisplayText = e.Column.CustomizationCaption + "N/A";
        }


        /// <summary>
        /// 设备类型列表 - 列文本Format
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TypeView_CustomColumnDisplayText(object sender,
            DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Value != null && e.Column.FieldName == "SonCount")
                e.DisplayText = $"{e.DisplayText}";
        }

        #endregion 事件

        #region 方法

        /// <summary>
        /// 数据加载
        /// </summary>
        void InitializeGridData()
        {
            List<DriveInfomationModel> lst = DriveInformationMaintenance.Instance().GetAll();
            DataTable tst = lst.GroupBy(x => x.EquipmentName)
                .Select(x => new { TypeName = x.Key, TypeDescription = "", SonCount = 0 }).ToList().toDataTable();

            if (!Datas.HasData())
                Datas = new DataSet();
            Datas.Tables.Add(tst);
            Datas.Tables.Add(lst.toDataTable());
            Datas.Relations.Add("Lk", Datas.Tables[0].Columns["TypeName"], Datas.Tables[1].Columns["EquipmentName"]);
            foreach (DataRow item in Datas.Tables[0].Rows)
            {
                item["SonCount"] = item.GetChildRows(Datas.Relations[0])?.Count();
            }

            gridControl.DataSource = Datas.Tables[0];
        }

        #endregion 方法

        private void page_DriveTypeLst_SizeChanged(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 自定义按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DriveItemView_ContextButtonClick(object sender, DevExpress.Utils.ContextItemClickEventArgs e)
        {
            try
            {
                //当前选中对象
                DataRow currentDataRow = ((DataRowView)DriveItemView.GetRow(((TileViewItem)e.DataItem).RowHandle)).Row;

                ///设备编码
                string EquipmentID = ((TileItem)e.DataItem).Text;

                if (e.Item.Name == "Btn_Maintenance")
                {
                    if (!ApiHelper.Instance.RoleExistsAuth("BIZ_MAINTENANCE_EDIT").ToBool())
                    {
                        XtraMessageBoxHelper.Error($"当前账号缺少此操作的权限");
                        return;
                    }

                    //此处应通过webpi下载xls逻辑
                    DriveInfomationModel entity = DriveInformationMaintenance.Instance().GetModelByEquipmentID(EquipmentID);

                    if (entity == null || entity.MaintenanceFormVersion == 0)
                    {
                        XtraMessageBox.Show("该设备未绑定点检表,请先绑定点检表。", "出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    //通过点检表主键ID获取点检表并保存到缓存目录
                    string templatePath = MaintenanceFormVersionMaintenance.Instance.GetFileSingle(entity.MaintenanceFormVersion);

                    List<DrivePlanModel> plans = PlanMaintenance.Instance.GetTipsPlan();
                    if (plans != null && plans.Count > 0 && plans.Any(x => x.EquipmentID == entity.AutoID))
                    {
                        DrivePlanModel plan = plans.FirstOrDefault(x => x.EquipmentID == entity.AutoID);
                        if (plan == null)
                        {
                            XtraMessageBoxHelper.Warn($"当前设备已完成设备保养，无需保养！");
                        }

                        // 20240418
                        //page_DriveMaintenance view = new page_DriveMaintenance(entity, plan.AutoID);
                        //DialogResult dr = view.ShowDialog();
                        //if (dr == DialogResult.OK)
                        //{
                        //    XtraMessageBoxHelper.Info("操作成功！");
                        //}
                        //else if (dr == DialogResult.Abort)
                        //{
                        //    XtraMessageBoxHelper.Info(view.result.Message);
                        //}
                    }
                    else
                    {
                        XtraMessageBoxHelper.Warn($"当前设备本月没有保养计划，无需保养！");
                    }
                }
                else if (e.Item.Name == "btn_ShowLogs")
                {
                    int intEquipmentID = 0;
                    if (int.TryParse(currentDataRow["AutoID"] + "", out intEquipmentID))
                    {
                        xuc_RepairLogLst _form = new xuc_RepairLogLst(intEquipmentID);
                        FlyoutAction action = new FlyoutAction() { Caption = "维修记录", Description = "" };
                        FlyoutCommand command1 = new FlyoutCommand() { Text = "确认", Result = DialogResult.OK };
                        action.Commands.Add(command1);
                        Predicate<DialogResult> predicate = (A) =>
                        {
                            return true;
                        };

                        FlyoutDialog.Show(GlobalInfo._RootForm, _form, action, new FlyoutProperties() { Style = FlyoutStyle.Popup }, predicate);

                    }
                    else
                    {
                        XtraMessageBox.Show("未能获取到设备信息,请重试。", "出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }
    }
}