using DevExpress.XtraBars.ToolbarForm;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using TsSFC.Base.Model.Device;
using TsSFCDeivceClient.Common;
using TsSFCDeivceClient.Model;
using TsSFCDeivceClient.Model.Common;
using TsSFCDeivceClient.Model.DeviceWarrantyRequest;

namespace TsSFCDeivceClient
{
    public partial class pageDeviceMaintenanceFormView : ToolbarForm
    {
        int m_SelectedCurrentRowIndex = 0;
        DataRow CurrentRequestForm = null;
        System.Configuration.Configuration m_Config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);

        string ServiceUrl
        {
            get
            {
                return m_Config.AppSettings.Settings["ServiceApiUrl"].Value.Trim();
            }
        }

        List<LookUpItemModel> lookupMaintenanceStatus;
        DeviceWarrantyRequestFormFilter _filter;
        DeviceWarrantyRequestFormFilter FilterInfo
        {
            get
            {
                if (_filter == null)
                    _filter = new DeviceWarrantyRequestFormFilter();

                _filter.EquipmentID = EquipmentID;
                _filter.StartTime = Filter_Start_Date;
                _filter.EndTime = Filter_End_Date.AddDays(1).AddMilliseconds(-1);
                _filter.Status = Filter_Status;
                _filter.DownStatus = Filter_DownStatus;

                return _filter;
            }
        }

        string EquipmentID
        {
            get { return txt_DeviceID.Text.Trim(); }
        }

        /// <summary>
        /// 设备状态
        /// </summary>
        DeviceWarrantyRequestFormStatus Filter_Status
        {
            get { return (DeviceWarrantyRequestFormStatus)((int)(cb_Status.EditValue)); }
        }

        /// <summary>
        /// 设备停机状态
        /// </summary>
        DeviceRunningStatus Filter_DownStatus
        {
            get { return (DeviceRunningStatus)cbbIsDown.SelectedIndex; }
        }

        /// <summary>
        /// 开始时间
        /// </summary>
        DateTime Filter_Start_Date
        {
            get { return Convert.ToDateTime(de_StartDate.EditValue); }
        }

        /// <summary>
        /// 结束时间
        /// </summary>
        DateTime Filter_End_Date
        {
            get { return Convert.ToDateTime(de_EndDate.EditValue); }
        }

        bool HasAuth = false;

        public pageDeviceMaintenanceFormView(UserInfo user, string APPVERSION)
        {
            InitializeComponent();

            Runtime.CurrentUser = user;
            Runtime.inParams = JsonConvert.SerializeObject(new { OPERATORGUID = user.GUID, OPERATOR = user.UserCode, CLIENTIP = ComputerHelper.Instance().IpAddress, CLIENTMAC = ComputerHelper.Instance().MacAddress, CLIENTNAME = ComputerHelper.Instance().ComputerName , APPVERSION  = APPVERSION });
            HasAuth = user.HasPost;
            this.Load += PageDeviceMaintenanceFormView_Load;
        }

        private void PageDeviceMaintenanceFormView_Load(object sender, EventArgs e)
        {
            if (Runtime.CurrentUser == null)
            {
                XtraMessageBoxHelper.Error($"非法的调用，请重试。");
                this.Close();
            }

            if (string.IsNullOrWhiteSpace(ServiceUrl))
            {
                XtraMessageBoxHelper.Error($"缺少配置字段（设备管理软件接口地址）【ServiceApiUrl】。");
                this.Close();
            }

            if (lookupMaintenanceStatus == null)
                lookupMaintenanceStatus = new List<LookUpItemModel>();

            foreach (DeviceWarrantyRequestFormStatus item in Enum.GetValues(typeof(DeviceWarrantyRequestFormStatus)))
            {
                lookupMaintenanceStatus.Add(new LookUpItemModel
                {
                    ValueMember = (int)item,
                    DisplayMember = item.ToDescription()
                });
            }

            cb_Status.Properties.DataSource = lookupMaintenanceStatus;
            cb_Status.Properties.DisplayMember = "DisplayMember";
            cb_Status.Properties.ValueMember = "ValueMember";
            cb_Status.Properties.BestFitMode = DevExpress.XtraEditors.Controls.BestFitMode.BestFitResizePopup;
            cb_Status.EditValue = (int)DeviceWarrantyRequestFormStatus.All;


            cbbIsDown.Properties.Items.BeginUpdate();
            foreach (DeviceRunningStatus item in Enum.GetValues(typeof(DeviceRunningStatus)))
            {
                cbbIsDown.Properties.Items.Add(item.ToDescription());
            }
            cbbIsDown.Properties.Items.EndUpdate();
            cbbIsDown.SelectedIndex = 0;


            de_StartDate.EditValue = DateTime.Today.AddMonths(-1);
            de_EndDate.EditValue = DateTime.Today;

            InitializeGridViewStyle();
        }

