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

namespace DeviceRepairAndOptimization.Pages.CustomField
{
    public partial class pageFieldCode : ToolbarForm
    {
        /// <summary>
        /// 窗口标题
        /// </summary>
        public string Caption = "字段配置";

        /// <summary>
        /// 当前字段编码
        /// </summary>
        public string FieldCode = "";

        /// <summary>
        /// 筛选条件
        /// </summary>
        public string FilterString = "";

        List<FieldsInfo> CurrentDatas;
        int m_SelectedCurrentRowIndex = 0;
        FieldsInfo CurrentFieldInfo;

        List<dynamic> _FieldsTypeCollect;
        public List<dynamic> FieldsTypeCollect
        {
            get
            {
                if (_FieldsTypeCollect == null)
                    _FieldsTypeCollect = new List<dynamic>() {
                    new { TypeValue = "NVarChar", Name = "文本值" },
                    new { TypeValue = "double", Name = "数值" },
                    new { TypeValue = "decimal", Name = "货币" }
                };
                return _FieldsTypeCollect;
            }
        }

        Dictionary<int, string> _UserMapping;
        Dictionary<int, string> UserMapping
        {
            get
            {
                if (_UserMapping == null)
                {
                    try
                    {
                        APIResponseData apiResponseData = UserManager.Instance.GetUserMapping();
                        if (!apiResponseData.IsSuccess)
                            throw new Exception(apiResponseData.Message);
                        _UserMapping = apiResponseData.ToDeserializeObject<Dictionary<int, string>>();
                    }
                    catch (Exception ex)
                    {
                        XtraMessageBoxHelper.Error(ex.Message);
                    }
                }
                return _UserMapping;
            }
        }

        public pageFieldCode(string Code, string DisPlayTitle = "字段配置")
        {
            InitializeComponent();

            FieldCode = Code;
            Caption = $"字段配置 - {DisPlayTitle}";
            this.Load += PageFieldCode_Load;
        }

        private void PageFieldCode_Load(object sender, EventArgs e)
        {
            Text = Caption;

            GridViewInitialize(gridView1);
            InitializeGridDatas();
            gridView1.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;
            gridView1.OptionsSelection.ShowCheckBoxSelectorInColumnHeader = DevExpress.Utils.DefaultBoolean.False;
            gridView1.CustomDrawColumnHeader += GridView1_CustomDrawColumnHeader;
            gridView1.RowCellClick += GridView1_RowCellClick;
            gridView1.CustomDrawRowIndicator += GridView1_CustomDrawRowIndicator;

            gridView1.RowStyle += (sd, ee) =>
            {
                DevExpress.XtraGrid.Views.Grid.GridView view = sd as DevExpress.XtraGrid.Views.Grid.GridView;

                if (ee.RowHandle >= 0)
                {
                    FieldsInfo item = view.GetRow(ee.RowHandle) as FieldsInfo;
                    if (!item.Status)
                        ee.Appearance.BackColor = Color.FromArgb(255, 126, 126);
                }
            };
        }

