using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Printing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using PEIS.Base;
using PEIS.Entity;
using PEIS.Event;
using PEIS.Model;
using PEIS.Model.Exam;
using PEIS.Presenter;
using PEIS.Utils;
using PEIS.View.UControl;
using static PEIS.Utils.ColorHelper;
namespace PEIS.View.Exam
{
    public partial class TotalForm : ViewBase, ITotalView
    {
        /// 
        /// 创建Presenter
        /// 
        /// 
        protected override object CreatePresenter()
        {
            return new TotalPresenter(this);
        }
        private HistoryView historyView;
        private readonly string _watermarkTeam = @"团检号或团队名称";
        private readonly string _watermarkInfo = @"体检号或体检者姓名";
        // 定义一个委托
        public delegate void SelectedPatientDelegate(long? eid);
        // 声明一个事件,供父窗体订阅
        public event SelectedPatientDelegate SelectedPatientEvent;
        #region 属性
        /// 
        /// 体检者列表
        /// 
        private List _patientList = new List();
        /// 
        /// 当前选中体检者
        /// 
        private EnrollmentPatient _patient = new EnrollmentPatient();
        /// 
        /// 科室分检
        /// 
        private List _examPart = new List();
        /// 
        /// 结论
        /// 
        private List _examConclusion = new List();
        /// 
        /// 检验报告结果
        /// 
        private List _lisReport = new List();
        /// 
        /// 是否是体检科
        /// 
        private bool _isPeidDeptUser;
        #endregion 属性
        public TotalForm()
        {
            InitializeComponent();
            //页面显示
            Shown += TotalForm_Shown;
            DgvPatient.RowClick += DgvPatientRowClick;
            //RadioButtonClick
            RbStatus1.Click += RadioButton_Click;
            RbStatus2.Click += RadioButton_Click;
            // 输入体检号回车
            //txtId.KeyDown += TxtId_KeyDown;
            OpsConclusion.TsmiRefresh.Text = "上移"; 
            OpsConclusion.TsmiRefresh.Image = Properties.Resources.shang;
            OpsConclusion.TsmiAdd.Text = "下移"; 
            OpsConclusion.TsmiAdd.Image = Properties.Resources.xia;
            //结论-排序
            OpsConclusion.TsmiRefresh.Click += (s, e) =>
             {
                 ConclusionSort(-1);
             };
            OpsConclusion.TsmiAdd.Click += (s, e) =>
            {
                ConclusionSort(1);
            };
            //结论-删除
            OpsConclusion.TsmiDelete.Click += ConclusionDelete_Click;
            //结论-保存
            OpsConclusion.TsmiSave.Click += ConclusionSave_Click;
            // 切换Tab页加载数据
            TabPart.SelectedPageChanged += TabPart_SelectedPageChanged;
            //完结
            TsmiFinish.Click += (s, e) =>
            {
                if (!_isPeidDeptUser)
                {
                    Global.MsgWarn("权限不足!");
                    return;
                }
                var dept = DAOHelp.GetDataBySQL($@"SELECT	a.DeptName FROM	Enrollment_FeeItem a
                LEFT JOIN Exam_Part b ON a.EID = b.EID  AND a.DeptCode = b.DeptCode
				LEFT JOIN Dict_FeeItem C ON a.KeyNo = C.KeyNo
                WHERE  a.EID = {_patient.ID} AND a.GiveUpTime IS NULL AND a.ItemClass <> '检验' AND b.VerifyTime IS NULL AND C.IsHide=0");
                if (dept.Count > 0)
                {
                    var result = MessageBox.Show($@"{dept.FirstOrDefault()?.DeptName} 存在未审核的检查项目,是否仍要完结?", @"完结",
                        MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (result != DialogResult.Yes) return;
                }
                Finish?.Invoke(this, new Args()
                {
                    ID = _patient.ID,
                    Code = Global.currentUser.Code,
                    Name = Global.currentUser.Name,
                    Item = true
                });
            };
            // 取消完结
            TsmiFinishCancel.Click += (s, e) =>
            {
                try
                {
                    if (!_isPeidDeptUser)
                    {
                        Global.MsgWarn("权限不足!");
                        return;
                    }
                    Finish?.Invoke(this, new Args()
                    {
                        ID = _patient.ID,
                        Code = Global.currentUser.Code,
                        Name = Global.currentUser.Name,
                        Item = false
                    });
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception);
                    throw;
                }
            };
            TsmiWeChatViewReport.Click += (s, e) =>
            {
                var status = !_patient.IsWeChatView ?? false;
                if (_patient.FinishTime == null)
                {
                    Global.MsgWarn("体检未完结!");
                    return;
                }
                WeChatViewRpt?.Invoke(this, new Args()
                {
                    ID = _patient.ID,
                    Item = status
                });
                _patient.IsWeChatView = status;
                TsmiWeChatViewReport.Text = status ? "已允许微信查看报告" : "已禁止微信查看报告";
                TsmiWeChatViewReport.ForeColor = status ? Color.Black : Color.Red;
                picWeChat.Visible = status;
            };
            TsmiAbandoned.Click += TsmiAbandoned_Click;
            //1.2.1.PACS
            DgvRptPacs.RowClick += DgvReportPacs_DoubleClick;
            //1.3.1.其他报告
            DgvRptExt.RowClick += (o, e) =>
            {
                if (DgvRptExt.GetFocusedRow() is ReportExt selected) SetPictureBoxReportExt(selected);
            };
            //颜色
            // DgvExamResult.CustomDrawCell += DgvExamResult_CustomDrawCell;
            //结论选择
            CmbSearchConclusion.DisplayMember = "ConclusionName";
            CmbSearchConclusion.ValueMember = "ConclusionName";
            CmbSearchConclusion.DataSource = Global._lstConclusion;
            CmbSearchConclusion.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            CmbSearchConclusion.CloseUp += CmbSearchConclusion_CloseUp;
            var userModel = new UserModel();
            _isPeidDeptUser = userModel.IsPeidDept();
            BtnRefresh.Click += BtnRefresh_Click;
            DgvLisReport.CustomDrawCell += DgvLisReport_CustomDrawCell;
            DgvPatient.Initialize();
            DgvPatient.CustomDrawCell += DgvPatient_CustomDrawCell;
            txtTeam.KeyDown += (s, e) =>
            {
                if (e.KeyCode == Keys.Enter) OnGetPatientList();
            };
            txtInfo.KeyDown += (s, e) =>
            {
                if (e.KeyCode == Keys.Enter) OnGetPatientList();
            };
            txtConclusionSerch.KeyDown += (s, e) =>
            {
                if (e.KeyCode == Keys.Enter) SearchAllConclusion();
            };
            txtConclusionSerch.TextChanged += (s, e) =>
            {
                SearchAllConclusion();
            };
            DgvExamConclusion.OptionsCustomization.AllowSort = true;
            //DgcAllConclusion.DataSource = Global._lstConclusion;
            // DgvAllConclusion.OptionsFind.AlwaysVisible = true;
            // DgvAllConclusion.OptionsFind.ShowClearButton = false;
            // DgvAllConclusion.OptionsFind.ShowCloseButton = false;
            DgvAllConclusion.DoubleClick += DgvAllConclusion_DoubleClick;
            DgvExamResultData.CustomDrawCell += DgvExamResultData_CustomDrawCell;
            // 启用行选择
            DgvExamConclusion.OptionsSelection.EnableAppearanceFocusedCell = false;
            DgvExamConclusion.OptionsSelection.MultiSelect = false; // 限制单选  
            // 启用编辑功能,以便显示勾选框
            DgvExamConclusion.OptionsBehavior.Editable = true;
            // 设置行头自动调整高度以显示勾选框
            DgvExamConclusion.OptionsView.RowAutoHeight = true;
            // pacs报告打印
            PrintPacs.Click += PrintPacs_Click;
        }
        private void ConclusionSort(int i)
        {
            if (DgvExamConclusion.GetFocusedRow() is ExamConclusion selected)
            {
                var current = _examConclusion.IndexOf(selected);
                if ((current == 0 && i < 0) || (current == _examConclusion.Count - 1 && i > 0))
                {
                    return;
                }
                var temp = _examConclusion[current + i];
                var tempSeq = _examConclusion[current + i].Seq;
                temp.Seq = selected.Seq;
                selected.Seq = tempSeq;
                _examConclusion[current + i] = selected;
                _examConclusion[current] = temp;
                _examConclusion = _examConclusion.OrderBy(o => o.Seq).ToList();
                // for (int j = 0; j < _examConclusion.Count; j++)
                // {
                //     _examConclusion[j].Seq = j + 1;
                // }
                Invoke(new Action(() => DgcExamConclusion.DataSource = null));
                Invoke(new Action(() => DgcExamConclusion.DataSource = _examConclusion));
                Invoke(new Action(() => DgcExamConclusion.DataSource = _examConclusion));
                Invoke(new Action(() => DgvExamConclusion.FocusedRowHandle = current+i));
                Invoke(new Action(() => DgvExamConclusion.SelectRow(current + i)));
            }
        }
        private void SearchAllConclusion()
        {
            var query = txtConclusionSerch.Text;
            var isId = long.TryParse(query, out var id);
            var list = string.IsNullOrEmpty(query)
                ? Global._lstConclusion
                : Global._lstConclusion.Where(p => p.SpellCode.Contains(query) || p.ConclusionName.Contains(query) || (isId && p.ID == id)).ToList();
            Invoke(new Action(() => DgcAllConclusion.DataSource = null));
            Invoke(new Action(() => DgcAllConclusion.DataSource = list));
        }
        private void DgvAllConclusion_DoubleClick(object sender, EventArgs e)
        {
            if (!_isPeidDeptUser)
            {
                MessageBox.Show(@"权限不足!");
                return;
            }
            if (_patient.FinishTime != null)
            {
                return;
            }
            if (DgvAllConclusion.GetFocusedRow() is Conclusion selected)
                _examConclusion.Add(new ExamConclusion()
                {
                    EID = _patient.ID,
                    Seq = _examConclusion.Count + 1,
                    Conclusion = selected.ConclusionName,
                    Suggestion = selected.Suggestion
                });
            ShowExamConclusion(_examConclusion);
        }
        /// 
        /// 体检者列表-自定义绘制单元格
        /// 
        /// 
        /// 
        private void DgvPatient_CustomDrawCell(object sender, RowCellCustomDrawEventArgs e)
        {
            if (e.Column.Caption != @"状态")
            {
                return;
            }
            var gridView = (GridView)sender;
            if (e.RowHandle < 0 || e.Column == null) return;
            // 获取当前单元格所在行的数据
            var rowData = gridView.GetRow(e.RowHandle) as EnrollmentPatient;
            switch (rowData?.Status)
            {
                case "科室分检":
                    e.Appearance.ForeColor = Color.Black;
                    e.Appearance.BackColor = Color.White;
                    break;
                case "总检":
                    e.Appearance.ForeColor = ForeMain;
                    e.Appearance.BackColor = BackMain;
                    break;
                case "打印":
                    e.Appearance.ForeColor = ForeSuccess;
                    e.Appearance.BackColor = BackSuccess;
                    break;
                case "弃检":
                    e.Appearance.ForeColor = ForeWarning;
                    e.Appearance.BackColor = BackWarning;
                    break;
                default:
                    e.Appearance.ForeColor = ForeInfo;
                    e.Appearance.BackColor = BackInfo;
                    break;
            }
        }
        private void DgvLisReport_CustomDrawCell(object sender, RowCellCustomDrawEventArgs e)
        {
            var gridView = (GridView)sender;
            if (e.RowHandle < 0 || e.Column == null) return;
            // 获取当前单元格所在行的数据
            var rowData = gridView.GetRow(e.RowHandle) as ExamResult;
            if (string.IsNullOrEmpty(rowData?.UnusualFlag)) return;
            switch (rowData.UnusualFlag)
            {
                case "↑":
                    e.Appearance.ForeColor = ColorHelper.ForeDanger;
                    e.Appearance.BackColor = ColorHelper.BackDanger;
                    break;
                case "↓":
                    e.Appearance.ForeColor = ColorHelper.ForeMain;
                    e.Appearance.BackColor = ColorHelper.BackMain;
                    break;
            }
        }
        private void TabPart_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            RefreshTabPageData(e.Page.Text);
        }
        private void CmbSearchConclusion_CloseUp(object sender, DevExpress.XtraEditors.Controls.CloseUpEventArgs e)
        {
            if (e.AcceptValue)
            {
                var editor = sender as SearchLookUpEdit;
                if (editor != null)
                {
                    // 获取选中的行数据
                    var rowData = editor.Properties.View.GetFocusedRow() as Conclusion;
                    if (rowData != null)
                    {
                        var conclusion = DgvExamConclusion.GetFocusedRow() as ExamConclusion;
                        if (rowData == null || conclusion == null) return;
                        var index = _examConclusion.IndexOf(conclusion);
                        _examConclusion[index].Conclusion = rowData.ConclusionName;
                        _examConclusion[index].Suggestion = rowData.Suggestion;
                        ShowExamConclusion(_examConclusion);
                    }
                }
            }
            // if (string.IsNullOrEmpty(e?.Value?.ToString())) return;
            // var rowData = Global._lstConclusion.FirstOrDefault(p => p.ConclusionName == e.Value.ToString());
            // var conclusion = DgvExamConclusion.GetFocusedRow() as ExamConclusion;
            // if (rowData == null || conclusion == null) return;
            // var index = _examConclusion.IndexOf(conclusion);
            // _examConclusion[index].Conclusion = rowData.ConclusionName;
            // _examConclusion[index].Suggestion = rowData.Suggestion;
            // ShowExamConclusion(_examConclusion);
        }
        private void DgvExamResult_CustomDrawCell(object sender, RowCellCustomDrawEventArgs e)
        {
            var gridView = (GridView)sender;
            if (e.RowHandle < 0 || e.Column == null) return;
            // 获取当前单元格所在行的数据
            var rowData = gridView.GetRow(e.RowHandle) as ExamResult;
            if (rowData?.VerifyTime != null) return;
            e.Appearance.ForeColor = ColorHelper.ForeWarning;
            e.Appearance.BackColor = ColorHelper.BackWarning;
        }
        /// 
        /// 刷新科室体检者列表
        /// 
        /// 
        /// 
        private void BtnRefresh_Click(object sender, EventArgs e)
        {
            OnGetPatientList();
        }
        /// 
        /// 预览报告单
        /// 
        /// 
        /// 
        private void TsmiAbandoned_Click(object sender, EventArgs e)
        {
            var eid = _patient.ID;
            if (eid > 0)
            {
                var rpt = ReportHelper.GetReport(eid);
                if (rpt == null)
                {
                    Global.Msg("err", "报告生成失败!");
                    return;
                }
                rpt.Show();
            }
        }
        #region IViewClick
        /// 
        /// 2.获取体检者列表
        /// 
        public event EventHandler> GetPatientList;
        public event EventHandler> GetPatient;
        public void ShowPatient(EnrollmentPatient item)
        {
            RefreshPatient(item);
            RefreshTabPageData(TabPart.SelectedTabPage.Text);
        }
        public void ShowPatientList(List items)
        {
            Invoke(new Action(() => _patientList = items));
            Invoke(new Action(() => DgcPatient.DataSource = null));
            Invoke(new Action(() => DgcPatient.DataSource = _patientList));
            Invoke(new Action(() => RbStatus1.Checked = false));
            Invoke(new Action(() => RbStatus2.Checked = false));
            Invoke(new Action(() => RbStatus3.Checked = false));
            Invoke(new Action(() => RbStatus4.Checked = true));
            Invoke(new Action(() => DgcExamResult.DataSource = null));
            Invoke(new Action(() => DgvPatient.BestFitColumns()));
        }
        private void OnGetPatientList()
        {
            {
                if (dateEditBeg?.Value == null || dateEditEnd?.Value == null ||
                    !DateTime.TryParse(dateEditBeg.Value.ToString(CultureInfo.InvariantCulture), out var _) ||
                    !DateTime.TryParse(dateEditEnd.Value.ToString(CultureInfo.InvariantCulture), out var _))
                    return;
                var dateType = comboDate?.SelectedItem as QueryDateType;
                if ((txtTeam.Text != _watermarkTeam || txtInfo.Text != _watermarkInfo)
                    && dateEditBeg.Value.Date == DateTime.Now.AddDays(-3).Date &&
                    dateEditEnd.Value.Date == DateTime.Now.Date)
                {
                    dateEditBeg.Value = DateTime.Now.AddDays(-15);
                }
                // 1日期类型、2开始日期、3结束日期、4体检团队、5个人信息
                GetPatientList?.Invoke(this, new Args()
                {
                    Items = new List()
                    {
                        dateType?.Code,
                        $"{Convert.ToDateTime(dateEditBeg.Value):yyyy-MM-dd}",
                        $"{Convert.ToDateTime(dateEditEnd.Value).AddDays(1):yyyy-MM-dd}",
                        txtTeam.Text == _watermarkTeam ? "" : txtTeam.Text,
                        txtInfo.Text == _watermarkInfo ? "" : txtInfo.Text,
                    }
                });
            }
        }
        /// 
        /// 5.获取科室分检结果列表
        /// 
        public event EventHandler> GetExamResultList;
        public void ShowExamResultList(List items)
        {
            Invoke(new Action(() => DgcExamResult.DataSource = null));
            Invoke(new Action(() => DgcExamResult.DataSource = items));
            Invoke(new Action(() => DgvExamResult.ExpandAllGroups()));
        }
        /// 
        /// 3. 获取科室小结
        /// 
        public event EventHandler> GetSummary;
        public void ShowSummary(List items)
        {
            Invoke(new Action(() => _examPart = items));
            Invoke(new Action(() => txtSummary.Text = null));
            Invoke(new Action(() =>
            {
                txtSummary.Text = @"-- 科室小结 --";
                _examPart.ForEach(item =>
                {
                    if (!string.IsNullOrEmpty(item.Summary))
                        txtSummary.Text += Environment.NewLine + $@"【{item.DeptName}】" + Environment.NewLine + item.Summary +
                                           Environment.NewLine;
                });
            }));
            Invoke(new Action(() => DgcSummary.DataSource = null));
            Invoke(new Action(() => DgcSummary.DataSource = _examPart));
            Invoke(new Action(() => DgcSummary.DataSource = _examPart));
            Invoke(new Action(() => DgvSummary.ExpandAllGroups()));
        }
        /// 
        /// 4. 获取结论词
        /// 
        public event EventHandler> GetExamConclusion;
        public event EventHandler> SaveExamConclusion;
        public void ShowExamConclusion(List items)
        {
            items = items.OrderBy(o => o.Seq).ToList();
            for (int j = 0; j < items.Count; j++)
            {
                items[j].Seq = j + 1;
            }
            Invoke(new Action(() => DgcExamConclusion.DataSource = null));
            Invoke(new Action(() => _examConclusion = items));
            Invoke(new Action(() => DgcExamConclusion.DataSource = _examConclusion));
            DgvExamConclusion.OptionsView.RowAutoHeight = true; // 启用自动行高调整 
            DgvExamConclusion.OptionsCustomization.AllowRowSizing = true;
            Invoke(new Action(() => DgvExamConclusion.TopRowIndex = items.Count));
            //DgvExamConclusion.BestFitColumns(); // 调整列宽以适应内容
        }
        /// 
        /// 11.获取科室分检结果列表
        /// 
        public event EventHandler> GetLisReport;
        public void ShowLisReport(List items)
        {
            Invoke(new Action(() => DgcLisReport.DataSource = null));
            Invoke(new Action(() => _lisReport = items));
            Invoke(new Action(() => DgcLisReport.DataSource = _lisReport));
        }
        /// 
        /// 修改完结状态
        /// 
        public event EventHandler> Finish;
        public void ShowFinish(int status)
        {
            Global.MsgInfo(status == 1 ? @"完结成功!" : status == -1 ? "取消完结成功!"  : "操作失败,请重试!");
            if (DgvPatient.GetFocusedRow() is EnrollmentPatient selected)
            {
                GetPatient?.Invoke(this, new Args