<%@ WebHandler Language="C#" Class="AnswerSheet" %>

using System;
using System.Web;
using EB_BLL;
using System.Data;
using EB_DAL;
using EB_Model;
using System.Collections.Generic;
using EB_Common;
using Jayrock.Json;

using System.Xml;
public class AnswerSheet : IHttpHandler
{

    HttpRequest Request = null;
    HttpResponse Response = null;

    public void ProcessRequest(HttpContext context)
    {
        Request = context.Request;
        Response = context.Response;
        //start qid            
        if (String.IsNullOrEmpty(Request["qid"]) || String.IsNullOrEmpty(Request["inList"]))
        {
            outError("错误：无效的参数！");
        }

        Guid qid = new Guid(Request["qid"].ToString());
        String index = Request["index"].ToString().Trim();
        String inList = EncryptString.Decrypt(Request["inList"]);


        if (index == String.Empty)
        {
            outError("错误：没有对应的答题！");
        }

        DateTime start = DateTime.MinValue;
        DateTime end = DateTime.Now;
        if (!DateTime.TryParse(Request["start"],out start))
        {
            outError("错误:参数错误！");
        }

        PT_AnswerQuestionnaire_BLL aqBLL = new PT_AnswerQuestionnaire_BLL();
        PT_AnswerQuestionnaire_Model aqModel = new PT_AnswerQuestionnaire_Model();

        aqModel.aq_id = Guid.NewGuid();
        aqModel.aq_pqid = qid;
        aqModel.aq_uid = N25175_User_BLL.GetLoginKey();
        aqModel.aq_answerStart = start;
        aqModel.aq_answerEnd = end;
        //如果是项目项目问卷样本答卷则
        aqModel.aq_cdate = DateTime.Now;
        aqModel.aq_udate = DateTime.Now;
        
        
        //获取答卷选择题与填空题
        List<PT_AnswerChoiceQuestion_Model> choiceAnswerList = new List<PT_AnswerChoiceQuestion_Model>();
        PT_ChoiceQuestion_BLL qebll = new PT_ChoiceQuestion_BLL();

        List<PT_ChoiceQuestion_Model> listcq = qebll.GetChoiceQuestion(inList,aqModel.aq_pqid);

        PT_ChoiceQuestionOption_BLL cqobll = new PT_ChoiceQuestionOption_BLL();
        //获取试卷的所有正确选项
        List<Guid> AnswerOption = cqobll.GetQuestionaireAnswerOptionKeys(qid);

        int correct = 0;
        int error = 0;
        //如果没有则不获取
        if (listcq != null)
        {
            foreach (PT_ChoiceQuestion_Model cqmodel in listcq)
            {
                bool zq = false;//题目是否回答正确
                if (cqmodel.pcq_type == 0)
                {
                    zq = BuilderRedio(choiceAnswerList, cqmodel, aqModel,AnswerOption);
                }
                else if (cqmodel.pcq_type == 1)
                {
                    zq = BuilderCheck(choiceAnswerList, cqmodel, aqModel,AnswerOption);
                }
                else
                {
                    outError("程序配置参数出错：选择题未知类型！");
                }

                if (zq){
                    correct++;
                }
                else{
                    error++;
                }
            }
        }
        aqModel.aq_correct = correct;//正确数量
        aqModel.aq_error = error;//错误数量
        //保存答卷
        String msg = aqBLL.Add(aqModel,choiceAnswerList);

        JsonObject json = new JsonObject();
        if (msg==String.Empty)
        {
            json.Accumulate("state", 1);
            json.Accumulate("key", aqModel.aq_id);
            json.Accumulate("data", "答卷已成功保存！");
        }
        else
        {
            json.Accumulate("state", 1);
            json.Accumulate("data", msg);
        }
        Response.Write(json);
        Response.End();
    }