        /// <summary>
        /// 自增长行号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs 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;
            }
        }

        /// <summary>
        /// 行选择模式，且全部只读
        /// </summary>
        /// <param name="view"></param>
        void GridViewInitialize(DevExpress.XtraGrid.Views.Grid.GridView view)
        {
            view.OptionsBehavior.Editable = false;
            view.OptionsBehavior.ReadOnly = true;

            view.OptionsSelection.EnableAppearanceFocusedCell = false;
            view.OptionsScrollAnnotations.ShowSelectedRows = DevExpress.Utils.DefaultBoolean.False;

            foreach (DevExpress.XtraGrid.Columns.GridColumn item in view.Columns)
            {
                item.OptionsColumn.AllowEdit = false;
                item.OptionsColumn.AllowGroup = DevExpress.Utils.DefaultBoolean.True;
                item.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
                item.OptionsColumn.AllowShowHide = false;
            }
        }

        private void GridView1_CustomDrawColumnHeader(object sender, DevExpress.XtraGrid.Views.Grid.ColumnHeaderCustomDrawEventArgs e)
        {
            if (e.Column != null && e.Column.Caption == "Selection")
                e.Info.Caption = "选择";
        }

        private void GridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                e.Handled = true;
                return;
            }

            if (e.Column.Caption == "Selection")
            {
                if (this.m_SelectedCurrentRowIndex == e.RowHandle && this.gridView1.IsRowSelected(e.RowHandle))
                    this.gridView1.UnselectRow(e.RowHandle);
            }
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem3_ItemClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                string RoleCode = "";
                //配件维护
                if (FieldCode.ToUpper() == "ACCESSORIES")
                {
                    RoleCode = "BIZ_FIELD_ACCESSORIES_ADD";
                }
                else
                {
                    RoleCode = $"BIZ_FIELD_{FieldCode.ToUpper()}_EDIT";
                }

                if (!GlobalInfo.HasRole(RoleCode))
                {
                    throw new Exception($"当前账号缺少此操作的权限");
                }

                pageFieldEdit view = new pageFieldEdit(FieldCode);

                DialogResult Dr = view.ShowDialog();
                if (Dr == DialogResult.OK)
                {
                    InitializeGridDatas();
                }
                else if (Dr == DialogResult.Abort)
                {
                    throw new Exception(view.ErrorMsg);
                }
                else
                {
                    InitializeGridDatas();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 数据加载
        /// </summary>
        void InitializeGridDatas()
        {
            try
            {
                splashScreenManager1.ShowWaitForm();

                APIResponseData apiResponseData = FieldsManager.Instance.GetQuery(FieldCode);
                if (!apiResponseData.IsSuccess)
                    throw new Exception(apiResponseData.Message);

                CurrentDatas = apiResponseData.ToDeserializeObject<List<FieldsInfo>>();

                foreach (var item in CurrentDatas)
                {
                    item.FieldTypeCaption = FieldsTypeCollect.FirstOrDefault(x => x.TypeValue == item.FieldType).Name;
                    item.StatusText = item.Status ? "启用" : "停用";
                    item.CreatorName = UserMapping[item.CreatBy];
                    if (item.ModifyBy.HasValue)
                        item.ModifierName = UserMapping[item.ModifyBy.Value];
                }

                gridControl1.DataSource = gridControl1.DataSource = CurrentDatas.Where(x => x.FieldText.Contains(FilterString)
|| x.FieldValue.Contains(FilterString)).ToList();
                gridView1.BestFitColumns();
                splashScreenManager1.TryCloseWait();
            }
            catch (Exception ex)
            {
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 获取选择的目标,并且更改状态按钮的图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            try
            {
                if (e.FocusedRowHandle >= 0)
                {
                    m_SelectedCurrentRowIndex = e.FocusedRowHandle;
                    CurrentFieldInfo = gridView1.GetRow(e.FocusedRowHandle) as FieldsInfo;

                    #region 修改选定状态
                    if (gridView1.SelectedRowsCount > 0)
                    {
                        for (int i = 0; i < this.gridView1.RowCount; i++)
                        {
                            if (this.gridView1.IsRowSelected(i) && this.gridView1.FocusedRowHandle.ToString().Equals(i.ToString()) == false)
                            {
                                this.gridView1.UnselectRow(i);
                            }
                        }
                    }

                    this.gridView1.SelectRow(e.FocusedRowHandle);
                    #endregion

                    #region 修改按钮图片
                    if (CurrentFieldInfo != null && CurrentFieldInfo.Status)
                    {
                        bar_btn_StatusChange.Caption = "字段禁用";
                        bar_btn_StatusChange.ImageOptions.Image = Properties.Resources.LOCK;
                    }
                    else
                    {
                        bar_btn_StatusChange.Caption = "字段启用";
                        bar_btn_StatusChange.ImageOptions.Image = Properties.Resources.UNLOCK;
                    }
                    #endregion
                }
                else
                {
                    CurrentFieldInfo = null;
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        #region 搜索
        private void repositoryItemButtonEdit1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter)
                return;

            gridControl1.DataSource = CurrentDatas.Where(x => x.FieldText.Contains(FilterString)
            || x.FieldValue.Contains(FilterString)).ToList();
            gridView1.BestFitColumns();
        }

        private void bar_btn_Search_ItemClick(object sender, ItemClickEventArgs e)
        {
            gridControl1.DataSource = CurrentDatas.Where(x => x.FieldText.Contains(FilterString)
            || x.FieldValue.Contains(FilterString)).ToList();
            gridView1.BestFitColumns();
        }

        private void repositoryItemTextEdit4_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter)
                return;

            bar_btn_Search.PerformClick();
        }

        private void repositoryItemTextEdit4_KeyUp(object sender, KeyEventArgs e)
        {
            FilterString = (sender as TextEdit).EditValue.ToString().Trim();
        }
        #endregion

        #region 修改状态
        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bar_btn_StatusChange_ItemClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                if (CurrentFieldInfo == null)
                    throw new Exception("请选择字段所在行！");

                string RoleCode = $"BIZ_FIELD_{FieldCode.ToUpper()}_EDIT";
                if (!GlobalInfo.HasRole(RoleCode))
                {
                    throw new Exception($"当前账号缺少此操作的权限");
                }

            getRemark:
                if (XtraMessageBoxHelper.AskYesNo($"<size=16>确认<b>{(CurrentFieldInfo.Status ? "<color=red>停用<color/>" : "<color=LimeGreen>启用<color/>")}<b/>字段{CurrentFieldInfo.FieldText} - {CurrentFieldInfo.FieldValue}?<size/>") == DialogResult.Yes)
                {
                    // 录入原因
                    string result = XtraInputBox.Show("原因录入:", $"请录入字段{(CurrentFieldInfo.Status ? "停用" : "启用")}原因", "");
                    if (string.IsNullOrWhiteSpace(result))
                    {
                        if (XtraMessageBoxHelper.AskYesNo("原因不能为空，是否继续操作？") == DialogResult.Yes)
                            goto getRemark;
                        return;
                    }

                    bool BeStatus = !CurrentFieldInfo.Status;
                    string Description = result;

                    APIResponseData apiResponseData = FieldsManager.Instance.ChangeStatus(CurrentFieldInfo.AutoID, BeStatus, Description);
                    if (!apiResponseData.IsSuccess)
                        throw new Exception(apiResponseData.Message);

                    InitializeGridDatas();
                    gridView1.RefreshData();
                    gridView1.FocusedRowHandle = m_SelectedCurrentRowIndex > 0 ? 0 : m_SelectedCurrentRowIndex + 1;
                    XtraMessageBoxHelper.Info("操作成功！");
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }
        #endregion

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem4_ItemClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                if (CurrentFieldInfo == null)
                    throw new Exception("请选择字段所在行！");

                string RoleCode = $"BIZ_FIELD_{FieldCode.ToUpper()}_EDIT";
                if (!GlobalInfo.HasRole(RoleCode))
                {
                    throw new Exception($"当前账号缺少此操作的权限");
                }

                if (!CurrentFieldInfo.Status)
                {
                    throw new Exception($"停用的数据不允许更改！");
                }

                pageFieldEdit view = new pageFieldEdit(FieldCode, CurrentFieldInfo);

                DialogResult Dr = view.ShowDialog();
                if (Dr == DialogResult.OK)
                {
                    InitializeGridDatas();
                }
                else if (Dr == DialogResult.Abort)
                {
                    throw new Exception(view.ErrorMsg);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }
    }
}