using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Net;
using System.Xml;
using System.Data.SqlClient;
namespace gwk_pic_downs
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                if (File.Exists(Application.StartupPath + @"\back.txt"))
                {
                    File.Delete(Application.StartupPath + @"\back.txt");
                }
                string filename = Application.StartupPath + @"\zhixing.xml";
               
                XmlDocument document = new XmlDocument();
                document.Load(filename);
                XmlNode node = document.SelectSingleNode("boot");

                string keyword = node.SelectSingleNode("keyword").InnerText;
                string ori_img = node.SelectSingleNode("ori_img").InnerText;
                string fmt_img = node.SelectSingleNode("fmt_img").InnerText;
                string old_ori_img = node.SelectSingleNode("old_ori_img").InnerText;

                int width = Convert.ToInt32(node.SelectSingleNode("width").InnerText);
                int height = Convert.ToInt32(node.SelectSingleNode("heigh").InnerText);
                string server = @node.SelectSingleNode("server").InnerText;
                string database = node.SelectSingleNode("database").InnerText;
                string loginName = node.SelectSingleNode("loginname").InnerText;
                string password = node.SelectSingleNode("password").InnerText;

                COperationsSQL ssql = new COperationsSQL(server, database, loginName, password);
                string[] strArray = keyword.Split(new char[] { ',' });

                for (int i = 0; i < strArray.Length; i++)
                {
                    Console.WriteLine("下载图片 >>>> " + strArray[i].ToString());
                    writeErr("下载图片 >>>> " + strArray[i].ToString());
                    SqlDataReader reader = ssql.ExecuteReader("select id,picurl,errcount from gwkproduct where ident like '" + strArray[i] + "_%' and flag=0");
                    while (reader.Read())
                    {
                        string picurl = reader["picurl"].ToString();
                        int id = Convert.ToInt32(reader["id"]);
                        int errcount = Convert.ToInt32(reader["errcount"]);
                        //http://image.all3c.com/images/upload/l/9113_l.jpg
                        string temp_path = picurl.Substring(picurl.IndexOf('/') + 2, picurl.LastIndexOf('/') - 7).Replace(':', '_'); //  image.all3c.com/images/upload/l

                        string ori_img_path = ori_img + "/" + temp_path;  //  原来下载的路径
                        string fmt_img_path = fmt_img + "/" + temp_path;
                        string old_ori_img_path = old_ori_img + "/" + temp_path;

                        string fileName = picurl.Substring(picurl.LastIndexOf('/') + 1).Replace('?', '_'); ;  // 除去前面的  9113_l.jpg

                        string ori_filename = ori_img_path + "/" + fileName;  //本地的文件
                        string fmt_filename = fmt_img_path + "/" + fileName;
                        string old_ori_filemane = old_ori_img_path + "/" + fileName;


                        string houzhui = fileName.Substring(fileName.LastIndexOf('.') + 1);
                        //if (houzhui != "jpg" || houzhui != "gif" || houzhui != "bmp")
                        if (houzhui != "jpg")  //不是图片格式,不下载
                        {
                            errcount = errcount + 1;
                            Console.WriteLine("ID为" + id + "的图片格式错误,禁止下载!**********************错误!!!");
                            writeErr("ID为" + id + "的图片格式错误,禁止下载**********************错误!!!!");
                            continue;
                        }

                        if (File.Exists(old_ori_filemane))   //看看备份中是否有该图片,有不下载,直接压缩,更改数据库flag为1
                        {
                            Console.WriteLine("ID为 "+id+" 所在的图片存在,直接压缩并更改flag为1");
                            writeErr("ID为 "+id+" 所在的图片存在,直接压缩并更改flag为1");
                            Directory.CreateDirectory(fmt_img_path);  //创建 压缩的目录
                            CreateImage(old_ori_filemane, fmt_filename, width, height);  //压缩图片并更改数据库flag为1
                            new COperationsSQL(server, database, loginName, password).ExecuteNonQuery("update gwkproduct set flag=1 where id='" + id + "'");
                            continue;
                        }

                        if (errcount >= 3)
                        {
                            Console.WriteLine("ID为 "+id+" 的errCount为 "+errcount.ToString()+" 不下载!*******************错误!!!");
                            writeErr("ID为 " + id + " 的errCount为 " + errcount.ToString() + " 不下载!*******************错误!!!");
                            continue;
                        }
                        while (errcount < 3)
                        {
                            try
                            {
                                Console.WriteLine("下载ID为 " + id + " 的图片! ");
                                Directory.CreateDirectory(ori_img_path);    //建立下载目录
                                WebClient myclient = new WebClient();
                                myclient.DownloadFile(picurl, ori_filename);  //下载图片到本地

                                if (File.Exists(ori_filename))   //如果下载到本地了
                                {

                                    Directory.CreateDirectory(fmt_img_path);  //创建 压缩的目录
                                    CreateImage(ori_filename, fmt_filename, width, height);  //压缩图片并更改数据库flag为1
                                    new COperationsSQL(server, database, loginName, password).ExecuteNonQuery("update gwkproduct set flag=1 where id='" + id + "'");


                                    //复制图片到old_ori_jmg
                                    Directory.CreateDirectory(old_ori_img_path);  //创建 备份的目录
                                    File.Copy(ori_filename, old_ori_filemane);
                                    break;
                                }
                                else
                                {
                                    errcount = errcount + 1;
                                }
                            }
                            catch (Exception exc)
                            {
                                Console.WriteLine("ID为 " + id + " 的图片下载错误,错误原因:" + exc.Message + " *******************错误!!!");
                                writeErr("ID为 " + id + " 的图片下载错误,错误原因:" + exc.Message + " *******************错误!!!");
                                errcount = errcount + 1;
                                new COperationsSQL(server, database, loginName, password).ExecuteNonQuery("update gwkproduct set errcount='"+errcount+"' where id='" + id + "'");
                            }

                        }

 

                    }
                    reader.Close();
                    Console.WriteLine("图片 >>>> " + strArray[i] + "下载完毕!");
                    writeErr("图片 >>>> " + strArray[i] + "下载完毕!");
                }
                Console.WriteLine("全部图片下载完毕!!!!!!!");
                writeErr("全部图片下载完毕!!!!!!!");
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message + " *******************错误!!!");
                writeErr(exception.Message + " *******************错误!!!");

            }
            finally
            {
                //Console.ReadKey();
            }

        }

        public static void writeErr(string errstring)
        {
            string errfile = Application.StartupPath + @"\back.txt";
            StreamWriter sw = new StreamWriter(errfile,true);
           
           sw.WriteLine(errstring);
           sw.Close();
           
        }
        public static void CreateImage(string oPath, string tPath, int width, int height)
        {
            int num;
            int num2;
            Graphics graphics;
            Bitmap image = new Bitmap(oPath);
            if ((image.Width <= width) && (image.Height <= height))
            {
                num = (int)Math.Round((decimal)((width - image.Width) / 2M));
                num2 = (int)Math.Round((decimal)((height - image.Height) / 2M));
                Bitmap bitmap2 = new Bitmap(width, height);
                using (graphics = Graphics.FromImage(bitmap2))
                {
                    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    graphics.Clear(Color.White);
                    graphics.DrawImage(image, num, num2);
                }
                bitmap2.Save(tPath);
                bitmap2.Dispose();
            }
            else
            {
                int num3;
                int num4;
                if ((width * image.Height) < (height * image.Width))
                {
                    num3 = width;
                    num4 = (int)Math.Round((decimal)((image.Height * width) / image.Width));
                    num = 0;
                    num2 = (int)Math.Round((decimal)((height - num4) / 2M));
                }
                else
                {
                    num3 = (int)Math.Round((decimal)((image.Width * height) / image.Height));
                    num4 = height;
                    num = (int)Math.Round((decimal)((width - num3) / 2M));
                    num2 = 0;
                }
                Bitmap bitmap3 = new Bitmap(num3, num4);
                using (graphics = Graphics.FromImage(bitmap3))
                {
                    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    graphics.FillRectangle(Brushes.White, 0, 0, num3, num4);
                    graphics.DrawImage(image, 0, 0, num3, num4);
                }
                Bitmap bitmap4 = new Bitmap(width, height);
                using (graphics = Graphics.FromImage(bitmap4))
                {
                    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    graphics.Clear(Color.White);
                    graphics.DrawImage(bitmap3, num, num2);
                }
                bitmap4.Save(tPath);
                bitmap4.Dispose();
            }
        }

 

 


    }
}