using Caliburn.Micro;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Data.OleDb;
using System.Data.SQLite;
using System.Data;
using System.Configuration;
using SimpleCRM.ViewDAO;
using SimpleCRM.Units;
using Telerik.Windows.Controls;
using System.Collections;
using System.Windows.Data;
using System.Windows;
using Telerik.Windows.Controls.GridView;
using System.Globalization;
using SimpleCRM.Service;
using Telerik.Windows.Controls.Charting;
using System.ComponentModel;
using System.Windows.Media;
using NPOI.HSSF.UserModel;
using System.IO;
using NPOI.HPSF;
using NPOI.SS.UserModel;
namespace SimpleCRM.ViewModels
{
    public class OrderPrintViewModel : Caliburn.Micro.Screen, IHandle<OrderEventArgs>
    {
        private readonly IEventAggregator eventAggregator;
        private readonly OrderService orderService;
        private readonly GoodsService goodsService;
        public OrderPrintViewModel(IEventAggregator _eventAggregator, GoodsService _GoodsService)
        {
            eventAggregator = _eventAggregator;
            eventAggregator.Subscribe(this);
            goodsService = _GoodsService;
        }

        private ObservableCollection<Goods> goods = new ObservableCollection<Goods>();
        public ObservableCollection<Goods> Goods { get { return goods; } set { goods = value; NotifyOfPropertyChange(() => Goods); } }


        public Order CurrentOrder { get; set; }
        public void Handle(OrderEventArgs message)
        {
            eventAggregator.Unsubscribe(this);
            CurrentOrder = message.Order;
            this.Goods = goodsService.GetGoods(" orderid=" + CurrentOrder.ID);
        }

        protected override void OnViewLoaded(object view)
        {
            MakeExcel();
            this.TryClose();
        }

        private void RemoveMergedRegion(ISheet sheet, int rowIndex)
        {
            int MergedCount = sheet.NumMergedRegions;
            for (int i = MergedCount - 1; i >= 0; i--)
            {
                var temp = sheet.GetMergedRegion(i);
                if (temp.FirstRow == rowIndex)
                {
                    sheet.RemoveMergedRegion(i);
                }
            }
        }

        private void MakeExcel()
        {
            string strFilePath = AppDomain.CurrentDomain.BaseDirectory + @"tp\order.xls";
            HSSFWorkbook sourceBook = new HSSFWorkbook(new FileStream(strFilePath, FileMode.Open));
            HSSFWorkbook targetBook = new HSSFWorkbook();

            string title = "食品有限公司订单";
            DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
            dsi.Company = title;
            dsi.Category = title;

            SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
            si.Author = "ZJF"; //填加xls文件作者信息
            si.ApplicationName = "SimpleCRM"; //填加xls文件创建程序信息
            si.LastAuthor = "SimpleCRM"; //填加xls文件最后保存者信息
            si.Comments = "ZJF"; //填加xls文件作者信息
            si.Title = title; //填加xls文件标题信息
            si.Subject = title;//填加文件主题信息
            si.CreateDateTime = DateTime.Now;
            si.EditTime = 10;
            si.Keywords = title;
            si.LastSaveDateTime = DateTime.Now;
            si.RevNumber = "1.0.0.0";

            targetBook.DocumentSummaryInformation = dsi;
            targetBook.SummaryInformation = si;

            HSSFSheet sourceSheet = (HSSFSheet)sourceBook.GetSheetAt(0);
            sourceSheet.CopyTo(targetBook, title, true, true);
            HSSFSheet targetSheet = (HSSFSheet)targetBook.GetSheetAt(0);

            IRow row = targetSheet.GetRow(0);
            row = targetSheet.GetRow(1);
            row.GetCell(1).SetCellValue(CurrentOrder.Date);
            row.GetCell(4).SetCellValue(CurrentOrder.Code);
            row.GetCell(6).SetCellValue(CurrentOrder.CustomerType);

            row = targetSheet.GetRow(2);
            row.GetCell(1).SetCellValue(CurrentOrder.CustomerName);
            row.GetCell(4).SetCellValue(CurrentOrder.SalesDepartment);
            row.GetCell(6).SetCellValue(CurrentOrder.SaleAreaName);

            row = targetSheet.GetRow(3);
            row.GetCell(1).SetCellValue(CurrentOrder.Warehouse);
            row.GetCell(4).SetCellValue(CurrentOrder.SalerName);
            row.GetCell(6).SetCellValue(CurrentOrder.Remark);

            if (goods.Count > 1)
            {
                short oldFoodRowHeight = targetSheet.GetRow(6).Height;
                int canAddRowNumber = goods.Count - 1;
                int addingIndex = 6;
                IRow goodsRow = targetSheet.GetRow(5);
                for (int i = 0; i < canAddRowNumber; i++)
                {
                    IRow targetRow = targetSheet.CopyRow(5, addingIndex);
                    targetRow.Height = goodsRow.Height;
                    addingIndex++;
                }
                RemoveMergedRegion(targetSheet, 6);
                IRow convertFoodRow = targetSheet.GetRow(6);
                for (int j = 0; j < goodsRow.Cells.Count; j++)
                {
                    convertFoodRow.Cells[j].CellStyle = goodsRow.Cells[j].CellStyle;
                }
                targetSheet.GetRow(targetSheet.LastRowNum).Height = oldFoodRowHeight;
            }

            int goodsIndex = 5;
            int rowNumber = 1;
            foreach (var goodsItem in goods)
            {
                IRow rowItem = targetSheet.GetRow(goodsIndex);
                var cells = rowItem.Cells;
                cells[0].SetCellValue(rowNumber);
                cells[1].SetCellValue(goodsItem.Name);
                cells[2].SetCellValue(goodsItem.Unit);
                cells[3].SetCellValue(goodsItem.RowNum);
                cells[4].SetCellValue(goodsItem.Suttle);
                cells[4].SetCellValue(goodsItem.TaxPrice);
                cells[5].SetCellValue(goodsItem.Total);
                goodsIndex++;
                rowNumber++;
            }

            MemoryStream fileExcel = new MemoryStream();
            targetBook.Write(fileExcel);

            string orderFilePath = AppDomain.CurrentDomain.BaseDirectory + @"AAAAAA\" + CurrentOrder.Code + ".xls";
            FileStream fs = new FileStream(orderFilePath, FileMode.Create, System.IO.FileAccess.Write);
            byte[] buff = fileExcel.ToArray();
            fs.Write(buff, 0, buff.Length);
            fs.Close();
            fileExcel.Close();
            System.Diagnostics.Process.Start(orderFilePath);
        }

    }
}
