using DevExpress.XtraBars.ToolbarForm;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.DXErrorProvider;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using TsSFCDeivceClient.Common;
using TsSFCDeivceClient.Email;
using TsSFCDeivceClient.Model;
using TsSFCDeivceClient.Model.Common;
using TsSFCDeivceClient.Model.DeviceWarrantyRequest;

namespace TsSFCDeivceClient
{
    public partial class DowntimeFormAdd : ToolbarForm
    {
        MailKitHelp mail = new MailKitHelp();
        string emailPattern = @"^(?("")("".+?(?<!\\)""@)|(([a-zA-Z0-9\-]+\.)+[a-zA-Z]{2,}))$";
        public DeviceInfo CurrentDeviceInfo = 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();
            }
        }
        bool InProduction
        {
            get { return Convert.ToBoolean(rg_NeedValidate.EditValue); }
        }

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

        int WhereFailureOccurred
        {
            get { return Convert.ToInt32(ddlWhereFailureOccurred.EditValue); }
        }

        public DowntimeFormAdd()
        {
            InitializeComponent();

            this.Load += DowntimeFormAdd_Load;
        }

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



            APIResponseData apiResponseData = Biz.HttpHelper.Instance.Get($"{ServiceUrl}{DeviceApiUrlConstValue.GetWhereFailureOccurred}");

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

            List<FieldsInfo> lst = apiResponseData.ToDeserializeObject<List<FieldsInfo>>();
            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();
                }
                //发件服务器设置

                // mail.medtronic.com
                mail.SmtpAddress = m_Config.AppSettings.Settings["SmtpServer"].Value.Trim();

                // false
                mail.IsSSL = bool.Parse(m_Config.AppSettings.Settings["SmtpSSL"].Value.Trim());

                // 25
                mail.SmtpPort = int.Parse(m_Config.AppSettings.Settings["SmtpPort"].Value.Trim());

                //是否启用无密码模式
                if (bool.Parse(m_Config.AppSettings.Settings["EmailNoPass"].Value.Trim()))
                {
                    mail.IsUseDefaultCredentials = true;
                }
                else
                    mail.PassWord = m_Config.AppSettings.Settings["EmailPassWord"].Value.Trim();

                mail.FromMailAddress = m_Config.AppSettings.Settings["EmailAddress"].Value.Trim();

                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";
            }
            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() == DialogResult.OK)
                    {
                        CurrentDeviceInfo = view.CurrentDeviceInfo;
                        bbtnDevice.EditValue = view.CurrentDeviceInfo.EquipmentName;
                    }
                }
            }
            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 + "";

                    // 有在生产的批次
                    DataTable dtRtn = null;
                    if (InProduction)
                    {
                        JObject js = JObject.Parse(Runtime.inParams);
                        js.Add("Batch", cBatch);

                        APIResponseData apiResponseData2 = Biz.HttpHelper.Instance.Post($"{ServiceUrl}{DeviceApiUrlConstValue.GetBatchInfoToStaff}", JsonConvert.SerializeObject(new { LoginCode = Runtime.CurrentUser.UserCode, Password = Runtime.CurrentUser.Password, inParams = js.ToString() }));
                        if (!apiResponseData2.IsSuccess)
                            throw new Exception(apiResponseData2.Message);

                        dtRtn = (DataTable)apiResponseData2.Data;
                    }

                    DeviceWarrantyRequestForm deviceWarrantyRequestForm = new DeviceWarrantyRequestForm
                    {
                        EquipmentPK = CurrentDeviceInfo.AutoID,
                        EquipmentID = CurrentDeviceInfo.EquipmentID,
                        EquipmentName = CurrentDeviceInfo.EquipmentName,
                        Location = WhereFailureOccurred,
                        LocationName = ddlWhereFailureOccurred.Text?.Trim(),
                        InProduction = InProduction,
                        Batch = cBatch,
                        FaultSymptoms = memoEdit1.EditValue + "",
                        IsDown = IsDown,
                        ReceivingDep = "设备设施部"
                    };

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

                    List<string> EmailList = new List<string>();
                    if (dtRtn != null && dtRtn.Rows.Count > 0 && dtRtn.Columns.Contains("Product") && dtRtn.Columns.Contains("Technology"))
                    {
                        string Product = dtRtn.Rows[0]["Product"] + "";
                        string Technology = dtRtn.Rows[0]["Technology"] + "";

                        apiResponseData = Biz.HttpHelper.Instance.Post($"{ServiceUrl}{DeviceApiUrlConstValue.ProductResourceAllocationsGet}", deviceWarrantyRequestForm.toJson());
                        if (!apiResponseData.IsSuccess)
                            throw new Exception(apiResponseData.Message);

                        List<dynamic> staffResourceAllocations = apiResponseData.ToDeserializeObject<List<dynamic>>();
                        //IList<StaffResourceAllocations> staffResourceAllocations = p_InspRespos.ProductResourceAllocationsGet(Product, Technology);
                        if (staffResourceAllocations != null && staffResourceAllocations.Count > 0)
                        {
                            foreach (var item in staffResourceAllocations)
                            {
                                if ((int)item.StaffPost == 0 || (int)item.StaffPost == 1)
                                {
                                    if (!string.IsNullOrWhiteSpace(item.StaffEMail) && Regex.IsMatch(item.StaffEMail, emailPattern))
                                    {
                                        EmailList.Add(item.StaffEMail);
                                    }

                                    if (!string.IsNullOrWhiteSpace(item.StaffResource?.EMail ?? ""))
                                    {
                                        EmailList.Add(item.StaffResource.EMail);
                                    }
                                }
                            }
                        }
                    }

                    if (EmailList.Count > 0 && InitializeMail())
                    {
                        mail.Title = $"有在生产的设备出现故障，请您尽快评估故障状态！";
                        mail.IsBodyHtml = true;
                        System.Text.StringBuilder builder = new System.Text.StringBuilder();
                        builder.AppendLine($"<p>在 {ddlWhereFailureOccurred.Text} 的 {CurrentDeviceInfo.EquipmentName}（{CurrentDeviceInfo.EquipmentID}） 发生故障，{(deviceWarrantyRequestForm.InProduction ? "存有产品在加工中，产品批次号：" + deviceWarrantyRequestForm.Batch : "")} ，请您尽快评估故障情况。</p>");
                        builder.AppendLine($"<p>发起人：生产部 - {Runtime.CurrentUser.UserName}</p>");
                        mail.Body = builder.ToString();
                        string msgResult = "";
                        //收件人
                        mail.ToMailAddress = EmailList.ToArray();
                        MailKitHelp.SendStatus ss = mail.Send(out msgResult);
                    }

                    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());
        }
    }
}