        List<DeviceWarrantyRequestForm> GridDatas = null;

        DataTable ToDataTable(IList list)
        {
            DataTable result = new DataTable();
            if (list.Count > 0)
            {
                PropertyInfo[] propertys = list[0].GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    Type colType = pi.PropertyType;
                    if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                    {
                        colType = colType.GetGenericArguments()[0];
                    }
                    result.Columns.Add(new DataColumn(pi.Name, colType));
                }
                for (int i = 0; i < list.Count; i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in propertys)
                    {
                        object obj = pi.GetValue(list[i], null) == null ? DBNull.Value : pi.GetValue(list[i], null);
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    result.LoadDataRow(array, true);
                }
            }
            return result;
        }

        void InitializeGridDatas()
        {
            try
            {
                splashScreenManager1.ShowWaitForm();
                APIResponseData apiResponseData = Biz.HttpHelper.Instance.Post($"{ServiceUrl}{DeviceApiUrlConstValue.GetMaintenance}", FilterInfo.ToJson());

                if (!apiResponseData.IsSuccess)
                    throw new Exception(apiResponseData.Message);

                GridDatas = apiResponseData.ToDeserializeObject<List<DeviceWarrantyRequestForm>>();

                DataTable table = ToDataTable(GridDatas);

                gridControl1.DataSource = null;
                gridControl1.DataSource = table;
                gridView1.BestFitColumns();
                CloseWaitForm();
            }
            catch (Exception ex)
            {
                gridControl1.DataSource = null;
                CloseWaitForm();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 初始化表格样式
        /// </summary>
        void InitializeGridViewStyle()
        {
            /// 自增长行号
            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);
                    BeginInvoke(new MethodInvoker(delegate { gridView1.IndicatorWidth = Convert.ToInt32(size.Width) + 20; }));
                }
            };

            /// 修改字段标题
            gridView1.CustomDrawColumnHeader += (s, e) =>
            {
                if (e.Column != null && e.Column.Caption == "Selection")
                    e.Info.Caption = "选择";
            };

            /// 单元格点击
            gridView1.RowCellClick += (s, 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);
                        return;
                    }
                }

                DataRow model = (gridView1.GetRow(e.RowHandle) as DataRowView).Row;
                if (model["AutoID"]?.ToString() != CurrentRequestForm["AutoID"]?.ToString())
                {
                    CurrentRequestForm = model;
                    this.gridView1.SelectRow(e.RowHandle);
                }
            };

            /// 表格选中行更改
            gridView1.FocusedRowChanged += (s, e) =>
            {
                try
                {
                    if (e.FocusedRowHandle >= 0)
                    {
                        m_SelectedCurrentRowIndex = e.FocusedRowHandle;
                        CurrentRequestForm = (gridView1.GetRow(e.FocusedRowHandle) as DataRowView).Row;

                        #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

                        bool PE = false;
                        bool QE = false;
                        bool RestorationConfirmation = false;

                        int AutoID = Convert.ToInt32(CurrentRequestForm["AutoID"]);
                        DeviceWarrantyRequestForm Item = GridDatas.FirstOrDefault(x => x.AutoID == AutoID);

                        if (Item != null && HasAuth && Item.FormStatus != DeviceWarrantyRequestFormStatus.BeComplate && Item.InProduction)
                        {
                            if (Item.EvaluatorItems != null)
                            {
                                if (!Item.EvaluatorItems.Any(x => x.EvaluatorCode == "PE"))
                                {
                                    PE = true;
                                }

                                if (!Item.EvaluatorItems.Any(x => x.EvaluatorCode == "QE"))
                                {
                                    QE = true;
                                }
                            }
                        }

                        if (Item != null && Item.MaintaionItems != null && Item != null && Item.MaintaionItems.SubmitBy > 0 &&
                        ((Item.InProduction && Item.EvaluatorItems != null && Item.EvaluatorItems.Count == 2) ||
                        (!Item.InProduction)) && Item.MaintaionItems.ValidateBy > 0 && Item.MaintaionItems.Validate2By > 0
                         && Item.RestorationConfirmationBy == 0
                        )
                        {
                            RestorationConfirmation = true;
                        }

                        this.Invoke(new Action(() =>
                        {
                            btn_Assessment_PE.Enabled = PE;
                            btn_Assessment_PE.Refresh();

                            btn_Assessment_QE.Enabled = QE;
                            btn_Assessment_QE.Refresh();

                            btnResumptionConfirm.Enabled = RestorationConfirmation;
                            btnResumptionConfirm.Refresh();
                        }));
                    }
                    else
                    {
                        CurrentRequestForm = null;
                    }
                }
                catch (Exception ex)
                {
                    XtraMessageBoxHelper.Error(ex.Message);
                }
            };

            gridView1.OptionsBehavior.Editable = false;
            gridView1.OptionsBehavior.ReadOnly = true;

            gridView1.OptionsSelection.MultiSelect = true;
            gridView1.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;

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

            foreach (DevExpress.XtraGrid.Columns.GridColumn item in gridView1.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 CloseWaitForm()
        {
            try
            {
                if (splashScreenManager1.IsSplashFormVisible)
                {
                    splashScreenManager1.CloseWaitForm();
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception ex)
            {
                //m_log.Error(ex.Message, ex);
            }
        }

        private void btn_Filter_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 新增设备维修单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_FormAdd_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                using (DowntimeFormAdd view = new DowntimeFormAdd())
                {
                    if (view.ShowDialog() == DialogResult.OK)
                    {
                        XtraMessageBoxHelper.Info("操作成功！");
                    }
                    InitializeGridDatas();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        private void btn_Query_Click(object sender, EventArgs e)
        {
            InitializeGridDatas();
            this.Refresh();
        }

        private void btn_Assessment_PE_Click(object sender, EventArgs e)
        {
            try
            {
                if (CurrentRequestForm == null)
                    throw new Exception($"请选择要评估的维修单！");

                int AutoID = 0;
                if (int.TryParse(CurrentRequestForm["AutoID"] + "", out AutoID) && AutoID > 0)
                {
                    DeviceWarrantyRequestForm Item = GridDatas.FirstOrDefault(x => x.AutoID == AutoID);
                    if (Item == null)
                        throw new Exception($"获取维修单数据出错，请重试！");

                    XtraInputBoxArgs args = new XtraInputBoxArgs { Prompt = "评估内容：", Caption = "质量部评估", DefaultResponse = "" };
                    args.Buttons = new DialogResult[] { DialogResult.OK, DialogResult.Cancel };
                    args.DefaultButtonIndex = (int)DialogResult.Cancel;
                    DialogResult DiaResult = DialogResult.None;
                    args.Showing += (a, b) =>
                    {
                        b.Buttons[DialogResult.OK].Click += (c, d) => { DiaResult = DialogResult.OK; };
                    };

                    var Description = XtraInputBox.Show(args);
                    if (DiaResult == DialogResult.None)
                        return;
                    else
                    {
                        if (string.IsNullOrWhiteSpace(Description + ""))
                            throw new Exception($"评估内容不能为空！");

                        if (Description.ToString().Length > 4000)
                            throw new Exception($"评估内容长度不能超过4000！");

                        splashScreenManager1.ShowWaitForm();
                        DeviceWarrantyEvaluatorInfo info = new DeviceWarrantyEvaluatorInfo
                        {
                            Description = Description + "",
                            EvaluatorCode = "PE",
                            FormID = Item.AutoID,
                        };

                        APIResponseData apiResponseData = Biz.HttpHelper.Instance.Post($"{ServiceUrl}{DeviceApiUrlConstValue.MaintenanceFormAssessment}", info.ToJson());
                        if (!apiResponseData.IsSuccess)
                            throw new Exception(apiResponseData.Message);
                    }
                }
                else
                {
                    throw new Exception($"获取维修单数据出错，请重试！");
                }
                CloseWaitForm();
                XtraMessageBoxHelper.Info("操作成功！");
                InitializeGridDatas();
            }
            catch (Exception ex)
            {
                CloseWaitForm();
                XtraMessageBoxHelper.Error(ex.Message);
                InitializeGridDatas();
            }
        }

        private void btn_Assessment_QE_Click(object sender, EventArgs e)
        {
            try
            {
                if (CurrentRequestForm == null)
                    throw new Exception($"请选择要评估的维修单！");

                int AutoID = 0;
                if (int.TryParse(CurrentRequestForm["AutoID"] + "", out AutoID) && AutoID > 0)
                {
                    DeviceWarrantyRequestForm Item = GridDatas.FirstOrDefault(x => x.AutoID == AutoID);
                    if (Item == null)
                        throw new Exception($"获取维修单数据出错，请重试！");

                    XtraInputBoxArgs args = new XtraInputBoxArgs { Prompt = "评估内容：", Caption = "质量部评估", DefaultResponse = "" };
                    args.Buttons = new DialogResult[] { DialogResult.OK, DialogResult.Cancel };
                    args.DefaultButtonIndex = (int)DialogResult.Cancel;
                    DialogResult DiaResult = DialogResult.None;
                    args.Showing += (a, b) =>
                    {
                        b.Buttons[DialogResult.OK].Click += (c, d) => { DiaResult = DialogResult.OK; };
                    };

                    var Description = XtraInputBox.Show(args);
                    if (DiaResult == DialogResult.None)
                        return;
                    else
                    {
                        if (string.IsNullOrWhiteSpace(Description + ""))
                            throw new Exception($"评估内容不能为空！");

                        if (Description.ToString().Length > 4000)
                            throw new Exception($"评估内容长度不能超过4000！");

                        splashScreenManager1.ShowWaitForm();
                        DeviceWarrantyEvaluatorInfo info = new DeviceWarrantyEvaluatorInfo
                        {
                            Description = Description.ToString(),
                            EvaluatorCode = "QE",
                            FormID = Item.AutoID,
                        };

                        APIResponseData apiResponseData = Biz.HttpHelper.Instance.Post($"{ServiceUrl}{DeviceApiUrlConstValue.MaintenanceFormAssessment}", info.ToJson());
                        if (!apiResponseData.IsSuccess)
                            throw new Exception(apiResponseData.Message);
                    }
                }
                else
                {
                    throw new Exception($"获取维修单数据出错，请重试！");
                }
                CloseWaitForm();
                XtraMessageBoxHelper.Info("操作成功！");
                InitializeGridDatas();
            }
            catch (Exception ex)
            {
                CloseWaitForm();
                XtraMessageBoxHelper.Error(ex.Message);
                InitializeGridDatas();
            }
        }

        private void pageDeviceMaintenanceFormView_SizeChanged(object sender, EventArgs e)
        {
            this.Refresh();
        }

        /// <summary>
        /// 设备恢复确认
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnResumptionConfirm_Click(object sender, EventArgs e)
        {
            try
            {
                if (CurrentRequestForm == null)
                    throw new Exception($"请选择要评估的维修单！");

                int AutoID = 0;
                if (int.TryParse(CurrentRequestForm["AutoID"] + "", out AutoID) && AutoID > 0)
                {
                    DeviceWarrantyRequestForm Item = GridDatas.FirstOrDefault(x => x.AutoID == AutoID);
                    if (Item == null)
                        throw new Exception($"获取维修单数据出错，请重试！");

                    if (Item != null && Item.MaintaionItems != null && Item != null && Item.MaintaionItems.SubmitBy > 0 &&
                       ((Item.InProduction && Item.EvaluatorItems != null && Item.EvaluatorItems.Count == 2) ||
                       (!Item.InProduction)) &&
                       ((Item.MaintaionItems.BeValidate && Item.MaintaionItems.ValidateBy > 0 && Item.MaintaionItems.Validate2By > 0)
                       || !Item.MaintaionItems.BeValidate)
                       && Item.RestorationConfirmationBy == 0
                       )
                    {
                        if (XtraMessageBoxHelper.Ask($"是否确认将维修单：<color=red>{Item.AutoID}</color>的状态修改为：<color=blue>已恢复</color>状态！") == DialogResult.OK)
                        {
                            splashScreenManager1.ShowWaitForm();

                            APIResponseData apiResponseData = Biz.HttpHelper.Instance.Post($"{ServiceUrl}{DeviceApiUrlConstValue.DeviceResumptionComfirm}?AutoID={AutoID}", "");
                            if (!apiResponseData.IsSuccess)
                                throw new Exception(apiResponseData.Message);

                            CloseWaitForm();
                            XtraMessageBoxHelper.Info("操作成功！");
                            InitializeGridDatas();
                        }
                    }
                    else
                    {
                        throw new Exception($"获取维修单状态出错，请重试！");
                    }
                }
                else
                {
                    throw new Exception($"获取评估单数据出错，请重试！");
                }
            }
            catch (Exception ex)
            {
                CloseWaitForm();
                XtraMessageBoxHelper.Error(ex.Message);
                InitializeGridDatas();
            }
        }
    }
}