using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace AIRS
{
    /// <summary>
    /// GradeCount.xaml 的交互逻辑
    /// </summary>
    public partial class GradeCount : Window
    {
              
        
        //委托事件
        public delegate void SelectGrade(List<String> grade_name,Boolean state);
        public static event SelectGrade SelectGradeEvent;

        public List<string> list_grade = new List<string>();

        public Dictionary<String, int> gradesum = new Dictionary<String, int>();
        public Dictionary<String, String> aiRES = new Dictionary<String, String>();
        public String gradename = "";
        public String gradetitle = "";
        public GradeCount()
        {
            InitializeComponent();
        }

        private void BtnLogin_Click(object sender, RoutedEventArgs e)
        {
            list_grade.Clear();
            SelectGradeEvent(list_grade,true);
        }

        private void BtnExport_Click(object sender, RoutedEventArgs e)
        {
            if (gradesum.Keys.Count > 0)
            {
                string filename = "";
                //申明保存对话框 
                SaveFileDialog dlg = new SaveFileDialog();
                //默然文件后缀 
                dlg.DefaultExt = "xls";
                //文件后缀列表 
                dlg.Filter = "Excel Files|*.xls";
                //默然路径是系统当前路径 
                dlg.InitialDirectory = Directory.GetCurrentDirectory();
                //保存对话框是否bai记忆上次du打开的目录
                dlg.RestoreDirectory = false;
                dlg.FileName = gradename + " - " + gradetitle + ".xls";
                dlg.Title = "导出Excel文件到";
                //打开保存对话框 
                if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    filename = dlg.FileName;
                    if (filename.Trim() != "")
                    {
                        if (IsFileInUse(filename) && System.IO.File.Exists(filename))
                        {
                            System.Windows.Forms.MessageBox.Show("无法导出！选择导出的文件正在被使用！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return;
                        }
                        StreamWriter sw = new StreamWriter(filename, false, Encoding.GetEncoding("gb2312"));
                        StringBuilder sb = new StringBuilder();

                        //zm:
                        sb.Append("图片" + "\t");
                        sb.Append("级别" + "\t");
                        sb.Append(Environment.NewLine);

                        foreach (var res in aiRES)
                        {
                            //文件名+级别+其它
                            
                            sb.Append(res.Key+"\t");
                            sb.Append(res.Value + "\t");
                            sb.Append(Environment.NewLine);
                        }


                        sb.Append(gname.Content.ToString() + "\t");
                        sb.Append(gcount.Content.ToString() + "\t");
                        sb.Append(Environment.NewLine);
                        int sum = 0;
                        foreach(string key in gradesum.Keys)
                        {
                            System.Windows.Forms.Application.DoEvents();
                            sb.Append(key + "\t");
                            sb.Append(gradesum[key].ToString() + "\t");
                            sb.Append(Environment.NewLine);
                            sum += gradesum[key];
                        }

                        sb.Append("合计" + "\t");
                        sb.Append(sum.ToString() + "\t");

                        sw.Write(sb.ToString());
                        sw.Flush();
                        sw.Close();

                    }

                    if (System.Windows.Forms.MessageBox.Show("导出成功！\r\n是否打开Excel文件?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        System.Diagnostics.Process.Start(filename);
                    }

                }
            }
        }

        /// <summary>
        /// 检测文件是否被其他程序占用
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static bool IsFileInUse(string fileName)
        {
            bool inUse = true;
            FileStream fs = null;
            try
            {
                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None);
                inUse = false;
            }
            catch { }
            finally
            {
                if (fs != null)
                    fs.Close();
            }
            return inUse;//true表示正在使用,false没有使用  
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            double _top = this.gname.Height + 14;

            gradesum = gradesum.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value);

            foreach(string key in gradesum.Keys)
            {
                System.Windows.Controls.Label g_select = new System.Windows.Controls.Label();
                g_select.Width = 70;
                g_select.Height = 37;
                g_select.Content = "";
                g_select.Tag = key;
                g_select.BorderThickness = new System.Windows.Thickness(1);
                g_select.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center;
                g_select.SetValue(Canvas.TopProperty, _top);
                g_select.SetValue(Canvas.LeftProperty, 15.0);
                g_select.SetValue(Canvas.BottomProperty, double.NaN);
                g_select.SetValue(Canvas.RightProperty, double.NaN);
                g_select.FontSize = 20;
                g_select.FontWeight = FontWeights.Bold;
                g_select.BorderBrush = new SolidColorBrush(Colors.Black);
                canshow.Children.Add(g_select);

                System.Windows.Controls.CheckBox checkBox = new System.Windows.Controls.CheckBox();
                checkBox.Tag = key;
                checkBox.IsChecked = false;
                checkBox.Checked += new RoutedEventHandler(check_checked);
                checkBox.Unchecked += new RoutedEventHandler(check_unchecked);
                checkBox.SetValue(System.Windows.Controls.CheckBox.StyleProperty, System.Windows.Application.Current.Resources["CheckBoxStyle"]);
                checkBox.SetValue(Canvas.TopProperty, _top - 13.5);
                checkBox.SetValue(Canvas.LeftProperty, 37.5);
                checkBox.SetValue(Canvas.BottomProperty, double.NaN);
                checkBox.SetValue(Canvas.RightProperty, double.NaN);
                canshow.Children.Add(checkBox);

                System.Windows.Controls.Label g_name = new System.Windows.Controls.Label();
                g_name.Width = 200;
                g_name.Height = 37;
                g_name.Content = key;
                g_name.Tag = "";
                //g_name.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(selectgrade);
                g_name.BorderThickness = new System.Windows.Thickness(1);
                g_name.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center;
                g_name.SetValue(Canvas.TopProperty, _top);
                g_name.SetValue(Canvas.LeftProperty, 85.0);
                g_name.SetValue(Canvas.BottomProperty, double.NaN);
                g_name.SetValue(Canvas.RightProperty, double.NaN);
                g_name.FontSize = 20;
                g_name.FontWeight = FontWeights.Bold;
                g_name.BorderBrush = new SolidColorBrush(Colors.Black);
                canshow.Children.Add(g_name);

                System.Windows.Controls.Label g_count = new System.Windows.Controls.Label();
                g_count.Width = 150;
                g_count.Height = 37;
                g_count.Content = gradesum[key].ToString();
                g_count.BorderThickness = new System.Windows.Thickness(1);
                g_count.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center;
                g_count.SetValue(Canvas.TopProperty, _top);
                g_count.SetValue(Canvas.LeftProperty, 284.5);
                g_count.SetValue(Canvas.BottomProperty, double.NaN);
                g_count.SetValue(Canvas.RightProperty, double.NaN);
                g_count.FontSize = 20;
                g_count.FontWeight = FontWeights.Bold;
                g_count.BorderBrush = new SolidColorBrush(Colors.Black);
                canshow.Children.Add(g_count);

                _top += 36;

                list_grade.Add(key);
            }
            this.canshow.Height = _top + 14;

            lbltitle.Content = gradename;
            ggrade.Content = gradetitle + ":";
        }

        private void check_checked(object sender,RoutedEventArgs e)
        {
            System.Windows.Controls.CheckBox cb = (System.Windows.Controls.CheckBox)sender;
            list_grade.Remove(cb.Tag.ToString());
            SelectGradeEvent(list_grade, false);
        }

        private void check_unchecked(object sender, RoutedEventArgs e)
        {
            System.Windows.Controls.CheckBox cb = (System.Windows.Controls.CheckBox)sender;
            list_grade.Add(cb.Tag.ToString());
            SelectGradeEvent(list_grade, false);
        }

        private void selectgrade(object sender, MouseButtonEventArgs e)
        {
            System.Windows.Controls.Label lbl = (System.Windows.Controls.Label)sender;
            if(lbl.Tag.ToString()=="")
            {
                lbl.Tag = "s";
                lbl.Foreground = new SolidColorBrush(Colors.Red);
                list_grade.Add(lbl.Content.ToString());
            }
            else
            {
                lbl.Tag = "";
                lbl.Foreground = new SolidColorBrush(Colors.Black);
                list_grade.Remove(lbl.Content.ToString());
            }
            SelectGradeEvent(list_grade,false);
        }

        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed) { DragMove(); }
        }

        private void imgmin_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            imgmin.Visibility = Visibility.Hidden;
            imgmin1.Visibility = Visibility.Visible;
        }

        private void imgmin1_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            imgmin.Visibility = Visibility.Visible;
            imgmin1.Visibility = Visibility.Hidden;
        }

        private void imgmin1_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        private void imgclosed_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            imgclosed.Visibility = Visibility.Hidden;
            imgclosed1.Visibility = Visibility.Visible;
        }

        private void imgclosed1_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            imgclosed.Visibility = Visibility.Visible;
            imgclosed1.Visibility = Visibility.Hidden;
        }

        private void imgclosed1_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            list_grade.Clear();
            SelectGradeEvent(list_grade, true);
        }
    }
}
