using CasunCommon.BaseUI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Pms.Common.SystemEnum;
using Pms.Common.Utility;

namespace PMSUI
{
    public partial class CTaskExceptionHandling : CasunForm
    {
        public CTaskExceptionHandling()
        {
            InitializeComponent();
        }

        private void Init()
        {
            DGVTask.Columns.Clear();
            DGVTask.DataSource = null;
            LoadTable();
        }


        private int selectRowIndexOfordersDataGridView;         // 记录选中的行号
        private int selectColumnIndexOfordersDataGridView;      // 记录选中的列号
        private int scrollingRowIndexOfordersDataGridView;      // 记录垂直滚动条位置
        private int scrollingColumnIndexOfordersDataGridView;   // 记录水平滚动条的位置


        private void LoadTable(string OrderID = "")
        {
            if (DGVTask.CurrentCell != null && DGVTask.RowCount != 0 && DGVTask.ColumnCount != 0)
            {
                selectRowIndexOfordersDataGridView = DGVTask.CurrentCell.RowIndex;
                selectColumnIndexOfordersDataGridView = DGVTask.CurrentCell.ColumnIndex;
                scrollingRowIndexOfordersDataGridView = DGVTask.FirstDisplayedScrollingRowIndex;
                scrollingColumnIndexOfordersDataGridView = DGVTask.FirstDisplayedScrollingColumnIndex;
            }

            DataTable dt;
            //DataSet ds = CasunModelDB.CDBManager.Instance.PMS_bas_StationIDRelated.GetAllList();
            if (OrderID == "")
            {
                dt = CFormColumnManager.GetDGVDataSource(this.Name, "PMS_mid_OrderData", " order by CalledTime desc ");
            }
            else
            {
                dt = CFormColumnManager.GetDGVDataSource(this.Name, "PMS_mid_OrderData", " order by CalledTime desc ", "OrderID = '" + OrderID + "'");
            }

            //if(DBNameToShowNameDic.ContainsKey("OrderState"))
            //{
            //    foreach(DataRow dw in dt.Rows)
            //    {
            //        string str = dw[DBNameToShowNameDic["OrderState"]].ToString();

            //        //dw[DBNameToShowNameDic["OrderState"]] = ((EOrderState)dw[DBNameToShowNameDic["OrderState"]]).ToString() ;
            //    }
            //}

            DGVTask.DataSource = dt;

            int n = DGVTask.RowCount;
            int m = DGVTask.ColumnCount;

            if (n != 0 && m != 0)
            {
                if (selectRowIndexOfordersDataGridView < n && selectColumnIndexOfordersDataGridView < m &&
                    scrollingRowIndexOfordersDataGridView < n && scrollingColumnIndexOfordersDataGridView < m)
                {
                    DGVTask.CurrentCell = DGVTask.Rows[selectRowIndexOfordersDataGridView].Cells[selectColumnIndexOfordersDataGridView];
                    DGVTask.FirstDisplayedScrollingRowIndex = scrollingRowIndexOfordersDataGridView;
                    DGVTask.FirstDisplayedScrollingColumnIndex = scrollingColumnIndexOfordersDataGridView;
                }
            }
        }

        private void CTaskExceptionHandling_Load(object sender, EventArgs e)
        {
            if (!InitDBNameToShowNameDic())
            {
                this.Close();
                return;
            }
            CasunUILib.ButtonHelps(btHelps);

            gp_Opt.Location = new Point(btHelps.Location.X, gp_Opt.Location.Y);
            gp_Read.Location = new Point(btHelps.Location.X, gp_Read.Location.Y);

            CasunUILib.GroupBoxReadModel(gp_Read, PermissionLevel);
            CasunUILib.GroupBoxReadWriteModel(gp_Opt, PermissionLevel);

            Init();
            CasunUILib.splitContainerModel(splitContainer1);
            CasunUILib.DgvModel(DGVTask);
        }

        /// <summary>
        /// 用于事件重复使用
        /// </summary>
        private Dictionary<string, string> DBNameToShowNameDic = new Dictionary<string, string>();


        private bool InitDBNameToShowNameDic()
        {
            if (!CFormColumnManager.GetDBNameToShowNameDic(this.Name, out DBNameToShowNameDic))
            {
                MessageBox.Show(CLanguageManager.LanguageChange("加载界面配置失败，请重启尝试恢复。"));
                return false;
            }
            return true;
        }

