using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;

using Entity;
using BLL;

public partial class Tester_DoTest2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            CheckRecorder();
            BindPaperInfo();
            BindTestInfo();
            new BLLTestRecorder().ModifyBeginTest(Helper.GetUrlParmValue("testID").ToString(), SessionClass.GetLoginUser().UserID, DateTime.Now);
        }
    }
    private void CheckRecorder()
    {
        BLLTestRecorder bllRecoder = new BLLTestRecorder();
        TestRecorder recorder = bllRecoder.GetTestRecorderListBy(Helper.GetUrlParmValue("testID").ToString(), SessionClass.GetLoginUser().UserID);
        if (null == recorder)
            Response.Redirect("msg.aspx?msg='考试不存在！'");

        if (recorder.Test.HasUnable)
        {
            Response.Redirect("msg.aspx?msg='这次考试的日期已过！'");
        }

        if (recorder.Test.BeforeEnable)
        {
            Response.Redirect("msg.aspx?msg='这次考试的日期未到！'");
        }

        if (recorder.HasTested)
        {
            Response.Redirect("msg.aspx?msg='你已经参加过该次考试了！'");
        }
    }

    private void BindTestInfo()
    {
        Test test = new BLLTest().GetTestByID(Helper.GetUrlParmValue("testID").ToString());
        if (test == null)
            Response.Redirect("msg.aspx?msg=" + "该考试不存在！");
        lblTestName.Text = test.TestName;
        Page.Title = test.TestName;
        lblNeededMinutes.Text = test.NeededMinutes.ToString();

        int hours = test.NeededMinutes / 60;
        int minutes = test.NeededMinutes % 60;
        TimeSpan ts = new TimeSpan(hours, minutes, 10);//延长10秒

        DateTime now = DateTime.Now;
        ViewState["endTime"] = now.Add(ts);
        ViewState["autoSaveInterval"] = test.AutoSaveInterval;

        Timer2.Interval = 60000 * test.AutoSaveInterval;

        lblTimeLeft.Text = string.Format("{0}小时{1}分钟{2}秒", ts.Hours, ts.Minutes, ts.Seconds);
        lblAutoSaveMinutes.Text = test.AutoSaveInterval.ToString();

        Timer1.Enabled = true;
        Timer2.Enabled = true;
    }

    private void BindPaperInfo()
    {
        int testID = Helper.GetUrlParmValue("testID");
        int paperID = Helper.GetUrlParmValue("paperID");
        int paperType = Helper.GetUrlParmValue("paperType");

        if ((PaperType)paperType == PaperType.BySelection)//手工选题
        {
            PaperByManualSelection paper = new BLLPaperByManuaSelection().GetPaper(testID, paperID);
            if (paper != null)
            {
                rptSubjectOfFillBlankList.DataSource = paper.FillBlankList;
                rptSubjectOfFillBlankList.DataBind();
                lblFillBlankListCount.Text = paper.FillBlankList.Count.ToString();
                if (paper.FillBlankList.Count > 0)
                {
                    lblFillBlankScores.Text = paper.FillBlankList[0].Scores.ToString();
                    lblFillBlankTotalScores.Text = (paper.FillBlankList[0].Scores * paper.FillBlankList.Count).ToString();
                }

                rptSubjectOfJudgeList.DataSource = paper.JudgeList;
                rptSubjectOfJudgeList.DataBind();
                lblJudgeListCount.Text = paper.JudgeList.Count.ToString();
                if (paper.JudgeList.Count > 0)
                {
                    lblJudgeScores.Text = paper.JudgeList[0].Scores.ToString();
                    lblJudgeTotalScores.Text = (paper.JudgeList[0].Scores * paper.JudgeList.Count).ToString();
                }

                rptSubjectOfSingleSelectionList.DataSource = paper.SingleSelectionList;
                rptSubjectOfSingleSelectionList.DataBind();
                lblSingleSelectionCount.Text = paper.SingleSelectionList.Count.ToString();
                if (paper.SingleSelectionList.Count > 0)
                {
                    lblSingleSelectionScores.Text = paper.SingleSelectionList[0].Scores.ToString();
                    lblSingleSelectionTotalScores.Text = (paper.SingleSelectionList[0].Scores * paper.SingleSelectionList.Count).ToString();
                }

                rptSubjectOfMultiSelectionList.DataSource = paper.MultiSelectionList;
                rptSubjectOfMultiSelectionList.DataBind();
                lblMultiSelectionCount.Text = paper.MultiSelectionList.Count.ToString();
                if (paper.MultiSelectionList.Count > 0)
                {
                    lblMultiSelectionScores.Text = paper.MultiSelectionList[0].Scores.ToString();
                    lblMultiSelectionTotalScores.Text = (paper.MultiSelectionList[0].Scores * paper.MultiSelectionList.Count).ToString();
                }

                rptSubjectOfSimpleAnswerList.DataSource = paper.SimpleAnswerList;
                rptSubjectOfSimpleAnswerList.DataBind();
                lblSimpleAnswerCount.Text = paper.SimpleAnswerList.Count.ToString();
                if (paper.SimpleAnswerList.Count > 0)
                {
                    int totalScores = 0;
                    foreach (SubjectOfSimpleAnswer subject in paper.SimpleAnswerList)
                    {
                        totalScores += subject.Scores;
                    }
                    lblSimpleAnswerTotalScores.Text = totalScores.ToString();
                }
                lblTotalScores.Text = (Convert.ToInt32(lblFillBlankTotalScores.Text)
                    + Convert.ToInt32(lblJudgeTotalScores.Text)
                    + Convert.ToInt32(lblSingleSelectionTotalScores.Text)
                    + Convert.ToInt32(lblMultiSelectionTotalScores.Text)
                    + Convert.ToInt32(lblSimpleAnswerTotalScores.Text)).ToString();
            }

            //创建考试对应的答案记录
            new BLLTestRecorder().CreateTestRecorderAnswer(Helper.GetUrlParmValue("recorderID"));
        }
        else if ((PaperType)paperType == PaperType.ByRandom)//随机抽题
        {
            PaperByRandomSelection paper = new BLLPaperByRandomSelection().GetPaper(testID, paperID);
            if (paper != null)
            {
                rptSubjectOfJudgeList.DataSource = paper.JudgeList;
                rptSubjectOfJudgeList.DataBind();
                lblJudgeListCount.Text = paper.JudgeList.Count.ToString();
                if (paper.JudgeList.Count > 0)
                {
                    lblJudgeScores.Text = paper.JudgeList[0].Scores.ToString();
                    lblJudgeTotalScores.Text = (paper.JudgeList[0].Scores * paper.JudgeList.Count).ToString();
                }

                rptSubjectOfSingleSelectionList.DataSource = paper.SingleSelectionList;
                rptSubjectOfSingleSelectionList.DataBind();
                lblSingleSelectionCount.Text = paper.SingleSelectionList.Count.ToString();
                if (paper.SingleSelectionList.Count > 0)
                {
                    lblSingleSelectionScores.Text = paper.SingleSelectionList[0].Scores.ToString();
                    lblSingleSelectionTotalScores.Text = (paper.SingleSelectionList[0].Scores * paper.SingleSelectionList.Count).ToString();
                }

                rptSubjectOfMultiSelectionList.DataSource = paper.MultiSelectionList;
                rptSubjectOfMultiSelectionList.DataBind();
                lblMultiSelectionCount.Text = paper.MultiSelectionList.Count.ToString();
                if (paper.MultiSelectionList.Count > 0)
                {
                    lblMultiSelectionScores.Text = paper.MultiSelectionList[0].Scores.ToString();
                    lblMultiSelectionTotalScores.Text = (paper.MultiSelectionList[0].Scores * paper.MultiSelectionList.Count).ToString();
                }
            
                lblTotalScores.Text = (Convert.ToInt32(lblJudgeTotalScores.Text)
                    + Convert.ToInt32(lblSingleSelectionTotalScores.Text)
                    + Convert.ToInt32(lblMultiSelectionTotalScores.Text)).ToString();

                //创建考试对应的答案记录
                new BLLTestRecorder().CreateTestRecorderAnswer(Helper.GetUrlParmValue("recorderID"),null,paper.JudgeList,paper.SingleSelectionList,paper.MultiSelectionList,null);
            }
        }
    }

    protected void btnSaveAnswer_Click(object sender, EventArgs e)
    {
        try
        {
            new BLLTestRecorder().ModifyTestRecorderAnswer(Helper.GetUrlParmValue("recorderID"), list1, list2, list3, list4, list5);
            lblMsg.Text = "保存成功(" + DateTime.Now.ToString() + ")";
        }
        catch(Exception ex)
        {
            Helper.Alert_Ajax(UpdatePanel5,"输入有误！"+ex.Message);
            lblMsg.Text = ex.Message;
        }
       
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            new BLLTestRecorder().ModifyTestRecorderAnswer(Helper.GetUrlParmValue("recorderID"), list1, list2, list3, list4, list5);
            new BLLTestRecorder().SubmitTest(Helper.GetUrlParmValue("testID").ToString(), SessionClass.GetLoginUser().UserID, string.Empty, DateTime.Now);
            if ((int)PaperType.ByRandom == Helper.GetUrlParmValue("paperType"))
            {
                new BLLTestMark().CreateTestMarkForRandomSelection(Helper.GetUrlParmValue("recorderID"));
            }
            Helper.ClosePage_Ajax(UpdatePanel5, "提交成功！");
            Timer1.Enabled = false;
            Timer2.Enabled = false;
        }
        catch (Exception ex)
        {
            Helper.Alert_Ajax(UpdatePanel5, "输入有误！" + ex.Message);
            lblMsg.Text = ex.Message;
        }
    }

    //考试时间监控
    protected void Timer1_Tick(object sender, EventArgs e)
    {
        this.Application.Lock();
        DateTime endTime = Convert.ToDateTime(ViewState["endTime"]);
        DateTime now = DateTime.Now;

        if (now.CompareTo(endTime) >= 0)//时间已到
        {

            Timer1.Enabled = false;
            Timer2.Enabled = false;
            new BLLTestRecorder().ModifyTestRecorderAnswer(Helper.GetUrlParmValue("recorderID"), list1, list2, list3, list4, list5);
            new BLLTestRecorder().AutoSubmitTest(Helper.GetUrlParmValue("testID").ToString(), SessionClass.GetLoginUser().UserID,string.Empty, DateTime.Now);
            if ((int)PaperType.ByRandom == Helper.GetUrlParmValue("paperType"))
            {
                new BLLTestMark().CreateTestMarkForRandomSelection(Helper.GetUrlParmValue("recorderID"));
            }
            Helper.ClosePage_Ajax(UpdatePanel5, "考试时间已到，系统已自动提交答案！");
        }

        TimeSpan ts = endTime.Subtract(now);
        lblTimeLeft.Text = string.Format("{0}小时{1}分钟{2}秒", ts.Hours, ts.Minutes, ts.Seconds);
        this.Application.UnLock();

    }

    //隔段时间保存答案
    protected void Timer2_Tick(object sender, EventArgs e)
    {
          new BLLTestRecorder().ModifyTestRecorderAnswer(Helper.GetUrlParmValue("recorderID"), list1, list2, list3, list4, list5);
          lblMsg.Text = "自动保存成功(" + DateTime.Now.ToString() + ")";
    }

    #region 答题信息
    private List<SubjectOfFillBlank> list1
    {
        get
        {
            List<SubjectOfFillBlank> list=new List<SubjectOfFillBlank>();
            int index = 0;
            foreach (RepeaterItem item in rptSubjectOfFillBlankList.Items)
            {
                try
                {
                    HiddenField hid = (HiddenField)item.FindControl("hidFillBlankID");
                    int id = Convert.ToInt32(hid.Value);
                    string answer = Request["txtFillBlankAnswer" + (++index)];
                    
                    SubjectOfFillBlank subject = new SubjectOfFillBlank();
                    subject.Id = id;
                    subject.Answer = answer;

                    list.Add(subject);
                }
                catch { }
            }
            return list;
        }
    }

    private List<SubjectOfJudge> list2
    {
        get
        {
            List<SubjectOfJudge> list = new List<SubjectOfJudge>();
            foreach (RepeaterItem item in rptSubjectOfJudgeList.Items)
            {
                try
                {
                    HiddenField hid = (HiddenField)item.FindControl("hidJudgeID");
                    int id = Convert.ToInt32(hid.Value);
                    TextBox txt = (TextBox)item.FindControl("txtJudgeAnswer");
                    bool answer = txt.Text.ToUpper() == "Y" ? true : false;

                    SubjectOfJudge subject = new SubjectOfJudge();
                    subject.Id = id;
                    subject.Answer = answer;

                    list.Add(subject);
                }
                catch { }
            }
            return list;
        }
    }

    private List<SubjectOfSingleSelection> list3
    {
        get
        {
            List<SubjectOfSingleSelection> list = new List<SubjectOfSingleSelection>();
            foreach (RepeaterItem item in rptSubjectOfSingleSelectionList.Items)
            {
                try
                {
                    HiddenField hid = (HiddenField)item.FindControl("hidSingleSelectionID");
                    int id = Convert.ToInt32(hid.Value);
                    TextBox txt = (TextBox)item.FindControl("txtSingleSelectionAnswer");
                    char answer = Convert.ToChar(txt.Text.ToUpper());

                    SubjectOfSingleSelection subject = new SubjectOfSingleSelection();
                    subject.Id = id;
                    subject.Answer = answer;

                    list.Add(subject);
                }
                catch { }
            }
            return list;
        }
    }

    private List<SubjectOfMultiSelection> list4
    {
        get
        {
            List<SubjectOfMultiSelection> list = new List<SubjectOfMultiSelection>();
            foreach (RepeaterItem item in rptSubjectOfMultiSelectionList.Items)
            {
                try
                {
                    HiddenField hid = (HiddenField)item.FindControl("hidMultiSelectionID");
                    int id = Convert.ToInt32(hid.Value);
                    TextBox txt = (TextBox)item.FindControl("txtMultiSelectionAnswer");
                    string answer = txt.Text.ToUpper();

                    SubjectOfMultiSelection subject = new SubjectOfMultiSelection();
                    subject.Id = id;
                    subject.Answer = answer;

                    list.Add(subject);
                }
                catch { }
            }
            return list;
        }
    }
    
    private List<SubjectOfSimpleAnswer> list5
    {
        get
        {
            List<SubjectOfSimpleAnswer> list = new List<SubjectOfSimpleAnswer>();
            foreach (RepeaterItem item in rptSubjectOfSimpleAnswerList.Items)
            {
                try
                {
                    HiddenField hid = (HiddenField)item.FindControl("hidSimpleAnswerID");
                    int id = Convert.ToInt32(hid.Value);
                    TextBox txt = (TextBox)item.FindControl("txtSimpleAnswerAnswer");
                    string answer = txt.Text;

                    SubjectOfSimpleAnswer subject = new SubjectOfSimpleAnswer();
                    subject.Id = id;
                    subject.Answer = answer;

                    list.Add(subject);
                }
                catch { }
            }
            return list;
        }
    }
    #endregion

}
