using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json;
using Microsoft.Practices.EnterpriseLibrary.Data;
using IL.Common;
using System.Configuration;

namespace WorkOrderControl
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private Database ctxMySQL;
        private Database ctxTask;

        private string setTime=System.Configuration.ConfigurationManager.AppSettings["SearchNum"];
        private void bt_begin_Click(object sender, EventArgs e)
        {
            bool stop = false;
            try
            {
                GetAPItoken();
            }
            catch (Exception ec)
            {
                MessageBox.Show("错误：获取token失败。" + ec.Message);
                return;
            }
            //
            int pageindex = 1;
            int pagesize = 10;
            string begintime = dt_begin.Text;
            string endtime = dt_end.Text;

            while (!stop)
            {
                try
                {
                    int rtn = GetAPIData(begintime, endtime, pageindex, pagesize, tb_token.Text);
                    if (rtn == 0)
                    {
                        pageindex++;
                    }
                    else if (rtn == -3)
                    {
                        MessageBox.Show("数据库错误！");
                        return;
                    }
                    else if (rtn == -99)
                    {
                        break;
                    }
                    else
                    {
                        stop = true;
                    }
                    Application.DoEvents();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("错误："+ex.Message);
                    return;
                }
            }
            MessageBox.Show("完成！");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //MessageBox.Show(ConfigurationManager.ConnectionStrings["test"].ToString());
            dt_begin.Text = DateTime.Now.ToString("yyyy-MM-dd");
            dt_end.Text = DateTime.Now.ToString("yyyy-MM-dd");
            DatabaseProviderFactory factory = new DatabaseProviderFactory();
            ctxTask = factory.Create("costTask");
            ctxMySQL = factory.Create("test");

           
        }
        private int GetAPItoken()
        {
            //
            try
            {

                string url = @"https://zcy.qianzhoukj.com/api/Third/getApiToken"; 
                string tokenParam="{ \"appid\": \"zcybf33af1a8430dd03e018ca68ff0850c2\",\"appsecret\": \"ea323b6f56b37af9d8e170d95331530281a42ee2\"}";
                System.Net.HttpWebRequest req = null;
                System.Net.HttpWebResponse res = null;

                ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;

                req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);  //创建HTTP 请求
                req.Method = "POST";

                req.ContentType = "application/json";  //发送参数格式
                //req.Accept = "*/*";
                req.Timeout = 15000;
                //req.AllowAutoRedirect = false;
                req.ContentLength = 0;
                byte[] postData = Encoding.ASCII.GetBytes(tokenParam);
                req.ContentLength = postData.Length;
                req.GetRequestStream().Write(postData, 0, postData.Length);
  
                res = (System.Net.HttpWebResponse)req.GetResponse();   //获取请求返回的响应
                System.IO.StreamReader read = new System.IO.StreamReader(res.GetResponseStream()); //读取来自API 接口的响应中的内容，也就是它的体
                DataEntity msgEntity = new DataEntity();
                string message = JsonConvert.DeserializeObject(read.ReadToEnd().ToString()).ToString();
                if (message == "{\"msg\":\"ok\",\"status\":1,\"data\":[]}" || message == "{\r\n  \"msg\": \"ok\",\r\n  \"status\": 1,\r\n  \"data\": []\r\n}")
                {
                    return -99;
                }
                //Msg data = JsonConvert.DeserializeObject<Msg>(message);
                //return ExcuteData(data.data);
                Msg_token token_data = JsonConvert.DeserializeObject<Msg_token>(message);
                tb_token.Text = token_data.data.token;
                return 0;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private int GetAPIData(string begintime,string endtime,int pageindex,int pagesize,string token)
        {
            try
            {

                string url = @"http://zcy.qianzhoukj.com/api/Third/getRepairReportList?starttime={0}&endtime={1}&pages={2}&pagesize={3}";
                System.Net.HttpWebRequest req = null;
                System.Net.HttpWebResponse res = null;

                url = string.Format(url, begintime, endtime, pageindex, pagesize);
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;

                req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);  //创建HTTP 请求
                //req.ProtocolVersion = HttpVersion.Version10;
                req.Method = "GET";
                //ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
                //json字符串
                req.ContentType = "application/json";  //发送参数格式
                //string jsonParam = "{ \"name\":\"张憨憨\",\"sex\":\"女\",\"age\":\"12\"}";
                // byte[] byteData = Encoding.UTF8.GetBytes(jsonParam);
                //int length = byteData.Length;
                // req.ContentLength = length;
                //Stream writer = req.GetRequestStream();
                //writer.Write(byteData, 0, length);
                //writer.Close();
                req.Accept = "*/*";
                req.Timeout = 15000;
                req.AllowAutoRedirect = false;
                req.Headers.Add("token", token);
                res = (System.Net.HttpWebResponse)req.GetResponse();   //获取请求返回的响应
                System.IO.StreamReader read = new System.IO.StreamReader(res.GetResponseStream()); //读取来自API 接口的响应中的内容，也就是它的体
                DataEntity msgEntity = new DataEntity();
                string message=JsonConvert.DeserializeObject(read.ReadToEnd().ToString()).ToString();
                if (message == "{\"msg\":\"ok\",\"status\":1,\"data\":[]}" || message == "{\r\n  \"msg\": \"ok\",\r\n  \"status\": 1,\r\n  \"data\": []\r\n}")
                {
                    return -99;
                }
                Msg data = JsonConvert.DeserializeObject <Msg> (message);
                //textBox1.Text = data;  //输出StreamReader 中所有的流
                //textBox1.Text = data.msg;
                return ExcuteData(data.data);
                //return 0;
                
                return 0;
            }
            catch (Exception ex)
            {
                //Console.WriteLine("This program is expected to throw WebException on successful run." +
                //        "\n\nException Message :" + ex.Message);
                //if (ex.Status == WebExceptionStatus.ProtocolError)
                //{
                //    Console.WriteLine("Status Code : {0}", ((HttpWebResponse)ex.Response).StatusCode);
                //    Console.WriteLine("Status Description : {0}", ((HttpWebResponse)ex.Response).StatusDescription);
                //}
                //Console.WriteLine(ex.Message);
                throw ex;
                //return -1;
            }
        }
        private int ExcuteData(data[] datas)
        {
            try
            {
                string insert = @"INSERT INTO v_workorder_source_info (number,post_name,post_phone,fault,fault_detail,zcmc,szks,szksMc,submit_time,status,
allocate_time,comment_time,repair_man,fy,sum_price,end_time,gys,mark,address_val,address) 
VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}',{14},'{15}','{16}',{17},'{18}','{19}');";

                for (int i = 0; i < datas.Length; i++)
                {
                    var cmd = ctxMySQL.GetSqlStringCommand(insert);
                    var command = ctxMySQL.GetSqlStringCommand(string.Format(insert, datas[i].number, datas[i].post_name, datas[i].post_phone
                        , datas[i].fault, datas[i].fault_detail, datas[i].zcmc, datas[i].szks, datas[i].szksMc, datas[i].submit_time, datas[i].status,
                        datas[i].allocate_time, datas[i].comment_time,
                        datas[i].repair_man, datas[i].fy, datas[i].sum_price, datas[i].end_time, datas[i].gys, datas[i].mark,
                        datas[i].address_val, datas[i].address));
                    SqlDataAccess.ExecuteNonQuery(ctxMySQL, command);
                }
                return 0;
            }
            catch (Exception ex)
            {
                return -3;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                GetAPItoken();
            }catch(Exception ec)
            {
                MessageBox.Show(ec.Message);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            var date_now = DateTime.Now;
            try
            {
                GetAPItoken();
            }
            catch (Exception ec)
            {
                MessageBox.Show(ec.Message);
            }
            timer1.Enabled = true;
        }
    }
}
