using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Reflection;
using core.BusinessObject;
using System.Web;

using Word;

///
///使用的是Word2003  引用Microsoft Word 11.0 Object Library;
///
namespace core.BusinessLogicLayer
{
    public class WordPages
    {
        private Word._Application oWord;
        private Word._Document oDoc;
        private Word._Document oDocAnswer;
        private object oMissing = System.Reflection.Missing.Value;
        private Word.Table tbl;
        private Word.Range rng;
        private object start = 0, end = 0;
        private string pathdoc;
        private string pathdot;
        private PaperHeadInfo objPaperHeadInfo;
        private PaperInfo objPaperInfo;
        private WordObject objWordObject = new WordObject();

        public WordPages(string _pathdoc, string _pathdot, PaperHeadInfo _objPaperHeadInfo, PaperInfo _objPaperInfo)
        {
            pathdoc = _pathdoc;
            pathdot = _pathdot;
            oWord = new Word.Application();
            objPaperHeadInfo = _objPaperHeadInfo;
            objPaperInfo = _objPaperInfo;
        }

        #region 生成Word文档的方法 List<Subject>
        public WordObject makeword(List<Subject> subjectList)
        {
            try
            {
                objWordObject = this.getWordDot2();

                List<List<Subject>> questionList = new List<List<Subject>>();

                List<Subject> choiceTypeList = new List<Subject>();
                List<Subject> blankTypeList = new List<Subject>();
                List<Subject> judgementTypeList = new List<Subject>();
                List<Subject> answerTypeList = new List<Subject>();
                List<Subject> otherTypeList = new List<Subject>();

                questionList.Add(choiceTypeList);
                questionList.Add(blankTypeList);
                questionList.Add(judgementTypeList);
                questionList.Add(answerTypeList);
                questionList.Add(otherTypeList);

                foreach (Subject subject in subjectList)
                {
                    if ("选择题".Equals(subject.ThemeName))
                    {
                        choiceTypeList.Add(subject);
                    }
                    else if ("填空题".Equals(subject.ThemeName))
                    {
                        blankTypeList.Add(subject);
                    }
                    else if ("判断题".Equals(subject.ThemeName))
                    {
                        judgementTypeList.Add(subject);
                    }
                    else if ("问答题".Equals(subject.ThemeName))
                    {
                        answerTypeList.Add(subject);
                    }
                    else
                    {
                        otherTypeList.Add(subject);
                    }
                }

                //输出考题
                foreach (List<Subject> qusList in questionList)
                {
                    if(qusList.Count != 0)
                        objWordObject = this.printfQuestion(qusList.ToArray());
                }

                //输出答案
                oDocAnswer = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                foreach (List<Subject> qusList in questionList)
                {
                    if (qusList.Count != 0)
                        objWordObject = this.printfAnswer(qusList.ToArray());
                }

                //for (int counttype = 0; counttype < questionList.Count - 1; counttype++)
                //{
                //    objWordObject = printfAnswer(ds_com, questionList[counttype].ToString(), counttype + 1);
                //}

                //保存文档
                object oFilename = pathdoc + objPaperHeadInfo.courseName + "(考题)" + System.DateTime.Now.ToShortDateString() + ".doc";    //需要保存的Word文件名 包括地址
                oDoc.SaveAs(ref oFilename, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                objWordObject.QuestionPath = oFilename.ToString();
                oFilename = pathdoc + objPaperHeadInfo.courseName + "(答案)" + System.DateTime.Now.ToShortDateString() + ".doc";    //需要保存的Word文件名 包括地址
                oDocAnswer.SaveAs(ref oFilename, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                objWordObject.AnswerPath = oFilename.ToString();
                objWordObject.Wordflag = true;
            }
            catch (Exception)
            {
                objWordObject.Wordflag = false;
                return objWordObject;
            }
            finally {
                oDoc.Close(ref oMissing, ref oMissing, ref oMissing);
                oDocAnswer.Close(ref oMissing, ref oMissing, ref oMissing);
                oWord.Quit(ref oMissing, ref oMissing, ref oMissing);               
            }
            return objWordObject;
        }
        #endregion

        #region 输出考题内容
        private WordObject printfQuestion(Subject[] qusList)
        {
            try
            {
                Paragraph oParamark;
                oParamark = oDoc.Content.Paragraphs.Add(ref oMissing);
                oParamark.Range.Font.Size = 10;
                oParamark.Range.Font.Bold = 1;
                //for (int countdt = 0; countdt < ds_com.Tables.Count; countdt++)  //判断ds_com中的table数 即：题型数目
                //{
                //    if (!questionType.Equals("anyType"))
                //    {
                //        if (ds_com.Tables[countdt].TableName.Equals(questionType))
                //        {
                            oParamark.LeftIndent = 0;
                            oParamark.Range.Font.Bold = 1;
                            oParamark.Range.Text = "\n" + qusList[0].ThemeName + "(共：" + qusList.Length + "题)";
                            oParamark.Format.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                            oParamark.Range.InsertParagraphAfter();
                            oParamark.Range.Font.Bold = 0;
                            oParamark.LeftIndent = 6;
                            for (int countrows = 1; countrows <= qusList.Length; countrows++)
                            {
                                oParamark.Range.Text = countrows + "、" + qusList[countrows - 1].SubjectContent;
                                oParamark.Range.InsertParagraphAfter();
                            }
                    //        break;
                    //    }
                    //}
                    //else
                    //{
                    //    if (!ds_com.Tables[countdt].TableName.Equals("选择题") && !ds_com.Tables[countdt].TableName.Equals("填空题") && !ds_com.Tables[countdt].TableName.Equals("判断题") && !ds_com.Tables[countdt].TableName.Equals("问答题"))
                    //    {
                    //        oParamark.LeftIndent = 0;
                    //        oParamark.Range.Font.Bold = 1;
                    //        string anyType = ds_com.Tables[countdt].TableName;
                    //        oParamark.Range.Text = "\n" + anyType + "(共：" + ds_com.Tables[anyType].Rows.Count + "题)";
                    //        oParamark.Format.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
                    //        oParamark.Range.InsertParagraphAfter();
                    //        oParamark.Range.Font.Bold = 0;
                    //        oParamark.LeftIndent = 6;
                    //        for (int countrows = 1; countrows <= ds_com.Tables[anyType].Rows.Count; countrows++)
                    //        {
                    //            oParamark.Range.Text = countrows + "、" + ds_com.Tables[anyType].Rows[countrows - 1].ItemArray.GetValue(3).ToString();
                    //            //oParamark.Format.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
                    //            oParamark.Range.InsertParagraphAfter();
                    //        }

                    //    }
                //    //}
                //}
            }
            catch (Exception)
            {
                oDocAnswer.Close(ref oMissing, ref oMissing, ref oMissing);
                oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
                objWordObject.Wordflag = false;
                return objWordObject;
            }
            return objWordObject;
        }
        #endregion

        #region 输出考题答案
        private WordObject printfAnswer(Subject[] qusList)
        {
            try
            {
                string questionType = qusList[0].ThemeName;
                rng = oDocAnswer.Range(ref start, ref end);
                //for (int countdt = 0; countdt < ds_com.Tables.Count; countdt++)  //判断ds_com中的table数 即：题型数目
                //{
                    #region 输出选择题和判断题答案
                    if (questionType.Equals("选择题") || questionType.Equals("判断题"))
                    {
                //        if (ds_com.Tables[countdt].TableName.Equals(questionType))
                //        {
                            // Insert a title for the table and paragraph marks. 
                            rng.InsertBefore(questionType + "答案:");
                            rng.Font.Name = "宋体";
                            rng.Font.Size = 10;
                            rng.Font.Bold = 1;
                            rng.InsertParagraphAfter();
                            rng.SetRange(rng.End, rng.End);

                            int rowsCount = qusList.Length;
                            int maxNumColumns = 10;
                            int numColumns = 1;
                            int numRows = 1;
                            if (rowsCount > maxNumColumns)
                            {
                                numColumns = maxNumColumns;
                                numRows = (rowsCount / numColumns) * 2;
                                if (rowsCount % numColumns != 0)
                                {
                                    numRows++;
                                }
                            }
                            else
                            {
                                numColumns = rowsCount;
                            }

                            rng.Tables.Add(rng, numRows * 2, numColumns, ref oMissing, ref oMissing);  // Add the table.
                            tbl = this.oDocAnswer.Tables[1];   // Format the table and apply a style.
                            tbl.Range.Font.Size = 12;
                            tbl.Range.Font.Bold = 0;
                            tbl.Range.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle;
                            tbl.Range.Borders.OutsideLineWidth = WdLineWidth.wdLineWidth050pt;
                            tbl.Range.Cells.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle;
                            tbl.Range.Cells.Borders.InsideLineWidth = WdLineWidth.wdLineWidth050pt;

                            //设置文本对齐方式
                            tbl.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                            tbl.Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                            tbl.Columns.PreferredWidthType = WdPreferredWidthType.wdPreferredWidthPoints;
                            tbl.Columns.PreferredWidth = 40.44F;
                            tbl.Rows.HeightRule = WdRowHeightRule.wdRowHeightAtLeast;
                            tbl.Rows.Height = 20.85F;

                            for (int countrows = 1, c = 1, r = 1; countrows <= rowsCount; countrows++, c++)
                            {
                                if (c > numColumns)
                                {
                                    c = 1;
                                    r += 2;
                                }
                                // Insert document properties into cells. 
                                tbl.Cell(r, c).Range.Text = countrows.ToString();
                                tbl.Cell(r + 1, c).Range.Text = qusList[countrows-1].SubjectAnswer;
                                //设置单元格背景色
                                tbl.Rows[r].Shading.ForegroundPatternColor = WdColor.wdColorAutomatic;
                                tbl.Rows[r].Shading.BackgroundPatternColor = WdColor.wdColorGray15;
                            }
                            //break;
                        //}
                    }
                    #endregion

                    #region 输出填空题答案
                    else if (questionType.Equals("填空题"))
                    {
                        //if (ds_com.Tables[countdt].TableName.Equals(questionType))
                        //{
                            // Insert a title for the table and paragraph marks. 
                            rng.InsertBefore(questionType + "答案:");
                            rng.Font.Name = "宋体";
                            rng.Font.Size = 10;
                            rng.Font.Bold = 1;
                            rng.InsertParagraphAfter();
                            rng.SetRange(rng.End, rng.End);

                            int numRows = qusList.Length;
                            int numColumns = 2;
                            rng.Tables.Add(rng, numRows, numColumns, ref oMissing, ref oMissing);  // Add the table.
                            tbl = this.oDocAnswer.Tables[1];   // Format the table and apply a style.
                            tbl.Range.Font.Size = 12;
                            tbl.Range.Font.Bold = 0;
                            tbl.Range.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle;
                            tbl.Range.Borders.OutsideLineWidth = WdLineWidth.wdLineWidth050pt;
                            tbl.Range.Cells.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle;
                            tbl.Range.Cells.Borders.InsideLineWidth = WdLineWidth.wdLineWidth050pt;

                            //设置文本对齐方式
                            tbl.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                            tbl.Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                            //设置列宽
                            tbl.Columns.PreferredWidthType = WdPreferredWidthType.wdPreferredWidthPoints;
                            tbl.Columns[1].PreferredWidth = 40.44F;
                            tbl.Columns[2].PreferredWidth = 400.44F;

                            //设置单元格背景色
                            tbl.Columns[1].Shading.ForegroundPatternColor = WdColor.wdColorAutomatic;
                            tbl.Columns[1].Shading.BackgroundPatternColor = WdColor.wdColorGray15;

                            for (int countrows = 1; countrows <= numRows; countrows++)
                            {
                                // Insert document properties into cells. 
                                tbl.Cell(countrows, 1).Range.Text = countrows.ToString();
                                tbl.Cell(countrows, 2).Range.Text = qusList[countrows-1].SubjectAnswer;
                                tbl.Cell(countrows, 2).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                            }
                            //break;
                        //}
                    }
                    #endregion

                    #region 输出其他题型的答案
                    else
                    {
                        //if (!questionType.Equals("选择题") && !questionType.Equals("判断题") && !questionType.Equals("填空题"))
                        //{
                            Paragraph oParamark;
                            oParamark = oDocAnswer.Content.Paragraphs.Add(ref oMissing);
                            oParamark.Range.Font.Size = 10;
                            oParamark.Range.Font.Bold = 1;
                            oParamark.LeftIndent = 0;
                            oParamark.Range.Text = "\n" + questionType + "(共：" + qusList.Length + "题)";
                            oParamark.Format.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                            oParamark.Range.InsertParagraphAfter();
                            oParamark.Range.Font.Bold = 0;
                            for (int countrows = 1; countrows <= qusList.Length; countrows++)
                            {
                                oParamark.Range.Text = countrows + "." + qusList[countrows-1].SubjectAnswer;
                                oParamark.Range.InsertParagraphAfter();
                            }
                        //}
                    }
                    #endregion
                //}
            }
            catch (Exception )
            {
                oDoc.Close(ref oMissing, ref oMissing, ref oMissing);
                oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
                objWordObject.Wordflag = false;
                return objWordObject;
            }
            return objWordObject;
        }
        #endregion

        #region 根据书签设置卷首
        //使用模板
        private WordObject getWordDot2()
        {
            try
            {
                //object oMissing = System.Reflection.Missing.Value;
                object oTemplate = pathdot + "wordpagedot.dot";
                oDoc = oWord.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);
                //object oBookMark = "schoolname";    //设置书签名称
                //oDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = objExamPageInfo.SchoolName;   //根据书签设置内容
                //oBookMark = "typepage";
                //oDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = objExamPageInfo.TypePage;
                object oBookMark = "SubjectExam";
                oDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = objPaperInfo.suitSpecialty;
                oBookMark = "SubjectID";
                oDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = objPaperHeadInfo.courseID.ToString();
                oBookMark = "CourseName";
                oDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = objPaperHeadInfo.courseName;
                oBookMark = "TypeExam";
                oDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = objPaperInfo.testType;
                oBookMark = "TeacherName";
                oDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = objPaperHeadInfo.teacherName;
                oBookMark = "TimePage";
                oDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = objPaperInfo.paperTime;
            }
            catch (Exception )
            {
                oDoc.Close(ref oMissing, ref oMissing, ref oMissing);
                oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
                objWordObject.Wordflag = false;
                return objWordObject;
            }
            return objWordObject;
        }
        #endregion
    }
}