        private void btQuery_Click(object sender, EventArgs e)
        {
            LoadTable(tbOrderID.Text.Trim());
        }

        private void btRefresh_Click(object sender, EventArgs e)
        {
            LoadTable();
        }

        private void btforceDelete_Click(object sender, EventArgs e)
        {

            if (DGVTask.CurrentRow == null)
            {
                return;
            }
            int DGVCurrentRow = DGVTask.CurrentRow.Index;

            if (DGVCurrentRow < 0 || (DBNameToShowNameDic.ContainsKey("OrderID") && DGVTask.Rows[DGVCurrentRow].Cells[DBNameToShowNameDic["OrderID"]].Value == null))
            {
                MessageBox.Show(CLanguageManager.LanguageChange("请选择需要处理的信息") + "！");
                return;
            }

            string strOrderID = DGVTask.Rows[DGVCurrentRow].Cells[DBNameToShowNameDic["OrderID"]].Value.ToString();
            //////没有taskstatus
            if (DGVTask.Rows[DGVCurrentRow].Cells[DBNameToShowNameDic["OrderState"]].Value.ToString() != ((int)EOrderState.Exception).ToString())
            {
                string strMesg = string.Format("{0}{1},{2}！"
                       , CLanguageManager.LanguageChange("强制删除")
                       , CLanguageManager.LanguageChange("只处理异常状态任务")
                       , CLanguageManager.LanguageChange("请谨慎操作")
                       );
                MessageBox.Show(strMesg);
                return;
            }
            string strMsg = CLanguageManager.LanguageChange("强制删除") + "：OrderID=" + strOrderID
                + CLanguageManager.LanguageChange("的任务信息") + "！";
            if (MessageBox.Show(strMsg, CLanguageManager.LanguageChange("强制删除"), MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
            {
                PmsCoreDB.DBHost.Instance.TransformOrderDataToHis(strOrderID);

                string strOptLog = string.Format("【{0}】:OrderID={1}"
                    , CLanguageManager.LanguageChange("强制删除")
                    , strOrderID);
                COperateLog.Instance.InsertOperaterLogAsync(UserID, strOptLog, DateTime.Now);

                DGVTask.Rows.RemoveAt(DGVCurrentRow);
            }
        }

        private void btHelps_Click(object sender, EventArgs e)
        {
            MessageBox.Show(PMSUI.Config.CConfigManager.gs_FormHelpConfig.GetFormHelp(this.Name));

        }

        private void btForceComplete_Click(object sender, EventArgs e)
        {

            if (DGVTask.CurrentRow == null)
            {
                return;
            }
            int DGVCurrentRow = DGVTask.CurrentRow.Index;

            if (DGVCurrentRow < 0 || (DBNameToShowNameDic.ContainsKey("OrderID") && DGVTask.Rows[DGVCurrentRow].Cells[DBNameToShowNameDic["OrderID"]].Value == null))
            {
                MessageBox.Show(CLanguageManager.LanguageChange($"{"请选择需要处理的信息"}！"));
                return;
            }
            string strOrderID = DGVTask.Rows[DGVCurrentRow].Cells[DBNameToShowNameDic["OrderID"]].Value.ToString();
            //////没有taskstatus
            if (DGVTask.Rows[DGVCurrentRow].Cells[DBNameToShowNameDic["OrderState"]].Value.ToString() != ((int)EOrderState.Append).ToString())
            {
                string strMesg = string.Format($"{CLanguageManager.LanguageChange("强制完成")}{CLanguageManager.LanguageChange("只处理未派车任务")},{CLanguageManager.LanguageChange("请谨慎操作")}！");
                MessageBox.Show(strMesg);
                return;
            }
            string strMsg = CLanguageManager.LanguageChange($"强制完成{strOrderID}{CLanguageManager.LanguageChange("的任务信息")}!");
            if (MessageBox.Show(strMsg, CLanguageManager.LanguageChange("强制完成"), MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
            {
                PmsCoreDB.DBHost.Instance.TransformOrderDataToHis(strOrderID);

                string strOptLog = string.Format($"【{CLanguageManager.LanguageChange("强制完成")}】:OrderID={strOrderID}");
                COperateLog.Instance.InsertOperaterLogAsync(UserID, strOptLog, DateTime.Now);

                DGVTask.Rows.RemoveAt(DGVCurrentRow);
            }
        }
    }
}
