using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FineUIPro.Web.common;
using BLL.Common;
using BLL;

namespace FineUIPro.Web.SES
{
    public partial class CSafePunishEdit : PageBase
    {
        #region 定义项
        /// <summary>
        /// 主键
        /// </summary>
        public string PunishmentId
        {
            get
            {
                return (string)ViewState["PunishmentId"];
            }
            set
            {
                ViewState["PunishmentId"] = value;
            }
        }
        #endregion
        #region 加载
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.btnClose.OnClientClick = ActiveWindow.GetHideReference();
                string view = Request.Params["view"];
               
                var role = BLL.Sys_RoleService.GetRole(CurrUser.RoleId);
                if (role != null && role.RoleName == "Contract Administrator")
                {
                    txtSESNo.Required = true;
                    txtCompletionDate.Required = true;
                    txtSESNo.Enabled = true;
                    txtCompletionDate.Enabled = true;
                }
                else
                {
                    txtSESNo.Required = false;
                    txtCompletionDate.Required = false;
                    txtSESNo.Enabled = false;
                    txtCompletionDate.Enabled = false;
                }

                // BLL.SESRelatedDataService.InitFONoDropDownList(this.drpFO_No, true);//合同号
                BLL.ContractorService.InitDropDownList(drpContractor, true); //承包商;  
                BLL.DepartService.InitDepartToWhere(this.drpBYC_RU, true);//BYC负责部门
                BLL.Sys_UserService.InitUserDropDownList(this.drpViolationInspector, true);//违章检查人
                txtViolationRelatedSes.Enabled = false;

                PunishmentId = Request.Params["punishmentId"];
                if (!string.IsNullOrEmpty(PunishmentId))
                {
                    Model.View_EMC_Punishment punishment = BLL.PunishmentService.GetPunishmentViewById(PunishmentId);
                    Model.EMC_Punishment pun = BLL.PunishmentService.GetPunishmentById(PunishmentId);
                    if (punishment != null)
                    {
                        this.txtPunishDate.Text = punishment.PunishDate != null ? string.Format("{0:yyyy-MM-dd}", punishment.PunishDate) : "";
                        this.txtPunishTime.Text = punishment.PunishDate != null ? punishment.PunishDate.Value.ToShortTimeString() : "";

                        if (!string.IsNullOrEmpty(punishment.ContractorId))
                        {
                            this.drpContractor.SelectedValue = punishment.ContractorId;
                            BLL.SESRelatedDataService.InitFONoDropDownList(this.drpFO_No, drpContractor.SelectedValue, true);//合同号
                            this.drpFO_No.SelectedValue = punishment.FO_NO;
                        }
                        
                        this.txtDiscispline.Text = punishment.Discipline;
                        this.txtLocation.Text = punishment.Location;
                        this.txtDescription.Text = punishment.Description;

                        this.txtCompany.Text = punishment.Company.HasValue ? punishment.Company.ToString() : "";
                        this.txtIndividual.Text = punishment.Individual.HasValue ? punishment.Individual.ToString() : "";
                        this.txtBackcharge.Text = punishment.Backcharge.HasValue ? punishment.Backcharge.Value.ToString("0.00") : "";

                        if (pun != null && !string.IsNullOrEmpty(pun.ViolationDegree))
                        {
                            drpViolationDegree.SelectedValue = pun.ViolationDegree;
                        }
                        
                        txtContractAdmin.Text = punishment.Contract_Admin;
                        txtMainCoordinator.Text = punishment.Main_Coordinator;
                        txtMCDept.Text = punishment.MCDept;
                        txtUserRepresentative.Text = punishment.User_Representative;
                        if (punishment.SelectYesNo != null)
                        {
                            drpSelectYesNo.SelectedValue = punishment.SelectYesNo == true ? "True" : "False";
                        }
                        else
                        {
                            drpSelectYesNo.SelectedValue = "";
                        }

                        txtDef.Text= punishment.Def;

                        if (!string.IsNullOrEmpty(punishment.BYC_RU))
                        {
                            this.drpBYC_RU.SelectedValue = punishment.BYC_RU;
                        }
                        if (!string.IsNullOrEmpty(punishment.Violation_Inspector))
                        {
                            this.drpViolationInspector.SelectedValue = punishment.Violation_Inspector;
                            var user = BLL.Sys_UserService.GetUsersByUserId(punishment.Violation_Inspector);
                            string depName = BLL.DepartService.GetDepartNameById(user.DepartId);
                            txtInspectionDep.Text = depName;
                        }

                        if (this.CurrUser.DepartId == punishment.BYC_RU || this.CurrUser.Account==Const.Gly)
                        {
                            btnSave.Hidden = false;
                            txtViolationRelatedSes.Enabled = true;
                            drpSelectYesNo.Enabled = true;
                            txtDef.Enabled = true;
                        }
                        else
                        {
                            btnSave.Hidden = true;
                            txtViolationRelatedSes.Enabled = false;
                            drpSelectYesNo.Enabled = false;
                            txtDef.Enabled = false;
                        }

                        var puList = (from x in Funs.DB.EMC_Punishment where x.Flag == "1" && x.BYC_RU != null && x.BYC_RU != "NA" select x.BYC_RU).Distinct().ToArray();
                        if (this.CurrUser.DepartId != null && puList.Contains(this.CurrUser.DepartId))
                        {
                            drpViolationInspector.Hidden = true;
                            txtInspectionDep.Hidden = true;
                        }

                        this.txtCompletionDate.Text = punishment.CompletionDate != null ? string.Format("{0:yyyy-MM-dd}", punishment.CompletionDate) : "";
                        this.txtSESNo.Text = punishment.SES_No;
                        txtViolationRelatedSes.Text = punishment.ViolationRelatedSes;
                    }
                }
                else
                {
                   
                }

