using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using BLL;


namespace FineUIPro.Web.Design
{
    public partial class IssuedNotice : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.btnClose.OnClientClick = ActiveWindow.GetHideReference();
                BLL.Sys_UserService.InitUserDropDownList(this.drpIssuedMan, true);//提出人
                BLL.Sys_UserService.InitUserDropDownList(this.drpReceivedMan, true);// 接收人
                BLL.Sys_UserService.InitUserDropDownList(this.drpProjectMan, true);// 接收人

                string designInputId = Request.Params["designInputId"];
                string noticeId = Request.Params["designNoticeId"];
                string flag = Request.Params["flag"];

                if (!string.IsNullOrEmpty(designInputId) && (flag == "add" || flag== "sup"))
                {
                    var input = BLL.DesignInputService.GetDesignInputById(designInputId);
                    var project = EProjectService.GeteProjectById(input.EProjectId);
                    txtJobNo.Text = project.ProjectControl_JobNo;
                    txtJobTitle.Text = project.ProjectControl_JobTitle;
                    txtDesignStage.Text = "IFC";
                    txtMutualIssuedName.Text = input.DesignInputChName + " " + input.DesignInputEnName;
                    txtPlanMutualIssuedDate.Text = string.Format("{0:yyyy-MM-dd}", (input.PlanStartDate));
                    txtActMutualIssuedDate.Text= string.Format("{0:yyyy-MM-dd}", (input.PlanEndDate));
                    txtIssuedDiscipline.Text = input.IssuedDiscipline;
                    txtReceivedDiscipline.Text = input.ReceivedDiscipline;

                    if (rdIsNeedConfirm.SelectedValue == "True")
                    {
                        drpProjectMan.Enabled = true;
                        Pgroup.Enabled = true;
                    }
                    else
                    {
                        drpProjectMan.Enabled = false;
                        Pgroup.Enabled = false;
                    }
                    string pfix = project.ProjectControl_JobNo + "-DI-" + input.IssuedDisciplineCode + "-" + input.ReceivedDisciplineCode + "-";
                    txtMutualIssuedNo.Text = BLL.SQLHelper.RunProcNewId("SpGetNewCodeByJobNo3", "dbo.Design_Notice", "MutualIssuedNo", pfix);

                    if (!string.IsNullOrEmpty(input.IssuedMan))
                    {
                        drpIssuedMan.SelectedValue = input.IssuedMan;
                    }
                    if (!string.IsNullOrEmpty(input.ReceivedMan))
                    {
                        drpReceivedMan.SelectedValue = input.ReceivedMan;
                    }
                    if (!string.IsNullOrEmpty(project.ProjectControl_ProjectManagerId))
                    {
                        drpProjectMan.SelectedValue = project.ProjectControl_ProjectManagerId;
                    }
                }

