using DeviceRepair.Models;
using DeviceRepairAndOptimization.Biz;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using DeviceRepairAndOptimization.Common;

namespace DeviceRepairAndOptimization.Pages.Maintain
{
    public partial class ucMaintenance : UserControl
    {
        DeviceWarrantyRequestFormView RequestForm;

        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 ucMaintenance(DeviceWarrantyRequestFormView requestForm)
        {
            InitializeComponent();

            RequestForm = requestForm;
            this.Load += UcMaintenance_Load;
        }

        private void UcMaintenance_Load(object sender, EventArgs e)
        {
            foreach (var item in this.layoutControlGroup1.Items)
            {
                if (item is DevExpress.XtraLayout.LayoutControlItem && (item != layoutControlItem5 || item != labelControl13))
                {
                    (item as DevExpress.XtraLayout.LayoutControlItem).CustomDraw += PageMaintainView_CustomDraw;
                }
            }

            layoutControlGroup1.ViewInfo.OwnerILayoutControl.AllowCustomizationMenu = false;
            layoutControlGroup2.ViewInfo.OwnerILayoutControl.AllowCustomizationMenu = false;
            layoutControlGroup3.ViewInfo.OwnerILayoutControl.AllowCustomizationMenu = false;

            InitializeDataDisplay();
        }

        #region 内容边框

        private void PageMaintainView_CustomDraw(object sender, DevExpress.XtraLayout.ItemCustomDrawEventArgs e)
        {
            if ((sender as DevExpress.XtraLayout.LayoutControlItem).ControlName == labelControl13.Name)
            {
                Point plt = new Point(e.Bounds.X, e.Bounds.Y);
                Point plb = new Point(e.Bounds.X, e.Bounds.Y + e.Bounds.Height);
                Point prt = new Point(e.Bounds.X + e.Bounds.Width, e.Bounds.Y);
                Point prb = new Point(e.Bounds.X + e.Bounds.Width, e.Bounds.Y + e.Bounds.Height);

                e.Graphics.DrawLine(Pens.Gray, new Point(e.Bounds.X, e.Bounds.Y), new Point(e.Bounds.X, e.Bounds.Y + e.Bounds.Height));   // 左
                e.Graphics.DrawLine(Pens.Gray, new Point(e.Bounds.X + e.Bounds.Width, e.Bounds.Y), new Point(e.Bounds.X + e.Bounds.Width, e.Bounds.Y + e.Bounds.Height));   // 右
                e.Graphics.DrawLine(Pens.Gray, new Point(e.Bounds.X, e.Bounds.Y), new Point(e.Bounds.X + e.Bounds.Width, e.Bounds.Y));   // 上
            }
            else if ((sender as DevExpress.XtraLayout.LayoutControlItem).ControlName == layoutControlItem15.Name || (sender as DevExpress.XtraLayout.LayoutControlItem).ControlName == disInProduction.Name)
            {
                e.Graphics.DrawLine(Pens.Gray, new Point(e.Bounds.X, e.Bounds.Y), new Point(e.Bounds.X, e.Bounds.Y + e.Bounds.Height));   // 左
                e.Graphics.DrawLine(Pens.Gray, new Point(e.Bounds.X + e.Bounds.Width, e.Bounds.Y), new Point(e.Bounds.X + e.Bounds.Width, e.Bounds.Y + e.Bounds.Height));   // 右
                e.Graphics.DrawLine(Pens.Gray, new Point(e.Bounds.X, e.Bounds.Y + e.Bounds.Height), new Point(e.Bounds.X + e.Bounds.Width, e.Bounds.Y + e.Bounds.Height));   // 上
            }
            else
            {
                e.Graphics.DrawRectangle(Pens.Gray, e.Bounds);
            }
        }

        #endregion