                if (view == "1")
                {
                    this.btnSave.Hidden = true;
                }
                else
                {
                    GetButtonPower();//按钮权限
                }
            }
        }
        #endregion

        #region 保存
        protected void PageManager1_CustomEvent(object sender, CustomEventArgs e)
        {
            if (e.EventArgument == "SaveConfirm_OK")
            {
                Save();
            }
            else if (e.EventArgument == "SaveConfirm_Cancel")
            {
                ShowNotify("执行了取消操作!");
            }
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (this.drpContractor.SelectedValue == BLL.Const._Null)
            {
                Alert.ShowInTop("Please select Contractor!", MessageBoxIcon.Warning);
                return;
            }

            if (this.drpFO_No.SelectedValue == BLL.Const._Null)
            {
                Alert.ShowInTop("Please select Contract No.!", MessageBoxIcon.Warning);
                return;
            }
            if (this.drpViolationInspector.SelectedValue == BLL.Const._Null)
            {
                Alert.ShowInTop("Please select Violation Inspector!", MessageBoxIcon.Warning);
                return;
            }

            if (this.drpBYC_RU.SelectedValue == BLL.Const._Null)
            {
                Alert.ShowInTop("Please select BYC Resp. Dept.!", MessageBoxIcon.Warning);
                return;
            }

            if (!string.IsNullOrEmpty(PunishmentId))
            {
                var punishment = BLL.PunishmentService.GetPunishmentById(PunishmentId);
                if ((this.CurrUser.DepartId == punishment.BYC_RU || this.CurrUser.Account == Const.Gly) && this.drpSelectYesNo.SelectedValue == "")
                {
                    Alert.ShowInTop("请选择是否有关联SES!", MessageBoxIcon.Warning);
                    return;
                }
            }
            if (PunishmentId == null)
            {
                PunishmentId = string.Empty;
            }

            if (BLL.PunishmentService.IsExistSES_NO(PunishmentId, this.txtSESNo.Text.Trim(), "1"))
            {
                Alert.ShowInTop("The Backcharge SES NO. already exists!");
                return;
            }

            if (txtViolationRelatedSes.Text != string.Empty && drpFO_No.SelectedValue != Const._Null)
            {
                var sesList = from x in Funs.DB.FC_SESReport where x.FO == drpFO_No.SelectedValue select x.SES_No;
                if (txtViolationRelatedSes.Text.Length != 10)
                {
                    PageContext.RegisterStartupScript(Confirm.GetShowReference("SES NO:" + txtViolationRelatedSes.Text + "长度不等10位 "  + ", 确认(继续) / 取消(退出)",
                                                       String.Empty,
                                                       MessageBoxIcon.Question,
                                 PageManager1.GetCustomEventReference(false, "SaveConfirm_OK"),
                                 PageManager1.GetCustomEventReference("SaveConfirm_Cancel")));
                }
                else
                {
                    if (!sesList.Contains(txtViolationRelatedSes.Text))
                    {
                        PageContext.RegisterStartupScript(Confirm.GetShowReference("SES NO:" + txtViolationRelatedSes.Text + " 不属于合同:" + drpFO_No.SelectedValue + ", 确认(继续) / 取消(退出)",
                                                       String.Empty,
                                                       MessageBoxIcon.Question,
                                 PageManager1.GetCustomEventReference(false, "SaveConfirm_OK"),
                                 PageManager1.GetCustomEventReference("SaveConfirm_Cancel")));

                    }
                    else
                    {
                        Save();
                    }
                }
            }
            else
            {
                Save();
            }
            
        }

        private void Save()
        {
            Model.EMC_Punishment punishment = new Model.EMC_Punishment();
            punishment.PunishDate = Funs.GetNewDateTime(this.txtPunishDate.Text.Trim() + " " + txtPunishTime.Text.Trim());
            punishment.FO_NO = drpFO_No.SelectedValue;
            if (txtSESNo.Text.Trim() != string.Empty)
            {
                punishment.SES_No = txtSESNo.Text.Trim();
            }
            punishment.Location = txtLocation.Text.Trim();
            punishment.Description = txtDescription.Text.Trim();
            if (txtCompany.Text != string.Empty)
            {
                punishment.Company = Convert.ToDecimal(txtCompany.Text.Trim());
            }
            if (txtIndividual.Text != string.Empty)
            {
                punishment.Individual = Convert.ToDecimal(txtIndividual.Text.Trim());
            }
            punishment.ViolationDegree = drpViolationDegree.SelectedValue;
            if (drpBYC_RU.SelectedValue != Const._Null)
            {
                punishment.BYC_RU = drpBYC_RU.SelectedValue;
            }
            if (drpViolationInspector.SelectedValue != Const._Null)
            {
                punishment.Violation_Inspector = drpViolationInspector.SelectedValue;
            }
            if (drpSelectYesNo.SelectedValue != "")
            {
                punishment.SelectYesNo = Convert.ToBoolean(drpSelectYesNo.SelectedValue);
            }
            if (txtDef.Text != "")
            {
                punishment.Def = txtDef.Text.Trim();
            }
            punishment.ViolationRelatedSes = txtViolationRelatedSes.Text.Trim();
            punishment.CompletionDate = Funs.GetNewDateTime(this.txtCompletionDate.Text.Trim());
            punishment.Flag = "1";

            if (!string.IsNullOrEmpty(PunishmentId))
            {
                punishment.PunishmentId = PunishmentId;
                BLL.PunishmentService.UpdatePunishment(punishment);
                BLL.Sys_LogService.AddLog(this.CurrUser.UserId, "Modify Contractor Safety Punishment!");
            }
            else
            {
                PunishmentId = SQLHelper.GetNewID(typeof(Model.EMC_Punishment));
                punishment.PunishmentId = PunishmentId;
                punishment.CreateDate = DateTime.Now;
                BLL.PunishmentService.AddPunishment(punishment);
                BLL.Sys_LogService.AddLog(this.CurrUser.UserId, "Add Contractor Safety Punishment!");
            }

            #region 承包商EHSS违规关联SES号的填写通知
            var vses = (from x in Funs.DB.EMC_Punishment
                        where (x.RelatedSesMailIsSend == null || x.RelatedSesMailIsSend == false)
                              && x.BYC_RU != null && x.BYC_RU.ToUpper() != "NA" && x.Flag == "1"
                         && x.PunishmentId== punishment.PunishmentId
                        select x).ToList();
            if (vses.Count() > 0)
            {
                Model.EmailPop pops = Funs.DB.EmailPop.FirstOrDefault(x => x.EmailID == BLL.Const.EmailPopId);
                if (pops == null)
                {
                    return;
                }

                foreach (var ses in vses)
                {
                    string[] mailTo = null;
                    string[] mailCC = null;
                    string resultMessage = "";

                    var emailTemplate = Funs.DB.SendEmailTemplate.Where(x => x.EmailName.Contains("承包商EHSS违规关联SES号的填写通知"));
                    if (emailTemplate.Count() > 0)
                    {
                        var dep = BLL.DepartService.GetDepartById(ses.BYC_RU);
                        if (dep != null && !string.IsNullOrEmpty(dep.DepartLeader))
                        {
                            var userTo = from x in Funs.DB.Sys_User
                                         where x.UserId == dep.DepartLeader
                                               && x.Email != null && x.Email != ""
                                         select x;
                            if (userTo != null)
                            {
                                mailTo = userTo.Select(x => x.Email).ToArray();
                            }

                            string contractor = string.Empty;
                            var fo = BLL.SESRelatedDataService.GetSESRelatedDataByFoNo(ses.FO_NO);
                            if (fo != null)
                            {
                                var userCC = from x in Funs.DB.Sys_User
                                             where (x.UserId == fo.Contract_Admin || x.UserId == fo.Main_Coordinator)
                                                   && x.Email != null && x.Email != ""
                                             select x;
                                mailCC = userCC.Select(x => x.Email).Distinct().ToArray();

                                var con = Funs.DB.View_Contractor_DropDownValue.FirstOrDefault(x => x.ContractorId == fo.Contractor);
                                if (con != null)
                                {
                                    contractor = con.Contractor;
                                }
                            }

                            if (mailTo.Length > 0)
                            {
                                NameValueCollection myPram = new NameValueCollection();
                                myPram.Add("ContractNo", fo.FO_NO);
                                myPram.Add("Contractor", contractor);
                                myPram.Add("Date", ses.PunishDate != null ? ses.PunishDate.Value.ToString("yyyy-MM-dd") : "");
                                myPram.Add("Time", ses.PunishDate != null ? ses.PunishDate.Value.ToString("HH:mm") : "");
                                myPram.Add("Violation Description", ses.Description);
                                bool result = MailHelper.SendPunishSesMail(pops, myPram, "承包商EHSS违规关联SES号的填写通知", mailTo, mailCC, out resultMessage);

                                if (result)
                                {
                                    ses.RelatedSesMailIsSend = true;
                                    Funs.DB.SubmitChanges();
                                }
                            }
                        }
                    }
                }
            }
            #endregion
            ShowNotify("Save successfully!", MessageBoxIcon.Success);
            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
        }
        #endregion

        protected void drpContractor_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.drpContractor.SelectedValue != BLL.Const._Null)
            {
                this.drpFO_No.Items.Clear();
                BLL.SESRelatedDataService.InitFONoDropDownList(this.drpFO_No, drpContractor.SelectedValue, true);//合同号
                drpFO_No.SelectedValue = BLL.Const._Null;
                txtDiscispline.Text = string.Empty;
            }
        }

        protected void drpFO_No_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (drpFO_No.SelectedValue != Const._Null)
            {
                string foNO = drpFO_No.SelectedValue;
                Model.View_FC_SESRelatedData fc = BLL.SESRelatedDataService.GetSESRelatedDataViewByFO(foNO);
                if (fc != null)
                {
                    txtDiscispline.Text = fc.Discipline;
                    txtContractAdmin.Text = fc.Contract_Admin;
                    txtMainCoordinator.Text = fc.Main_Coordinator;
                    txtUserRepresentative.Text = fc.User_Representative;
                    txtMCDept.Text = fc.MCDept;
                }
            }
        }

        protected void drpViolationInspector_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (drpViolationInspector.SelectedValue != Const._Null)
            {
                string manId = drpViolationInspector.SelectedValue;
                var user = BLL.Sys_UserService.GetUsersByUserId(manId);
                string depName = BLL.DepartService.GetDepartNameById(user.DepartId);
                txtInspectionDep.Text = depName;
            }
        }

        protected void drpSelectYesNo_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (drpSelectYesNo.SelectedValue == "True")
            {
                txtViolationRelatedSes.Readonly = false;
                txtViolationRelatedSes.ShowRedStar = true;
                txtViolationRelatedSes.Required = true;
            }
            else
            {
                txtViolationRelatedSes.Readonly = true;
                txtViolationRelatedSes.ShowRedStar = false;
                txtViolationRelatedSes.Required = false;
                txtDef.ShowRedStar = true;
                txtDef.Required = true;
            }
        }

        protected void txtPunish_OnTextChanged(object sender, EventArgs e)
        {
            decimal? numCompany = 0;
            decimal? numIndividual = 0;
            if (txtCompany.Text != string.Empty)
            {
                numCompany = Funs.GetNewDecimal(txtCompany.Text);
            }
            if (txtIndividual.Text != string.Empty)
            {
                numIndividual = Funs.GetNewDecimal(txtIndividual.Text);
            }

            txtBackcharge.Text = (numCompany + numIndividual).Value.ToString("0.00");
        }

        private void SetReadonly(bool read)
        {
            txtPunishDate.Enabled = read;
            txtPunishTime.Enabled = read;
            drpContractor.Enabled = read;
            drpFO_No.Enabled = read;
            txtDiscispline.Enabled = read;
            txtLocation.Enabled = read;
            txtDescription.Enabled = read;
            txtCompany.Enabled = read;
            txtIndividual.Enabled = read;
            txtBackcharge.Enabled = read;
            drpViolationDegree.Enabled = read;
            txtContractAdmin.Enabled = read;
            txtMainCoordinator.Enabled = read;
            txtMCDept.Enabled = read;
            txtUserRepresentative.Enabled = read;
            drpBYC_RU.Enabled = read;
            drpViolationInspector.Enabled = read;
            txtInspectionDep.Enabled = read;
            txtSESNo.Enabled = read;
            txtCompletionDate.Enabled = read;
        }

        #region 权限设置
        /// <summary>
        /// 菜单按钮权限
        /// </summary>
        private void GetButtonPower()
        {
            var buttonList = BLL.CommonService.GetAllButtonList(this.CurrUser.UserId, BLL.Const.CSafePunishMenuId);
            if (buttonList.Count() > 0)
            {
                if (buttonList.Contains(BLL.Const.BtnSave))
                {
                    this.btnSave.Hidden = false;
                }
                else
                {
                    SetReadonly(false);
                }
            }
           
        }
        #endregion
    }
}