using DevExpress.XtraBars.ToolbarForm;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.DXErrorProvider;
using DeviceRepair.Models;
using DeviceRepair.Models.Common;
using DeviceRepair.Models.DeviceMaintenance;
using DeviceRepair.Utils.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using TsSFCDevice.Client.Biz.Base.Utils;
using TsSFCDevice.Client.Biz.Impl;
using TsSFCDevice.Client.Launch.Common;
using TsSFCDevice.Client.Launch.Common.Email;

namespace TsSFCDevice.Client.Launch.Maintain
{
    public partial class DowntimeFormAdd : ToolbarForm
    {
        MailKitHelp mail = new MailKitHelp();
        public DeviceInformationInfo CurrentDeviceInfo = null;

        bool InProduction
        {
            get { return Convert.ToBoolean(rg_NeedValidate.EditValue); }
        }

        bool IsDown
        {
            get { return Convert.ToBoolean(rg_IsDown.EditValue); }
        }

        FieldsInfo WhereFailureOccurred
        {
            get { return (ddlWhereFailureOccurred.GetSelectedDataRow() as FieldsInfo); }
        }

        public DowntimeFormAdd()
        {
            InitializeComponent();

            this.Load += DowntimeFormAdd_Load;
        }

        private void DowntimeFormAdd_Load(object sender, EventArgs e)
        {
            IList<FieldsInfo> lst = CustomFieldRepository.Instance.GetDatas(new string[] { "WhereFailureOccurred" });
            ddlWhereFailureOccurred.Properties.DataSource = lst;
            ddlWhereFailureOccurred.Properties.DisplayMember = "FieldText";
            ddlWhereFailureOccurred.Properties.ValueMember = "AutoID";
            ddlWhereFailureOccurred.Properties.BestFitMode = DevExpress.XtraEditors.Controls.BestFitMode.BestFitResizePopup;
            if (ddlWhereFailureOccurred.Properties.DataSource != null && (ddlWhereFailureOccurred.Properties.DataSource as List<FieldsInfo>).Count > 0)
            {
                ddlWhereFailureOccurred.EditValue = (ddlWhereFailureOccurred.Properties.DataSource as List<FieldsInfo>)[0].AutoID;
            }
        }

