FrmWoAHuiUpload.cs 9.73 KB
using GeneralLib;
using NetLib;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using static SunVoteARSPPT.ReportEx;

namespace SunVoteARSPPT
{
    public partial class FrmWoAHuiUpload : Form
    {
        public FrmWoAHuiUpload()
        {
            InitializeComponent();
        }

        private void FrmWoAHuiUpload_Load(object sender, EventArgs e)
        {
            GlobalInfo.SysLanguage.SetLanguage(this.Name, this);

            LoadSet();
            btnCreateID_Click(null, null);
        }

        class KeyID_DicPar
        {
            public int KeyID = 0;
            public Dictionary<string, VoterResultPar> DicPar = new Dictionary<string, VoterResultPar>();
        }
        private void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                string file = Path.GetFileNameWithoutExtension(Globals.SunVoteARSAddIn.Application.ActivePresentation.Name);
                string sResponseType = "'Choice','Order','Judge','Number','Text'";
                //var dicVoterScorePar = GetVoterScoreDetail(sResponseType);
                //Dictionary<string, VoterScorePar> dicVoterScorePar = GetVoterScorePar(sResponseType);
                Dictionary<string, TopicReusultPar> dicTopicResult = GetTopicResultPar(sResponseType);
                Dictionary<string, Dictionary<string, VoterResultPar>> dicVoterResultPar = GetVoterResultPar(sResponseType, dicTopicResult);
                var roster = RosterList.RosterLoad;
                var rosterEnabled = RosterList.RosterLoad.RosterEnabled;

                Dictionary<int, KeyID_DicPar> dicVID_TID_Par = new Dictionary<int, KeyID_DicPar>();
                Dictionary<string, double> dicTID_Score = new Dictionary<string, double>();
                foreach (var v in dicVoterResultPar)
                {
                    foreach (var vv in v.Value)
                    {
                        int vid = vv.Value.VoterID;
                        int keyID = vv.Value.KeyIDNum;
                        string tid = vv.Value.TopicID;
                        var par = vv.Value;
                        var KPar = new KeyID_DicPar() { KeyID = keyID, DicPar = new Dictionary<string, VoterResultPar>() };
                        if (!dicVID_TID_Par.ContainsKey(vid))
                            dicVID_TID_Par.Add(vid, KPar);

                        if (!dicVID_TID_Par[vid].DicPar.ContainsKey(tid))
                            dicVID_TID_Par[vid].DicPar.Add(tid, par);

                        if (!dicTID_Score.ContainsKey(tid))
                            dicTID_Score.Add(tid, 0);
                    }
                }
                Dictionary<int, KeyID_DicPar> dicVID_TID_Par_Sort = dicVID_TID_Par.OrderBy(o => o.Value.KeyID).ToDictionary(o => o.Key, o => o.Value);

                Dictionary<string, object> dicInfo = new Dictionary<string, object>();
                dicInfo.Add("title", txtTitle.Text);
                dicInfo.Add("id", txtID.Text);
                Dictionary<string, object> dicDataBody = new Dictionary<string, object>();

                var lstDataSend = new List<object>();
                lstDataSend.Add(dicInfo);
                lstDataSend.Add(dicDataBody);