    /// <summary>
    /// 获取已跳过的所有题目
    /// </summary>
    /// <param name="choiceAnswerList"></param>
    /// <param name="cqmodel"></param>
    /// <param name="aqModel"></param>
    private void BuilderCancelAnswer(List<Guid> cancelAnswerList, List<PT_ChoiceQuestion_Model> cqlist, DataTable caList)
    {
        foreach (PT_ChoiceQuestion_Model cqmodel in cqlist)
        {
            Object ChoiceValue = Request[cqmodel.pcq_id.ToString()];
            if (ChoiceValue == null)
            {
                continue;
            }
            String selectOption = ChoiceValue.ToString();
            if (selectOption == String.Empty)
            {
                continue;
            }
            if (cqmodel.pcq_type == 0)
            {
                Guid ChoiceID = new Guid(selectOption);//单选题选项ID

                DataRow[] rows = caList.Select(String.Format("oid='{0}'", ChoiceID));

                foreach (DataRow row in rows)
                {
                    cancelAnswerList.Add((Guid)row["cqid"]);
                }
            }
            else if (cqmodel.pcq_type == 1)
            {
                String[] options = selectOption.ToString().Split(',');
                for (int c = 0; c < options.Length; c++)
                {
                    Guid ChoiceID = new Guid(options[c]);//多选题选项ID

                    DataRow[] rows = caList.Select(String.Format("oid='{0}'", ChoiceID));
                    foreach (DataRow row in rows)
                    {
                        cancelAnswerList.Add((Guid)row["cqid"]);
                    }
                }
            }
            else
            {
                outError("程序配置参数出错：选择题未知类型！");
            }
        }
    }

    /// <summary>
    /// 获取答卷的单选部分
    /// </summary>
    /// <param name="choiceAnswerList"></param>
    /// <param name="aqModel"></param>
    /// <param name="itemValue"></param>
    private bool BuilderRedio(
        List<PT_AnswerChoiceQuestion_Model> choiceAnswerList,
        PT_ChoiceQuestion_Model cqmodel,
        PT_AnswerQuestionnaire_Model aqModel,
        List<Guid> answerList)
    {
        //cqmodel.pcq_cdate
        //String itemValue = new Guid 
        Object redioValue = Request[cqmodel.pcq_id.ToString()];
        if (redioValue == null)
        {
            outError(String.Format("您还未选择题目：{0}", cqmodel.pcq_question));
        }

        Guid radioOptionID = new Guid(redioValue.ToString());//单选题选项ID
        PT_AnswerChoiceQuestion_Model choiceAnswerModel = new PT_AnswerChoiceQuestion_Model();
        choiceAnswerModel.acq_aqid = aqModel.aq_id;
        choiceAnswerModel.acq_cdate = DateTime.Now;
        choiceAnswerModel.acq_cqoid = radioOptionID;
        choiceAnswerModel.acq_id = Guid.NewGuid();
        choiceAnswerModel.acq_udate = DateTime.Now;

        //判断单选题答案是否是正确答案
        bool iszq = answerList.Contains(choiceAnswerModel.acq_cqoid);
        if (iszq)
        {
            answerList.Remove(choiceAnswerModel.acq_cqoid);
        }
        choiceAnswerModel.acq_correct = iszq;

        choiceAnswerList.Add(choiceAnswerModel);
        return iszq;
    }

    /// <summary>
    /// 获取答卷的多选部分
    /// </summary>
    /// <param name="choiceAnswerList"></param>
    /// <param name="aqModel"></param>
    /// <param name="itemValue"></param>
    private bool BuilderCheck(List<PT_AnswerChoiceQuestion_Model> choiceAnswerList,
        PT_ChoiceQuestion_Model cqModel,
        PT_AnswerQuestionnaire_Model aqModel,
        List<Guid> answerList)
    {
        //所有选中的复选框
        String checkOptions = Request[cqModel.pcq_id.ToString()];
        if (checkOptions == null)
        {
            outError(String.Format("您还未选择题目：{0}", cqModel.pcq_question));
        }
        String[] options = checkOptions.Split(',');
        bool isAllCorrect = true;
        for (int c = 0; c < options.Length; c++)
        {
            PT_AnswerChoiceQuestion_Model checkAnswerModel = new PT_AnswerChoiceQuestion_Model();
            checkAnswerModel.acq_aqid = aqModel.aq_id;
            checkAnswerModel.acq_cdate = DateTime.Now;
            checkAnswerModel.acq_cqoid = new Guid(options[c]);
            checkAnswerModel.acq_id = Guid.NewGuid();
            checkAnswerModel.acq_udate = DateTime.Now;


            if (answerList.Contains(checkAnswerModel.acq_cqoid))
            {
                answerList.Remove(checkAnswerModel.acq_cqoid);
                checkAnswerModel.acq_correct = true;
            }
            else
            {
                checkAnswerModel.acq_correct = false;
                isAllCorrect = false;
            }

            choiceAnswerList.Add(checkAnswerModel);
        }
        //判断题目是否正确
        return isAllCorrect;
    }

    /// <summary>
    /// 输出错误的方法
    /// </summary>
    /// <param name="msg"></param>
    private void outError(String msg)
    {
        JsonObject json = new JsonObject();
        json.Accumulate("state", -1);
        json.Accumulate("data", msg);
        Response.Write(json);
        Response.End();
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }



}