using HSUCO_Cargo_Garage_Operation_Program.CustomForm;
using MetroFramework;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace HSUCO_Cargo_Garage_Operation_Program.CustomUserControl
{
    public partial class WaitingList : UserControl
    {
        public WaitingList() => InitializeComponent();

        private void ApplicantList_Load(object sender, EventArgs e)
        {
            metroComboBox_SearchType.SelectedIndex = 0;
        }

        private void DataChange()
        {
            var applicants = Database.GetApplicantWait();
            switch (metroComboBox_SearchType.SelectedIndex)
            {
                case 0:
                    applicants = applicants.Where(x => x.CargoVehicleNumber.Contains(metroTextBox_Search.Text.Trim())).ToList();

                    break;

                case 1:
                    applicants = applicants.Where(x => x.PassengerVehicleNumber.Contains(metroTextBox_Search.Text.Trim())).ToList();
                    break;

                case 2:
                    applicants = applicants.Where(x => x.Name.Contains(metroTextBox_Search.Text.Trim())).ToList();
                    break;

                case 3:
                    applicants = applicants.Where(x => x.Phone.Contains(metroTextBox_Search.Text.Trim())).ToList();
                    break;

                case 4:
                    applicants = applicants.Where(x => x.Address.Contains(metroTextBox_Search.Text.Trim())).ToList();
                    break;
            }

            var dataTable = new DataTable();
            dataTable.Columns.Add("순위");
            dataTable.Columns.Add("접수번호");
            dataTable.Columns.Add("신청구분");
            dataTable.Columns.Add("성명(법인명)");
            dataTable.Columns.Add("생년월일(법인등록번호)");
            dataTable.Columns.Add("연락처");
            dataTable.Columns.Add("주소");
            dataTable.Columns.Add("차량번호(화물)");
            dataTable.Columns.Add("차종(화물)");
            dataTable.Columns.Add("차량번호(승용)");
            dataTable.Columns.Add("차종(승용)");
            dataTable.Columns.Add("차량 타입");
            dataTable.Columns.Add("신청일");

            string order;
            int countLarge = 1;
            int countOversized = 1;
            for (int i = 0; i < applicants.Count; i++)
            {
                if (applicants[i].VehicleType == 0)
                {
                    order = $"대형-{countLarge}";
                    countLarge++;
                }
                else
                {
                    order = $"특대형-{countOversized}";
                    countOversized++;
                }
                string owner = string.Empty;
                switch (applicants[i].Owenr)
                {
                    case EOwner.Individual:
                        owner = "개인";
                        break;

                    case EOwner.IndividualIntoCorporation:
                        owner = "지입";
                        break;
                    case EOwner.Corporation:
                        owner = "법인";
                        break;
                }

                string vehicleType = "";
                switch (applicants[i].VehicleType)
                {
                    case EVehicleType.Large_Down:
                        vehicleType = "대형(4.5톤 미만)";
                        break;
                    case EVehicleType.Large_Up:
                        vehicleType = "대형(4.5톤 이상)";
                        break;
                    case EVehicleType.Oversized_Down:
                        vehicleType = "특대형(4.5톤 미만)";
                        break;
                    case EVehicleType.Oversized_Up:
                        vehicleType = "특대형(4.5톤 이상)";
                        break;
                }
                dataTable.Rows
                    .Add(
                    order,
                    applicants[i].No,
                    owner,
                    applicants[i].Name,
                    applicants[i].PersonalNumber,
                    applicants[i].Phone,
                    applicants[i].Address,
                    applicants[i].CargoVehicleNumber,
                    applicants[i].CargoVehicleName,
                    applicants[i].PassengerVehicleNumber,
                    applicants[i].PassengerVehicleName,
                    vehicleType,
                    applicants[i].Date.DateTimeDatabase()

                    );
            }

            dataGridView_List.DataSource = dataTable;
            dataGridView_List.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
        }

        private void metroButton_Search_Click(object sender, EventArgs e) => DataChange();

        private void metroButton_Delete_Click(object sender, EventArgs e)
        {
            var selectCount = dataGridView_List.SelectedRows.Count;
            if (selectCount == 0) return;
            string no = dataGridView_List.SelectedRows[0].Cells[1].Value.ToString();

            var message = "선태하신 화물챠랑번호 " + dataGridView_List.SelectedRows[0].Cells[7].Value.ToString() + "을 삭제 하시겠습니까?";

            if (MetroMessageBox.Show(this, message, "삭제", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
            {
                bool result = Database.DeleteApplicantList(no);
                if (result)
                {
                    MetroMessageBox.Show(this, "삭제에 성공하였습니다.", "성공", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    DataChange();
                }
                else
                {
                    MetroMessageBox.Show(this, "삭제에 실패하였습니다.", "성공", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void metroButton_UpdateUser_Click(object sender, EventArgs e)
        {
            var count = dataGridView_List.Rows.Count;
            if (count == 0) return;

            Promotion promotion = new Promotion("대기자 이용기간", "이용 시작일", "이용 종료일");
            DialogResult dialogResult = promotion.ShowDialog();
            if (dialogResult != DialogResult.OK)
            {
                return;
            }
            DateTime startDate = promotion.StartDate;
            LeftAreaInformation leftAreaInformation = Database.GetLeftArea(startDate, Global.GlobalSettings.CargoLargeMaxCount, Global.GlobalSettings.CargoOversizedMaxCount);
            if (leftAreaInformation.Large.Count + leftAreaInformation.OverSized.Count == 0)
            {
                MetroMessageBox.Show(this, "남은 자리가 없습니다", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            LeftUserInformation leftUserInformation = Database.GetLeftUserWait(startDate);
            if (leftUserInformation.Large + leftUserInformation.OverSized == 0)
            {
                MetroMessageBox.Show(this, "당첨처리 할수 있는 인원이 없습니다.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            // 자릿수가 0 이고 추첨하는 인원이 
            bool largeBool = leftAreaInformation.Large.Count == 0 || leftUserInformation.Large == 0;
            bool overSizedBool = leftAreaInformation.OverSized.Count == 0 || leftUserInformation.OverSized == 0;
            StringBuilder stringBuilder;
            if (largeBool && overSizedBool)
            {
                stringBuilder = new StringBuilder();
                stringBuilder.AppendLine("현재 당첨 가능한 사람/자리 가 없습니다.");
                stringBuilder.AppendLine($"대　형 대기인원/남은자리 : {leftUserInformation.Large}/{leftAreaInformation.Large.Count}");
                stringBuilder.Append($"특대형 대기인원/남은자리 : {leftUserInformation.OverSized}/{leftAreaInformation.OverSized.Count}");
                MetroMessageBox.Show(this, stringBuilder.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;

            }
            stringBuilder = new StringBuilder();
            stringBuilder.AppendLine("다음 사항을 추첨하시겠습니까?");
            stringBuilder.AppendLine($"대　형 대기인원/남은자리 : {leftUserInformation.Large}/{leftAreaInformation.Large.Count}");
            stringBuilder.Append($"특대형 대기인원/남은자리 : {leftUserInformation.OverSized}/{leftAreaInformation.OverSized.Count}");
            dialogResult = MetroMessageBox.Show(this, stringBuilder.ToString(), "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
            if (dialogResult == DialogResult.Yes)
            {
                List<ResultSetUserListInformation> result = Database.SetUserListForApplicantWait(leftAreaInformation, promotion.EndDate);
                InsertResult insertResult = new InsertResult(result);
                insertResult.ShowDialog();
                DataChange();
            }
        }

        private void metroButton_ExportExcel_Click(object sender, EventArgs e)
        {
            var excelWrapper = new ExcelWrapper();

            var saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "XLSX files (*.xlsx)|*.xlsx";

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                var result = excelWrapper.WriteDataTableToExcel((DataTable)dataGridView_List.DataSource, "대기자 리스트", saveFileDialog.FileName, "대기자 리스트", Environment.MachineName, DateTime.Now);
                if (result)
                {
                    MetroMessageBox.Show(this, "엑셀 파일 저장에 성공하였습니다.", "Excel Export", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    DataChange();
                }
                else
                {
                    MetroMessageBox.Show(this, "엑셀 파일 저장에 실패하였습니다.", "Excel Export", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void metroButton_UpdateUserData_Click(object sender, EventArgs e)
        {
            var selectCount = dataGridView_List.SelectedRows.Count;
            if (selectCount == 0) return;
            string no = dataGridView_List.SelectedRows[0].Cells[1].Value.ToString();

            UpdateUserInformation updateUserInformation = Database.GetUserData(EUserInformationType.ApplicantList, no);
            UpdateUserData updateUserData = new UpdateUserData(updateUserInformation);
            DialogResult dialogResult = updateUserData.ShowDialog();
            if (dialogResult == DialogResult.OK)
            {
                DataChange();
            }
        }

        private void metroButton_ManualPermission_Click(object sender, EventArgs e)
        {
            var selectCount = dataGridView_List.SelectedRows.Count;
            if (selectCount == 0) return;
            string no = dataGridView_List.SelectedRows[0].Cells[1].Value.ToString();
            // 수동 배차
            Promotion promotion = new Promotion("수동 이용기간", "이용 시작일", "이용 종료일");
            DialogResult dialogResult = promotion.ShowDialog();
            if (dialogResult != DialogResult.OK)
            {
                return;
            }
            DateTime startDate = promotion.StartDate;
            EVehicleType eVehicleType = Database.GetApplicantVehicleType(no);
            LeftAreaInformation leftAreaInformation = Database.GetLeftArea(startDate, Global.GlobalSettings.CargoLargeMaxCount, Global.GlobalSettings.CargoOversizedMaxCount);
            List<int> leftArea = eVehicleType == EVehicleType.Large_Up || eVehicleType == EVehicleType.Large_Down ? leftAreaInformation.Large : leftAreaInformation.OverSized;
            if (leftArea.Count == 0)
            {
                MetroMessageBox.Show(this, "현재 당첨 가능한 사람/자리 가 없습니다.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            ManualPermission manualPermission = new ManualPermission(eVehicleType == EVehicleType.Large_Down || eVehicleType == EVehicleType.Large_Up ? "대형" : "특대형", leftArea);
            DialogResult result = manualPermission.ShowDialog();
            if (result == DialogResult.OK)
            {
                bool setResult = Database.SetManualUserList(no, manualPermission.selectArea, promotion.StartDate, promotion.EndDate);
                if (setResult)
                {
                    MetroMessageBox.Show(this, "성공적으로 배정하였습니다.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    DataChange();
                }
                else
                {
                    MetroMessageBox.Show(this, "배정에 실패하였습니다..", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void metroButton_PrintReceipt_Click(object sender, EventArgs e)
        {
            var selectCount = dataGridView_List.SelectedRows.Count;
            if (selectCount == 0) return;
            string no = dataGridView_List.SelectedRows[0].Cells[0].Value.ToString();
            PrintFilingReceiptInformation printFilingReceiptInformation = Database.GetApplicantData(no);
            PrintFilingReceipt printFilingReceipt = new PrintFilingReceipt(new List<PrintFilingReceiptInformation>() { printFilingReceiptInformation });
            printFilingReceipt.Print();
        }
    }
}