using Newtonsoft.Json.Linq;
using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.OpenXmlFormats.Wordprocessing;
using NPOI.SS.Formula.Eval;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XWPF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Mall.Common.Plugin
{
    /// <summary>
    /// npoi word帮助类
    /// </summary>
    public class NPOIWordHelper
    {
        /// <summary>
        /// 测试word导出
        /// </summary>
        /// <returns></returns>
        public bool CreateFistShopWord() {
            string path = "D:\\testfile\\test.docx";
            XWPFDocument doc = new XWPFDocument();

            // 添加段落
            XWPFParagraph gp = doc.CreateParagraph();
            gp.Alignment = ParagraphAlignment.CENTER;//水平居中
            XWPFRun gr = gp.CreateRun();
            gr.GetCTR().AddNewRPr().AddNewRFonts().ascii = "黑体";
            gr.GetCTR().AddNewRPr().AddNewRFonts().eastAsia = "黑体";
            gr.GetCTR().AddNewRPr().AddNewRFonts().hint = ST_Hint.eastAsia;
            gr.GetCTR().AddNewRPr().AddNewSz().val = (ulong)44;//2号字体
            gr.GetCTR().AddNewRPr().AddNewSzCs().val = (ulong)44;
            gr.GetCTR().AddNewRPr().AddNewB().val = true; //加粗
            gr.GetCTR().AddNewRPr().AddNewColor().val = "red";//字体颜色
            gr.SetText("成都首店经济创·领大奖");
            gr.AddCarriageReturn();
            gr.AppendText("奖项申报材料");

            gp = doc.CreateParagraph();
            gp.Alignment = ParagraphAlignment.CENTER;//水平居中
            gr = gp.CreateRun();
            CT_RPr rpr = gr.GetCTR().AddNewRPr();
            CT_Fonts rfonts = rpr.AddNewRFonts();
            rfonts.ascii = "宋体";
            rfonts.eastAsia = "宋体";
            rpr.AddNewSz().val = (ulong)21;//5号字体
            rpr.AddNewSzCs().val = (ulong)21;
            gr.SetText("（奖项3：2019年度成都首发贡献奖）");
            gr.AddCarriageReturn();
            gr.AppendText("时间要求：2019年1月 - 2020年6月");
            gr.AddCarriageReturn();
            gr.AppendText("对象要求：品牌或载体举办皆可");
            gp = doc.CreateParagraph();

            //添加表格
            XWPFTable table = doc.CreateTable(2, 2);//创建表格 行/列
            CT_Tbl m_CTTbl = doc.Document.body.GetTblArray()[0];//获得文档第一张表
            CT_TblPr m_CTTblPr = m_CTTbl.AddNewTblPr();
            m_CTTblPr.AddNewTblW().w = "8000"; //表宽
            m_CTTblPr.AddNewTblW().type = ST_TblWidth.dxa;
            m_CTTblPr.tblpPr = new CT_TblPPr
            {
                tblpX = "0",//表左上角坐标
                tblpY = "0",
                tblpXSpec = ST_XAlign.center,//若不为“Null”，则优先tblpX，即表由tblpXSpec定位
                tblpYSpec = ST_YAlign.center,//若不为“Null”，则优先tblpY，即表由tblpYSpec定位  
                leftFromText = (ulong)180,
                rightFromText = (ulong)180,
                vertAnchor = ST_VAnchor.text,
                horzAnchor = ST_HAnchor.page
            };//表定位


            #region 行赋值
            CT_TcPr m_Pr = table.GetRow(0).GetCell(0).GetCTTc().AddNewTcPr();
            m_Pr.tcW = new CT_TblWidth() { w = "2500", type = ST_TblWidth.dxa };

            table.GetRow(0).Height = 1000;
            table.GetRow(0).GetCell(0).SetVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
            table.GetRow(0).GetCell(0).SetText("企业名称");
            table.GetRow(0).GetCell(1).SetVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
            table.GetRow(0).GetCell(1).SetText("小老弟奎哥就是大观看的睡觉啦");

            table.GetRow(1).Height = 1000;
            table.GetRow(1).GetCell(0).SetVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
            table.GetRow(1).GetCell(0).SetText("图文详情");
            var cell = table.GetRow(1).GetCell(1);
            cell.SetVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);

            var cW = 3000;//单元格的宽度和高度
            var cH = 3000;

            //得到要插入的图片
            var img = new FileStream("C:\\Users\\Administrator\\Desktop\\testImage\\视频文件\\通用欢迎图.jpg", FileMode.Open, FileAccess.Read);

            //进行图片插入

            XWPFParagraph p = cell.AddParagraph();
            XWPFRun run = p.CreateRun();
            var widthPic = (int)((double)cW / 587 * 38.4 * 9525);
            var heightPic = (int)((double)cH / 587 * 38.4 * 9525);
            run.AddPicture(img, (int)NPOI.XWPF.UserModel.PictureType.JPEG, "11.png", widthPic, heightPic);
            #endregion

            using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
            {
                doc.Write(fs);
                Console.WriteLine("生成word成功");
            }

            return true;
        }

        /// <summary>
        /// 榜单报名生成word
        /// </summary>
        /// <param name="path">本地存储路径</param>
        /// <param name="enrollContent"></param>
        /// <param name="prizeName"></param>
        /// <param name="time"></param>
        /// <param name="objectName"></param>
        /// <returns></returns>
        public bool CreateFistShopEnrollWord(string path, string enrollContent, string prizeName, string time, string objectName)
        {
            XWPFDocument doc = new XWPFDocument();

            #region 头部组装
            // 添加段落
            XWPFParagraph gp = doc.CreateParagraph();
            gp.Alignment = ParagraphAlignment.CENTER;//水平居中
            XWPFRun gr = gp.CreateRun();
            gr.GetCTR().AddNewRPr().AddNewRFonts().ascii = "黑体";
            gr.GetCTR().AddNewRPr().AddNewRFonts().eastAsia = "黑体";
            gr.GetCTR().AddNewRPr().AddNewRFonts().hint = ST_Hint.eastAsia;
            gr.GetCTR().AddNewRPr().AddNewSz().val = (ulong)44;//2号字体
            gr.GetCTR().AddNewRPr().AddNewSzCs().val = (ulong)44;
            gr.GetCTR().AddNewRPr().AddNewB().val = true; //加粗
            gr.GetCTR().AddNewRPr().AddNewColor().val = "red";//字体颜色
            gr.SetText("成都首店经济创·领大奖");
            gr.AddCarriageReturn();
            gr.AppendText("奖项申报材料");

            gp = doc.CreateParagraph();
            gp.Alignment = ParagraphAlignment.CENTER;//水平居中
            gr = gp.CreateRun();
            CT_RPr rpr = gr.GetCTR().AddNewRPr();
            CT_Fonts rfonts = rpr.AddNewRFonts();
            rfonts.ascii = "宋体";
            rfonts.eastAsia = "宋体";
            rpr.AddNewSz().val = (ulong)21;//5号字体
            rpr.AddNewSzCs().val = (ulong)21;
            gr.SetText("（" + prizeName + "）");
            gr.AddCarriageReturn();
            gr.AppendText("时间要求：" + time);
            gr.AddCarriageReturn();
            gr.AppendText("对象要求：" + objectName);
            gp = doc.CreateParagraph();
            #endregion

            #region 解析报名内容
            if (string.IsNullOrEmpty(enrollContent))
            {
                return false;
            }
            List<WordFormDataItem> elist = JsonHelper.DeserializeObject<List<WordFormDataItem>>(enrollContent);
            elist = elist.Where(x => x.CompKey != "ImageUploadComp" && x.CompKey != "VideoUploadComp").ToList();
            if (!elist.Any())
            {
                return false;
            }
            int rowNumT = elist.Count();
            #endregion

            //添加表格
            XWPFTable table = doc.CreateTable(rowNumT, 2);//创建表格 行/列
            CT_Tbl m_CTTbl = doc.Document.body.GetTblArray()[0];//获得文档第一张表
            CT_TblPr m_CTTblPr = m_CTTbl.AddNewTblPr();
            m_CTTblPr.AddNewTblW().w = "9000"; //表宽
            m_CTTblPr.AddNewTblW().type = ST_TblWidth.dxa;
            m_CTTblPr.tblpPr = new CT_TblPPr
            {
                tblpX = "0",//表左上角坐标
                tblpY = "0",
                tblpXSpec = ST_XAlign.center,//若不为“Null”，则优先tblpX，即表由tblpXSpec定位
                tblpYSpec = ST_YAlign.center,//若不为“Null”，则优先tblpY，即表由tblpYSpec定位  
                leftFromText = (ulong)180,
                rightFromText = (ulong)180,
                vertAnchor = ST_VAnchor.text,
                horzAnchor = ST_HAnchor.page
            };//表定位
            //设置列宽
            CT_TcPr m_Pr = table.GetRow(0).GetCell(0).GetCTTc().AddNewTcPr();
            m_Pr.tcW = new CT_TblWidth() { w = "2500", type = ST_TblWidth.dxa };

            #region 行赋值
            int rowNum = 0;
            foreach (var item in elist)
            {
                #region 解析值
                string Name = "";
                string Value = "";
                if (item.CompKey == "SingleLineText" || item.CompKey == "MultiLineText")
                {
                    var obj = JsonHelper.DeserializeObject<WordTextItem>(item.CompData.ToString());
                    Name = obj.Name;
                    Value = obj.TextValue;
                }
                else if (item.CompKey == "DorpDownList")
                {
                    var obj = JsonHelper.DeserializeObject<WordSelectItem>(item.CompData.ToString());
                    Name = obj.Name;

                    var olist = obj.OptionList.Where(x => ("," + obj.OptionValue + ",").Contains("," + x.Id + ",")).ToList();
                    Value = string.Join(",", olist.Select(x => x.Name));
                }
                else
                {
                    continue;
                }
                #endregion
                table.GetRow(rowNum).Height = 1000;
                table.GetRow(rowNum).GetCell(0).SetVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
                table.GetRow(rowNum).GetCell(0).SetText(Name);
                table.GetRow(rowNum).GetCell(1).SetVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
                table.GetRow(rowNum).GetCell(1).SetText(Value);
                rowNum++;
            }
            #endregion

            using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
            {
                doc.Write(fs);
                Console.WriteLine("生成word成功");
            }

            return true;
        }
    }

    /// <summary>
    /// 自定义数据
    /// </summary>
    public class WordFormDataItem
    {
        /// <summary>
        ///组件Key
        /// </summary>
        public string CompKey { get; set; }

        /// <summary>
        /// 是否选中
        /// </summary>
        public bool isCked { get; set; }

        /// <summary>
        /// 组件对象
        /// </summary>
        public object CompData { get; set; }
    }

    /// <summary>
    /// 文本对象
    /// </summary>
    public class WordTextItem
    {
        /// <summary>
        /// 名字
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 字数(0-不限)
        /// </summary>
        public int WordsLength { get; set; }

        /// <summary>
        /// 是否必填
        /// </summary>
        public bool IsRequire { get; set; }

        /// <summary>
        /// 文本值
        /// </summary>
        public string TextValue { get; set; }

        /// <summary>
        /// 备注
        /// </summary>
        public string Remark { get; set; }
    }

    /// <summary>
    /// 下拉框对象
    /// </summary>
    public class WordSelectItem
    {
        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 是否多选
        /// </summary>
        public bool IsMultiple { get; set; }

        /// <summary>
        /// 选项值（以英文逗号相隔）
        /// </summary>
        public string OptionValue { get; set; }

        /// <summary>
        /// 是否必填
        /// </summary>
        public bool IsRequire { get; set; }

        /// <summary>
        /// 选项列表
        /// </summary>
        public List<WordSelectOption> OptionList { get; set; }

        /// <summary>
        /// 备注
        /// </summary>
        public string Remark { get; set; }
    }

    /// <summary>
    /// 选项列表
    /// </summary>
    public class WordSelectOption
    {
        /// <summary>
        /// 编号
        /// </summary>
        public int Id { get; set; }

        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; set; }
    }

}