        void InitializeDataDisplay()
        {
            disCreatDeptName.Text = "生产部 - " + RequestForm.CreatorName;
            disCreatOn.Text = RequestForm.CreatOn.HasValue ? RequestForm.CreatOn.Value.ToString("yyyy/MM/dd HH:mm:ss") : "";
            disEquipmentID.Text += RequestForm.EquipmentID;
            disEquipmentName.Text += RequestForm.EquipmentName;
            disFaultSymptoms.Text = RequestForm.FaultSymptoms;
            if (RequestForm.InProduction)
            {
                disInProduction.Text = $"Yes, Product Lot/Testing Order产品批号/检测任务号\r\n{RequestForm.Batch}";
            }
            else
            {
                disInProduction.Text = $"No";
            }

            disReceivingDep.Text = RequestForm.ReceivingDep;

            if (RequestForm.EvaluatorItems != null && RequestForm.EvaluatorItems.Count > 0)
            {
                var PEItem = RequestForm.EvaluatorItems.Where(x => x.EvaluatorCode == "PE").FirstOrDefault();
                if (PEItem != null)
                {
                    disEvaluatorName_QA.Text = $"{PEItem.Description} - {PEItem.CreatorName}";
                }

                var QEItem = RequestForm.EvaluatorItems.Where(x => x.EvaluatorCode == "QE").FirstOrDefault();
                if (QEItem != null)
                {
                    disEvaluatorName_EA.Text = $"{QEItem.Description} - {QEItem.CreatorName}";
                }
            }

            if (disEvaluatorName_QA.Text.Length == 0)
                disEvaluatorName_QA.Text = "N/A";

            if (disEvaluatorName_EA.Text.Length == 0)
                disEvaluatorName_EA.Text = "N/A";

            // 故障发生地
            disLocation.Text = RequestForm.LocationName;

            if (RequestForm.MaintaionItems != null && RequestForm.MaintaionItems.SubmitBy > 0)
            {
                APIResponseData apiResponseData = FieldsManager.Instance.GetQuery("SymptomlDistinction,Maintenance,Accessories");
                if (!apiResponseData.IsSuccess)
                    throw new Exception(apiResponseData.Message);

                List<FieldsInfo> SelectionDatas = apiResponseData.ToDeserializeObject<List<FieldsInfo>>();
                if (SelectionDatas != null)
                {
                    Dictionary<int, FieldsInfo> keyValuePairs = SelectionDatas.ToDictionary(x => x.AutoID, x => x);

                    // 现象区分
                    labelControl8.Text = keyValuePairs.ContainsKey(RequestForm.MaintaionItems.SymptomlDistinction) ? keyValuePairs[RequestForm.MaintaionItems.SymptomlDistinction].FieldText : "";

                    // 维修方式
                    labelControl11.Text = keyValuePairs.ContainsKey(RequestForm.MaintaionItems.Maintenance) ? keyValuePairs[RequestForm.MaintaionItems.Maintenance].FieldText : "";

                    // 开始时间
                    labelControl14.Text = RequestForm.MaintaionItems.MaintainStartTime.ToString("yyyy/MM/dd HH:mm:ss");

                    // 结束时间
                    labelControl15.Text = RequestForm.MaintaionItems.MaintainEndTime.ToString("yyyy/MM/dd HH:mm:ss");

                    // 故障原因
                    labelControl29.Text = RequestForm.MaintaionItems.MaintainCause;

                    // 维修内容
                    labelControl30.Text = RequestForm.MaintaionItems.MaintainContent;

                    //配件
                    if (RequestForm.MaintaionItems.AccessoriesItems != null && RequestForm.MaintaionItems.AccessoriesItems.Count > 0)
                    {
                        System.Text.StringBuilder builder = new System.Text.StringBuilder();
                        foreach (DeviceWarrantyRequestAccessoriesInfo item in RequestForm.MaintaionItems.AccessoriesItems)
                        {
                            builder.Append($"{item.FieldName} x {item.AccessoriesCount};");
                        }
                        labelControl31.Text = builder.ToString();
                    }

                    // 维修人
                    labelControl32.Text = UserMapping[RequestForm.MaintaionItems.SubmitBy];

                    // 是否需要验证
                    if (RequestForm.MaintaionItems.BeValidate)
                    {
                        labelControl33.Text = $"Yes   需要，Validation ID验证编号：<u>{RequestForm.MaintaionItems.ValidateNo}</u>";
                    }
                    else
                    {
                        labelControl33.Text = $"No    不需要， Rational理由：<u>{RequestForm.MaintaionItems.Reason}</u>";
                    }

                    if (RequestForm.MaintaionItems.ValidateBy != 0)
                    {
                        // 设备恢复确认
                        string ValidateText = $"{UserMapping[RequestForm.MaintaionItems.ValidateBy]} / {RequestForm.MaintaionItems.ValidateOn.ToString("yyyy-MM-dd HH:mm:ss")}    ";
                        if (RequestForm.MaintaionItems.Validate2By != 0)
                            ValidateText += $"{UserMapping[RequestForm.MaintaionItems.Validate2By]} / { RequestForm.MaintaionItems.Validate2On.ToString("yyyy-MM-dd HH:mm:ss") }";

                        labelControl34.Text = ValidateText;
                    }

                    // 生产部 - 设备恢复确认
                    if (RequestForm.RestorationConfirmationBy > 0)
                    {
                        labelControl35.Text = $"{RequestForm.RestorationConfirmationOnName} / {RequestForm.RestorationConfirmationOn.Value.ToString("yyyy-MM-dd HH:mm:ss")}";
                    }

                    DateTime FormSubDate = RequestForm.CreatOn.Value;
                    TimeSpan timeDifference = RequestForm.MaintaionItems.MaintainEndTime - RequestForm.MaintaionItems.MaintainStartTime;

                    // 总修复时间
                    labelControl26.Text = $"{timeDifference.Days}天/{(timeDifference.Hours)}小时/{(timeDifference.Minutes)}分钟/{timeDifference.Seconds}秒";

                    // 总停机时间
                    timeDifference = RequestForm.MaintaionItems.MaintainEndTime - FormSubDate;
                    labelControl27.Text = $"{timeDifference.Days}天/{(timeDifference.Hours)}小时/{(timeDifference.Minutes)}分钟/{timeDifference.Seconds}秒";
                }
            }
        }
    }
}