                dicDataBody.Add("total", dicVID_TID_Par_Sort.Count);
                var lstData = new List<object>();
                dicDataBody.Add("data", lstData);
                foreach (var v in dicVID_TID_Par_Sort)
                {
                    var row = roster.GetRowByVoterID(v.Key + "");
                    var dicScore = dicTID_Score.ToDictionary(o => o.Key, o => o.Value);
                    foreach (var vv in v.Value.DicPar)
                    {
                        if (dicScore.ContainsKey(vv.Value.TopicID))
                            dicScore[vv.Value.TopicID] = vv.Value.Score;
                    }

                    Dictionary<string, object> dicData = new Dictionary<string, object>();
                    dicData.Add("设备SN", row.Cells[0]);
                    //dicData.Add("身份证号", "430105888888");
                    //dicData.Add("姓名", "XXX");
                    dicData.Add(roster.Columns[1].ColumnName, row.Cells[1]);
                    dicData.Add(roster.Columns[2].ColumnName, row.Cells[2]);
                    dicData.Add("考试标题", file);
                    dicData.Add("分项成绩", dicScore.Values.ToList());
                    dicData.Add("时间戳", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                    lstData.Add(dicData);
                }

                string s = MyJson.Serialize(lstDataSend);
                File.WriteAllText(GlobalInfo.APP_DIR + @"\send_json.txt", s);

                string res = Post(ServerUrl, s).ToLower();//{"code":100,"msg":"success","t":"服务器成功接收数据"}

                var dicRes = MyJson.DisSerialize<Dictionary<string, object>>(res);
                if ((dicRes != null) && (dicRes.ContainsKey("code")))
                {
                    string code = dicRes["code"] + "";
                    string msg = "";
                    if (dicRes.ContainsKey("t"))
                        msg = dicRes["t"] + "";
                    MessageBox.Show("返回代码" + code + ":\r\n" + msg);
                }
                else
                {
                    MessageBox.Show("服务器没有返回");
                }

                SaveSet();
            }
            catch (Exception ex)
            {
                SystemLog.WriterLog(ex, "btnSubmit_Click");
            }

        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        void SaveSet()
        {
            //保存
            //INIControl ini = INIControl.GetInstances(GlobalInfo.SYSTEM_CONFIG_PATH);
            //ini.WriteValue("UploadWoAHui", "Title", txtTitle.Text);
            Globals.SunVoteARSAddIn.Application.ActivePresentation.Tags.Add("WoAHui_Title", txtTitle.Text);
        }
        string ServerUrl = "";
        void LoadSet()
        {
            string file = Path.GetFileNameWithoutExtension(Globals.SunVoteARSAddIn.Application.ActivePresentation.Name);
            //ServerUrl = "http://193.112.248.202:8888/docking/receive";
            //加载
            INIControl ini = INIControl.GetInstances(GlobalInfo.SYSTEM_CONFIG_PATH);
            ServerUrl = ini.ReadString("UploadWoAHui", "ServerUrl", "");
            if (string.IsNullOrEmpty(ServerUrl))
            {
                ServerUrl = "http://193.112.248.202:8888/docking/receive";
                ini.WriteValue("UploadWoAHui", "ServerUrl", ServerUrl);
            }
            //txtTitle.Text = ini.ReadString("UploadWoAHui", "Title", file);
            txtTitle.Text = Globals.SunVoteARSAddIn.Application.ActivePresentation.Tags["WoAHui_Title"] + "";
            if (string.IsNullOrEmpty(txtTitle.Text))
                txtTitle.Text = file;
        }

        internal string Post(string Url, string jsonParas)
        {
            string res = "";
            string strURL = Url;

            //创建一个HTTP请求  
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
            //Post请求方式  
            request.Method = "POST";
            //内容类型
            request.ContentType = "text/html;charset=" + Encoding.UTF8.WebName;
            //request.ContentType = "application/x-www-form-urlencoded";
            request.Timeout = 5000;
            //设置参数,并进行URL编码 

            string paraUrlCoded = jsonParas;//System.Web.HttpUtility.UrlEncode(jsonParas);   

            byte[] payload;
            //将Json字符串转化为字节  
            payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
            //设置请求的ContentLength   
            request.ContentLength = payload.Length;
            //发送请求,获得请求流 

            Stream writer;
            try
            {
                writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
            }
            catch (Exception)
            {
                writer = null;
                Console.Write("连接服务器失败!");
            }
            //将请求参数写入流
            writer.Write(payload, 0, payload.Length);
            writer.Close();//关闭请求流

            String strValue = "";//strValue为http响应所返回的字符流
            HttpWebResponse response;
            try
            {
                //获得响应流
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = ex.Response as HttpWebResponse;
            }

            //Stream s = response.GetResponseStream();
            //Stream postData = request.InputStream;
            //StreamReader sRead = new StreamReader(s);
            //string postContent = sRead.ReadToEnd();
            //sRead.Close();

            response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            res = myStreamReader.ReadToEnd(); //myStreamReader.ReadBlock()
            //res += "  耗时毫秒=" + t.ElapsedMilliseconds;
            myStreamReader.Close();
            myResponseStream.Close();
            response.Close();


            return res;//返回Json数据
        }

        private void btnCreateID_Click(object sender, EventArgs e)
        {
            txtID.Text = DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(0, 10000).ToString().PadLeft(4, '0');//时间戳+4位随机值
        }
    }
}