                if (!string.IsNullOrEmpty(noticeId))
                {
                    var notice = BLL.DesignInputService.GetDesignNotice(noticeId);
                    var input = BLL.DesignInputService.GetDesignInputById(notice.DesignInputId);
                    var project = EProjectService.GeteProjectById(input.EProjectId);
                    txtJobNo.Text = project.ProjectControl_JobNo;
                    txtJobTitle.Text = project.ProjectControl_JobTitle;
                    txtIssuedDiscipline.Text = input.IssuedDiscipline;
                    txtReceivedDiscipline.Text = input.ReceivedDiscipline;

                    txtDesignStage.Text = notice.DesignStage;
                    txtMutualIssuedName.Text = notice.MutualIssuedName;
                    txtMutualIssuedDef.Text = notice.MutualIssuedDef;
                    rdIsNeedConfirm.SelectedValue = notice.IsNeedConfirm.Value.ToString();
                    if (notice.IsNeedConfirm == true)
                    {
                        drpProjectMan.Enabled = true;
                        this.Pgroup.Enabled = true;
                    }
                    else
                    {
                        drpProjectMan.Enabled = false;
                        Pgroup.Enabled = false;
                    }
                    txtPMDef.Text = notice.ConfirmResult;
                    txtReceivedManDef.Text = notice.ReceivedManDef;

                    if (!string.IsNullOrEmpty(notice.IssuedMan))
                    {
                        drpIssuedMan.SelectedValue = notice.IssuedMan;
                    }
                    if (!string.IsNullOrEmpty(notice.ReceivedMan))
                    {
                        drpReceivedMan.SelectedValue = notice.ReceivedMan;
                    }
                    if (!string.IsNullOrEmpty(notice.ProjectManagerId))
                    {
                        drpProjectMan.SelectedValue = notice.ProjectManagerId;
                    }
                    if (notice.PlanMutualIssuedDate.HasValue)
                    {
                        this.txtPlanMutualIssuedDate.Text = string.Format("{0:yyyy-MM-dd}", (notice.PlanMutualIssuedDate));
                    }
                    if (notice.ActMutualIssuedDate.HasValue)
                    {
                        this.txtActMutualIssuedDate.Text = string.Format("{0:yyyy-MM-dd}", (notice.ActMutualIssuedDate));
                    }

                    if (flag == "edit")
                    {
                        if (notice.Flag == "2")
                        {
                            txtDesignStage.Enabled = false;
                            txtMutualIssuedName.Enabled = false;
                        }
                        txtMutualIssuedNo.Text = notice.MutualIssuedNo;
                    }
                    else  // 变更
                    {
                        txtDesignStage.Enabled = false;
                        txtMutualIssuedName.Enabled = false;
                        txtPMDef.Text = "";
                        txtReceivedManDef.Text = "";

                        var q = from x in Funs.DB.Design_Notice where x.Sup_DesignNoticeId == noticeId orderby x.MutualIssuedNo descending select x;
                        string num = string.Empty;
                        if (q.Count() > 0)
                        {
                            string no = q.First().MutualIssuedNo;
                            string subNo = no.Substring(2, 3);
                            num = Funs.GetThreeNumber(subNo);
                        }
                        else
                        {
                            num = "001";
                        }

                        txtMutualIssuedNo.Text = "CH" + num + "-" + notice.MutualIssuedNo;
                    }
                }
            }
        }

        protected void rdIsNeedConfirm_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            if (rdIsNeedConfirm.SelectedValue == "True")
            {
                drpProjectMan.Enabled = true;
                Pgroup.Enabled = true;
            }
            else
            {
                drpProjectMan.Enabled = false;
                Pgroup.Enabled = false;
            }
        }

        #region 通知单添加修改及流程
        // 提出人保存 创建第一个
        private void AddIssuedManSave(string state)
        {
            string designInputId = Request.Params["designInputId"];
            string noticeId = Request.Params["designNoticeId"];
            string flag = Request.Params["flag"];
            var oldNotice = BLL.DesignInputService.GetDesignNotice(noticeId);
            if (string.IsNullOrEmpty(designInputId))
            {
                designInputId = oldNotice.DesignInputId;
            }

            Model.Design_Notice notice = new Model.Design_Notice();
            notice.DesignNoticeId = Guid.NewGuid().ToString();
            notice.DesignInputId = designInputId;
            notice.DesignStage = txtDesignStage.Text.Trim();
            notice.MutualIssuedNo = txtMutualIssuedNo.Text.Trim();
            notice.MutualIssuedName = txtMutualIssuedName.Text.Trim();
            notice.MutualIssuedDef = txtMutualIssuedDef.Text.Trim();
            notice.IsNeedConfirm = Convert.ToBoolean(rdIsNeedConfirm.SelectedValue);

            notice.IssuedMan = drpIssuedMan.SelectedValue;
            notice.ReceivedMan = drpReceivedMan.SelectedValue;
            notice.ProjectManagerId = drpProjectMan.SelectedValue;

            if (!string.IsNullOrEmpty(txtPlanMutualIssuedDate.Text))
            {
                notice.PlanMutualIssuedDate = Convert.ToDateTime(txtPlanMutualIssuedDate.Text);
            }
            if (!string.IsNullOrEmpty(txtActMutualIssuedDate.Text))
            {
                notice.ActMutualIssuedDate = Convert.ToDateTime(txtActMutualIssuedDate.Text);
            }

            // 创建或增加补充通知单
            if (flag == "add" || flag=="sup")
            {
                notice.Flag = "1";
                notice.Sup_DesignNoticeId = "0";
            }
            // 变更通知单
            if (flag == "change")
            {
                notice.Flag = "2";
                notice.Sup_DesignNoticeId = noticeId;
            }
            BLL.DesignInputService.AddDesignNotice(notice);

            // 流程
            if (state == "Submit")
            {
                // 实际开始日期为第一个创建通知单的日期
                var first = from x in Funs.DB.Design_Notice where x.DesignInputId == designInputId select x;
                if (first.Count() == 1)
                {
                    BLL.DesignInputService.UpdateDesignInputActStartDate(designInputId, DateTime.Now);
                }
                else
                {
                    var inputds = BLL.DesignInputService.GetDesignInputById(designInputId);
                    if (!inputds.ActStartDate.HasValue)
                    {
                        BLL.DesignInputService.UpdateDesignInputActStartDate(designInputId, DateTime.Now);
                    }
                }

                Model.Design_NoticeFlow flow = new Model.Design_NoticeFlow();
                flow.NoticeFlowId = Guid.NewGuid().ToString();
                flow.DesignNoticeId = notice.DesignNoticeId;
                flow.SubmitStep = "提出人";
                flow.SubmitMan = drpIssuedMan.SelectedValue;
                flow.SubmitDate = DateTime.Now;
                flow.HandleState = "已提交";
                flow.HandleIdea = txtMutualIssuedDef.Text.Trim();
                DesignInputService.AddNoticeFlow(flow);

                Model.Design_NoticeFlow flow1 = new Model.Design_NoticeFlow();
                flow1.NoticeFlowId = Guid.NewGuid().ToString();
                flow1.DesignNoticeId = notice.DesignNoticeId;
                if (rdIsNeedConfirm.SelectedValue == "True")
                {
                    flow1.SubmitStep = "项目经理";
                    flow1.SubmitMan = drpProjectMan.SelectedValue;
                    flow1.HandleIdea = txtPMDef.Text.Trim();
                }
                else
                {
                    flow1.SubmitStep = "接收人";
                    flow1.SubmitMan = drpReceivedMan.SelectedValue;
                    flow1.HandleIdea = txtReceivedManDef.Text.Trim();
                }
                flow1.SubmitDate = null;
                flow1.HandleState = "待办理";

                DesignInputService.AddNoticeFlow(flow1);

                // 邮件
                SendEmail(notice.DesignNoticeId, flow.SubmitMan, flow1.SubmitMan);
            }
            else // 暂存
            {
                Model.Design_NoticeFlow flow = new Model.Design_NoticeFlow();
                flow.NoticeFlowId = Guid.NewGuid().ToString();
                flow.DesignNoticeId = notice.DesignNoticeId;
                flow.SubmitStep = "提出人";
                flow.SubmitMan = drpIssuedMan.SelectedValue;
                flow.SubmitDate = null;
                flow.HandleState = "待提交";
                flow.HandleIdea = txtMutualIssuedDef.Text.Trim();
                DesignInputService.AddNoticeFlow(flow);
            }
            ShowNotify("Save Successfully!", MessageBoxIcon.Success);
            PageContext.RegisterStartupScript(ActiveWindow.GetWriteBackValueReference(designInputId)
             + ActiveWindow.GetHidePostBackReference());
            //PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
        }

        /// <summary>
        /// 提出人暂存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnPause_Click(object sender, EventArgs e)
        {
            string handle = GetCurSubmitMan();
            if (drpIssuedMan.SelectedValue== CurrUser.UserId || handle == CurrUser.UserId)
            {
                string flag = Request.Params["flag"];
                if (flag == "add" || flag == "sup" || flag== "change")
                {
                    AddIssuedManSave("Pause");
                }
                if (flag == "edit")
                {
                    UpdateNoticeAndFlow("Pause");
                }
            }
            else
            {
                ShowNotify("非当前办理人,不能操作!", MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// 提出人提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnIssuedManSubmit_Click(object sender, EventArgs e)
        {
            string handle = GetCurSubmitMan();
            if (drpIssuedMan.SelectedValue == CurrUser.UserId || handle == CurrUser.UserId)
            {
                string flag = Request.Params["flag"];
                if (flag == "add" || flag == "sup" || flag == "change")
                {
                    AddIssuedManSave("Submit");
                }
                if (flag == "edit")
                {
                    UpdateNoticeAndFlow("Submit");
                }
            }
            else
            {
                ShowNotify("非当前办理人,不能操作!", MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// 项目经理提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnProjectManSubmit_Click(object sender, EventArgs e)
        {
            string handle = GetCurSubmitMan();
            if ( handle == CurrUser.UserId)
            { 
                UpdateNoticeAndFlow("Submit");
            }
            else
            {
                ShowNotify("非当前办理人,不能操作!", MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// 项目经理返回
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnProjectManReturn_Click(object sender, EventArgs e)
        {
            string handle = GetCurSubmitMan();
            if (handle == CurrUser.UserId)
            {
                UpdateNoticeAndFlow("Return");
            }
            else
            {
                ShowNotify("非当前办理人,不能操作!", MessageBoxIcon.Warning);
            }
        }


        /// <summary>
        /// 接收人确认
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnConfirm_Click(object sender, EventArgs e)
        {
            string handle = GetCurSubmitMan();
            if (handle == CurrUser.UserId)
            {
                UpdateNoticeAndFlow("Submit");
            }
            else
            {
                ShowNotify("非当前办理人,不能操作!", MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// 接收人返回
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnReceivedManReturn_Click(object sender, EventArgs e)
        {
            string handle = GetCurSubmitMan();
            if (handle == CurrUser.UserId)
            {
                UpdateNoticeAndFlow("Return");
            }
            else
            {
                ShowNotify("非当前办理人,不能操作!", MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// 获取当前的办理人
        /// </summary>
        /// <returns></returns>
        private string GetCurSubmitMan()
        {
            string noticeId = Request.Params["designNoticeId"];
            var flow = BLL.DesignInputService.GetNoticeFlow(noticeId);
            if (flow != null)
            {
                return flow.SubmitMan;
            }
            else
            {
                return "";
            }
        }

        private void UpdateNoticeAndFlow(string state)
        {
            string noticeId = Request.Params["designNoticeId"];
            string flag = Request.Params["flag"];
            // 更新一个通知单及流程
            if (flag == "edit")
            {
                var designNotice = BLL.DesignInputService.GetDesignNotice(noticeId);
                Model.Design_Notice notice = new Model.Design_Notice();

                notice.DesignInputId = designNotice.DesignInputId;
                notice.DesignStage = txtDesignStage.Text.Trim();
                notice.MutualIssuedNo = txtMutualIssuedNo.Text.Trim();
                notice.MutualIssuedName = txtMutualIssuedName.Text.Trim();
                notice.MutualIssuedDef = txtMutualIssuedDef.Text.Trim();
                notice.IsNeedConfirm = Convert.ToBoolean(rdIsNeedConfirm.SelectedValue);
                //notice.ConfirmResult = txtDescribe.Text.Trim();

                notice.IssuedMan = drpIssuedMan.SelectedValue;
                notice.ReceivedMan = drpReceivedMan.SelectedValue;
                notice.ProjectManagerId = drpProjectMan.SelectedValue;

                if (!string.IsNullOrEmpty(txtPlanMutualIssuedDate.Text))
                {
                    notice.PlanMutualIssuedDate = Convert.ToDateTime(txtPlanMutualIssuedDate.Text);
                }
                if (!string.IsNullOrEmpty(txtActMutualIssuedDate.Text))
                {
                    notice.ActMutualIssuedDate = Convert.ToDateTime(txtActMutualIssuedDate.Text);
                }
                notice.DesignNoticeId = designNotice.DesignNoticeId;

                var flow = BLL.DesignInputService.GetNoticeFlow(noticeId);
                if (flow.SubmitStep == "提出人") // 提出人才可修改通知单信息
                {
                    BLL.DesignInputService.UpdateDesignNotice(notice);
                    if (state == "Submit")
                    {
                        BLL.DesignInputService.UpdateDesignFlow(flow.NoticeFlowId, "已提交", txtMutualIssuedDef.Text.Trim(), DateTime.Now);
                        Model.Design_NoticeFlow flow1 = new Model.Design_NoticeFlow();
                        flow1.NoticeFlowId = Guid.NewGuid().ToString();
                        flow1.DesignNoticeId = notice.DesignNoticeId;
                        if (rdIsNeedConfirm.SelectedValue == "True")
                        {
                            flow1.SubmitStep = "项目经理";
                            flow1.SubmitMan = drpProjectMan.SelectedValue;
                        }
                        else
                        {
                            flow1.SubmitStep = "接收人";
                            flow1.SubmitMan = drpReceivedMan.SelectedValue;
                        }
                        flow1.SubmitDate = null;
                        flow1.HandleState = "待办理";

                        DesignInputService.AddNoticeFlow(flow1);

                        // 邮件
                        SendEmail(noticeId, flow.SubmitMan, flow1.SubmitMan);
                    }
                }
                else if (flow.SubmitStep == "项目经理")
                {
                    BLL.DesignInputService.UpdateProjectDef(notice.DesignNoticeId, txtPMDef.Text.Trim());
                    if (state == "Submit")
                    {
                        BLL.DesignInputService.UpdateDesignFlow(flow.NoticeFlowId, "已提交", txtPMDef.Text.Trim(), DateTime.Now);
                        Model.Design_NoticeFlow flow1 = new Model.Design_NoticeFlow();
                        flow1.NoticeFlowId = Guid.NewGuid().ToString();
                        flow1.DesignNoticeId = notice.DesignNoticeId;
                        flow1.SubmitStep = "接收人";
                        flow1.SubmitMan = drpReceivedMan.SelectedValue;
                        flow1.SubmitDate = null;
                        flow1.HandleState = "待办理";
                        DesignInputService.AddNoticeFlow(flow1);

                        // 邮件
                        SendEmail(noticeId, flow.SubmitMan, flow1.SubmitMan);
                    }
                    else //返回
                    {
                        BLL.DesignInputService.UpdateDesignFlow(flow.NoticeFlowId, "已返回", txtPMDef.Text.Trim(), DateTime.Now);
                        Model.Design_NoticeFlow flow1 = new Model.Design_NoticeFlow();
                        flow1.NoticeFlowId = Guid.NewGuid().ToString();
                        flow1.DesignNoticeId = notice.DesignNoticeId;
                        flow1.SubmitStep = "提出人";
                        flow1.SubmitMan = drpIssuedMan.SelectedValue;
                        flow1.HandleIdea = designNotice.MutualIssuedDef;
                        flow1.SubmitDate = null;
                        flow1.HandleState = "待办理";
                        DesignInputService.AddNoticeFlow(flow1);

                        // 邮件
                        SendEmail(noticeId, flow.SubmitMan, flow1.SubmitMan);
                    }
                }
                else // 接收人
                {
                    BLL.DesignInputService.UpdateReceivedManDef(notice.DesignNoticeId, txtReceivedManDef.Text.Trim());
                    if (state == "Submit")
                    {
                        // 完成 
                        BLL.DesignInputService.UpdateDesignFlow(flow.NoticeFlowId, "已提交", txtReceivedManDef.Text.Trim(), DateTime.Now);
                        // 更新实际日期
                        BLL.DesignInputService.UpdateDesignInputComplete(designNotice.DesignInputId, true, DateTime.Now);
                    }
                    else //返回
                    {
                        BLL.DesignInputService.UpdateDesignFlow(flow.NoticeFlowId, "已返回", txtReceivedManDef.Text.Trim(), DateTime.Now);
                        Model.Design_NoticeFlow flow1 = new Model.Design_NoticeFlow();
                        flow1.NoticeFlowId = Guid.NewGuid().ToString();
                        flow1.DesignNoticeId = notice.DesignNoticeId;
                        flow1.SubmitStep = "提出人";
                        flow1.SubmitMan = drpIssuedMan.SelectedValue;
                        flow1.HandleIdea = designNotice.MutualIssuedDef;
                        flow1.SubmitDate = null;
                        flow1.HandleState = "待办理";
                        DesignInputService.AddNoticeFlow(flow1);

                        // 邮件
                        var input = BLL.DesignInputService.GetDesignInputById(designNotice.DesignInputId);
                        SendEmail(noticeId, flow.SubmitMan, flow1.SubmitMan);
                    }
                }

                ShowNotify("Save Successfully!", MessageBoxIcon.Success);

                PageContext.RegisterStartupScript(ActiveWindow.GetWriteBackValueReference(designNotice.DesignInputId)
                 + ActiveWindow.GetHidePostBackReference());
            }
        }

        /// <summary>
        /// 流程中邮件发送
        /// </summary>
        /// <param name="mutualIssuedNo"></param>
        /// <param name="planEndDate"></param>
        /// <param name="userId"></param>
        private void SendEmail(string noticeId, string submitMan, string userId)
        {
            var notice = BLL.DesignInputService.GetDesignNotice(noticeId);
            var input = BLL.DesignInputService.GetDesignInputById(notice.DesignInputId);
            var project = BLL.EProjectService.GeteProjectById(input.EProjectId);
            string person_Ch = string.Empty;
            string person_En = string.Empty;
            var user = from x in BLL.Funs.DB.Sys_User where x.UserId == submitMan select x;
            if (user.Count() > 0)
            {
                person_Ch = user.First().ChineseName;
                person_En = user.First().UserName;
            }

            NameValueCollection nameValue = new NameValueCollection();
            nameValue.Add("projectNo", project.ProjectControl_JobNo);
            nameValue.Add("IssuedDiscOrNo", project.ProjectControl_JobNo + "-" + project.ProjectControl_JobTitle + "," + input.DesignInputChName + " " + input.DesignInputEnName + " " + input.DesignInputNo + " " + notice.MutualIssuedNo);
            nameValue.Add("Person_Ch", person_Ch);
            nameValue.Add("Person_En", person_En);

            if (!string.IsNullOrEmpty(userId))
            {
                Model.Sys_User sys_User = new Model.Sys_User();
                sys_User = BLL.Sys_UserService.GetUsersByUserId(userId);
                nameValue.Add("UserName", sys_User.UserName);
                List<Model.Sys_User> list = new List<Model.Sys_User>();

                list.Add(sys_User);
                EmailSendMessage(BLL.Const.DesignInputString, nameValue, BLL.Const.CustomString, list, "");
            }
        }

        #endregion

    }
}