        bool InitializeMail()
        {
            try
            {
                if (mail == null)
                {
                    mail = new MailKitHelp();
                }
                //发件服务器设置
                SysEmailConfigInfo config = CommonRepository.Instance.sysEmailConfigByModuleCode("DeviceWarranty");

                mail.FromMailAddress = config.EmailAddress;
                mail.SmtpAddress = config.SmtpServer;
                mail.IsSSL = config.SmtpSSL;
                mail.SmtpPort = config.SmtpPort;
                if (!config.EmailNoPass)
                {
                    mail.PassWord = DESEncrypt.Decrypt(config.EmailPassWord);
                }
                else
                {
                    mail.IsUseDefaultCredentials = true;
                }

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 故障发生时是否有产品在加工/测试在进行 - 是否开启批次号输入控件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rg_NeedValidate_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                txtBatch.Enabled = InProduction;
                if (!InProduction)
                    txtBatch.EditValue = "N/A";
                else
                    txtBatch.EditValue = "";
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 选择设备信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bbtnDevice_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                CurrentDeviceInfo = null;
                using (pageDeivceView view = new pageDeivceView())
                {
                    if (view.ShowDialog(this) == DialogResult.OK)
                    {
                        CurrentDeviceInfo = view.CurrentDeviceInfo;
                        bbtnDevice.EditValue = $"{view.CurrentDeviceInfo.EquipmentName}（{CurrentDeviceInfo.EquipmentID}）";
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 初始化验证控件
        /// </summary>
        private void InitializeValidationProvider()
        {
            try
            {
                List<BaseEdit> param = new List<BaseEdit> { textEdit2, bbtnDevice, ddlWhereFailureOccurred, memoEdit1 };
                foreach (var item in param)
                {
                    dxValidationProvider1.RemoveControlError(item);
                }
                dxValidationProvider1.RemoveControlError(txtBatch);


                dxValidationProvider1 = new DXValidationProvider();

                //实例化一个必填规则，错误提示为：该字段不能为空
                ConditionValidationRule required = new ConditionValidationRule("RequiredRule", ConditionOperator.IsNotBlank) { ErrorText = $"字段不能为空" };

                if (InProduction)
                {
                    param.Add(txtBatch);
                }

                for (int i = 0; i < param.Count; i++)
                {
                    dxValidationProvider1.SetValidationRule(param[i], required);
                    dxValidationProvider1.SetIconAlignment(param[i], ErrorIconAlignment.MiddleRight);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                InitializeValidationProvider();
                if (dxValidationProvider1.Validate())
                {
                    string cBatch = txtBatch.EditValue + "";
                    List<string> emailLst = new List<string>();


                    if (InProduction)
                    {
                        if (!SFCRepository.Instance.GetBatchInfoToStaff(cBatch))
                            throw new Exception("当前批次不存在！");

                        emailLst = MaintenanceRepository.Instance.SFC_Batch_PE_QE_Email(cBatch)?.ToList();
                    }

                    DeviceWarrantyRequestFormInfo deviceWarrantyRequestForm = new DeviceWarrantyRequestFormInfo
                    {
                        AutoID = CurrentDeviceInfo.AutoID,
                        EquipmentPK = CurrentDeviceInfo.AutoID,
                        EquipmentID = CurrentDeviceInfo.EquipmentID,
                        EquipmentName = CurrentDeviceInfo.EquipmentName,
                        Location = WhereFailureOccurred.AutoID,
                        LocationName = WhereFailureOccurred?.FieldText,
                        LocationGuid = WhereFailureOccurred.GUID,
                        InProduction = InProduction,
                        Batch = cBatch,
                        FaultSymptoms = memoEdit1.EditValue + "",
                        IsDown = IsDown,
                        ReceivingDep = "设备设施部",
                        FormVer = 1,
                    };

                    int MaintenanceAutoID = 0;
                    APIResponseData apiResponseData = MaintenanceRepository.Instance.ADD_DeviceDownForm_DATA(deviceWarrantyRequestForm, out MaintenanceAutoID);
                    if (!apiResponseData.IsSuccess)
                        throw new Exception(apiResponseData.Message);

                    try
                    {
                        if (emailLst.Count > 0 && InitializeMail())
                        {
                            mail.Title = $"有在生产的设备出现故障，请您尽快评估故障状态！";
                            mail.IsBodyHtml = true;
                            System.Text.StringBuilder builder = new System.Text.StringBuilder();
                            builder.AppendLine($"<p>在 {ddlWhereFailureOccurred.Text} 发起的编号为：{MaintenanceAutoID} 的报修单，设备 {CurrentDeviceInfo.EquipmentName}（{CurrentDeviceInfo.EquipmentID}） 发生故障，{(deviceWarrantyRequestForm.InProduction ? "存有产品在加工中，产品批次号：" + deviceWarrantyRequestForm.Batch : "")} ，请您尽快评估故障情况。</p>");
                            builder.AppendLine($"<p>发起人：生产部 - {Utility.SystemRuntimeInfo.CurrentUser.UserName}</p>");
                            mail.Body = builder.ToString();
                            string msgResult = "";
                            //收件人
                            mail.ToMailAddress = emailLst.ToArray();
                            MailKitHelp.SendStatus ss = mail.Send(out msgResult);
                        }
                    }
                    catch (Exception ex)
                    {
                        XtraMessageBoxHelper.Warn($"新增数据成功，邮件发送失败，失败原因:{ex.Message}");
                    }

                    DialogResult = DialogResult.OK;
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        private void txtBatch_Properties_KeyPress(object sender, KeyPressEventArgs e)
        {
            //增加了自动切换大写，控制只能输入大写字母、数字、回退按钮、复制快捷键(复制的数据没有控制格式)
            e.KeyChar = Convert.ToChar(e.KeyChar.ToString().ToUpper());
        }
    }
}