using MWS.Data.InterFace;
using MWS.Data.Manager;
using MWS.Domain.Common.DataExporting;
using MWS.Domain.Dto;
using MWS.Domain.Prints;
using MWS.Domain.View.History;
using MWS.Library.Common;
using MWS.Library.Common.Module;
using MWS.Model;
using MWS.Model.Dto;
using MWSDomain.Common.CoreLib;
using System;
using System.Collections.Generic;
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.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace MWS.Domain.View.Weight
{
    /// <summary>
    /// WeightRecordPage.xaml 的交互逻辑
    /// </summary>
    public partial class WeightRecordPage : Page
    {
        private IWeight weightManage;
        private IDevice deviceManage;
        private ITeam teamManage;
        private IEntrance entranceManage;
        private int entranceId = 0;
        private int deviceId = 0;
        private int teamId = 0;
        private DateTime startTime;
        private DateTime endTime;
        private List<Zigbee> zigbees;
        private IZigbee zigbeeManager;
        public WeightRecordPage()
        {
            InitializeComponent();
            weightManage = new WeightManager();
            deviceManage = new DeviceManager();
            teamManage = new TeamManager();
            entranceManage = new EntranceManager();
            zigbeeManager = new ZigbeeManager();
        }
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            startTime = DateTime.Now.AddHours(-24);
            endTime = DateTime.Now;
            BindEntranceComboBox();
            BindDeviceComboBox();
            BindTeamComboBox();
            pagination.CurrentPageNumberChanging += Pagination_CurrentPageNumberChanging;
            btDataSelect.Content = startTime.ToString() + "-" + endTime.ToString();
           

            GetListData();
        }
        
        private void Pagination_CurrentPageNumberChanging(object sender, RoutedEventArgs e)
        {
            GetListData(pagination.CurrentPageNumber);
        }
        private void GetListData(int pageIndex = 1)
        {
            entranceId = Convert.ToInt32(entrance.SelectedValue);
            deviceId = Convert.ToInt32(device.SelectedValue);
            teamId = Convert.ToInt32(team.SelectedValue);
            var dateSelect = btDataSelect.Content.ToString().Split('-');
            startTime = dateSelect[0].ToDateTime();
            endTime = dateSelect[1].ToDateTime();
            PageData<RecordDto> pa = weightManage.GetAllRecords(entranceId, deviceId, teamId, startTime, endTime, pageIndex, pagination.PageDataCount);

            lstWeight.ItemsSource = pa.Data;

            pagination.TotalDataCount = pa.TotalCount;
            pagination.CurrentPageNumber = pageIndex;
        }
        private void search_Click(object sender, RoutedEventArgs e)
        {
            GetListData();
        }
        /// <summary>
        /// 获取料口类型
        /// </summary>
        /// <param name="selectIndex"></param>
        private void BindEntranceComboBox()
        {
            try
            {
                List<T_Entrance> entrances = entranceManage.GetAll("");

                List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
               
                foreach (var item in entrances)
                {
                    list.Add(new KeyValuePair<string, string>( item.Id.ToString(), item.Name ));
                }
                list.Insert(0, new KeyValuePair<string, string>("0", "全部"));
                entrance.ItemsSource = list;
                entrance.SelectedValuePath = "Key";
                entrance.DisplayMemberPath = "Value";
                entrance.SelectedIndex = 0;
            }
            catch (Exception ex)
            {

                throw;
            }

        }
        /// <summary>
        /// 获取车辆
        /// </summary>
        /// <param name="selectIndex"></param>
        private void BindDeviceComboBox()
        {
            try
            {
                //List<Device> devices = deviceManage.GetAll();

                zigbees = zigbeeManager.GetAll();
                List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
                //    (entrances.Select(c=>c.Id,c)
                //{
                //    new KeyValuePair<string, string>("0", "全部"),
                //    new KeyValuePair<string, string>("1", "1号料口"),
                //    new KeyValuePair<string, string>("2", "2号料口"),
                //    new KeyValuePair<string, string>("3", "3号料口")
                // };
                foreach (var item in zigbees)
                {
                    list.Add(new KeyValuePair<string, string>(item.Id.ToString(), item.Name));
                }
                list.Insert(0, new KeyValuePair<string, string>("0", "全部"));
               
                device.ItemsSource = list;
                device.SelectedValuePath = "Key";
                device.DisplayMemberPath = "Value";
                device.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
                {
                     new KeyValuePair<string, string>("0", "全部"),
                    new KeyValuePair<string, string>("1", "1号车"),
                    new KeyValuePair<string, string>("2", "2号车"),
                    new KeyValuePair<string, string>("3", "3号车")
                 };
                device.ItemsSource = list;
                device.SelectedValuePath = "Key";
                device.DisplayMemberPath = "Value";
                device.SelectedIndex = 0;
            }

        }
        /// <summary>
        /// 获取班组类型
        /// </summary>
        /// <param name="selectIndex"></param>
        private void BindTeamComboBox()
        {
            try
            {
                List<Team> teams = teamManage.GetAll("");

                List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
               
                foreach (var item in teams)
                {
                    list.Add(new KeyValuePair<string, string>(item.Id.ToString(), item.Name));
                }
                list.Insert(0, new KeyValuePair<string, string>("0", "全部"));

                team.ItemsSource = list;
                team.SelectedValuePath = "Key";
                team.DisplayMemberPath = "Value";
                team.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("0", "全部"),
                    new KeyValuePair<string, string>("1", "夜班"),
                    new KeyValuePair<string, string>("2", "白班"),
                    new KeyValuePair<string, string>("3", "中班")
                 };
                team.ItemsSource = list;
                team.SelectedValuePath = "Key";
                team.DisplayMemberPath = "Value";
                team.SelectedIndex = 0;
            }

        }

        private void BtnExport_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.SaveFileDialog fileDialog = new System.Windows.Forms.SaveFileDialog
            {
                Title = "Export Excel",
                Filter = "Excel(*.xlsx)|*.xlsx|Excel 97-2003(*.xls)|*.xls",
                ValidateNames = true,
                AddExtension = true,
                FileName = "称重记录" + DateTime.Now.ToString("yyyyMMdd")
            };
            if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                var source = weightManage.GetAllExportRecords(entranceId, deviceId, teamId, startTime, endTime);
               
                if (source != null)
                {
                    new WeightRecordReportExcelExporter().ExportToFile(fileDialog.FileName, source);
                }
            }

        }
        private delegate void DoPrintMethod(PrintDialog pdlg, DocumentPaginator paginator);
        private void print_Click(object sender, RoutedEventArgs e)
        {
            #region 打印预览

            #endregion
            DateTime now = DateTime.Now;
            List<RecordDto> details = new List<RecordDto>();
            details = weightManage.GetAllExportRecords(entranceId, deviceId, teamId, startTime, endTime);
            var source = new PrintTableDto<RecordDto>()
            {
                Title = "称重记录报告",
                LeftSubtitle = "统计方式：班组",
                RightSubtitle = "时间区间："+ startTime .ToString()+ " 至 "+endTime.ToString(),
                Footer = "共计：" + details.Sum(c => c.NetWeight) + " 吨",
                Columns = new List<HeaderColumnDto> { new HeaderColumnDto() { DisplayName = "设备", FiledName = "DeviceName", FormatString = "G" }, new HeaderColumnDto() { DisplayName = "班组", FiledName = "TeamName" }, new HeaderColumnDto() { DisplayName = "料口", FiledName = "EntranceName" }, new HeaderColumnDto() { DisplayName = "重量（吨）", FiledName = "NetWeight" }, new HeaderColumnDto() { DisplayName = "时间", FiledName = "Time" } },
                Data = details
            };
            PrintPreviewWindow previewWnd = new PrintPreviewWindow();
            previewWnd.LoadDocumentAndRender<RecordDto>("/Prints/Documents/PrintTableFlowDocument.xaml", source, new TableDocumentRenderer());
            previewWnd.Owner = Window.GetWindow(this);
            previewWnd.ShowInTaskbar = false;
            previewWnd.ShowDialog();
            #region 打印
            //PrintPreviewWindow printWnd = new PrintPreviewWindow();
            //PrintDialog pdlg = new PrintDialog();
            //FlowDocument doc = printWnd.LoadDocumentAndRender<WeightRecordDto>("/Prints/Documents/PrintTableFlowDocument.xaml", source, new TableDocumentRenderer());
            //Dispatcher.BeginInvoke(new DoPrintMethod(DoPrint), DispatcherPriority.ApplicationIdle, pdlg, ((IDocumentPaginatorSource)doc).DocumentPaginator);

            #endregion
        }
        private void DoPrint(PrintDialog pdlg, DocumentPaginator paginator)
        {
            pdlg.PrintDocument(paginator, "称重记录");
        }

        private void btDataSelect_Click(object sender, RoutedEventArgs e)
        {
            var dateSelect = btDataSelect.Content.ToString().Split('-');
            startTime = dateSelect[0].ToDateTime();
            endTime = dateSelect[1].ToDateTime();
            DateTimeSelectWindow dateTimeSelectWindow = new DateTimeSelectWindow(startTime, endTime);
            dateTimeSelectWindow.ShowDialog();
            if ((bool)dateTimeSelectWindow.DialogResult)
            {
                this.startTime = dateTimeSelectWindow.BeginTime;
                this.endTime = dateTimeSelectWindow.EndTime;
                btDataSelect.Content = dateTimeSelectWindow.BeginTime.ToString() + "-" + dateTimeSelectWindow.EndTime.ToString();
            };
        }
    }
}
