using RGD.Common;
using RGD.DataService;
using RGD.DBUtility;
using System;
using System.Data;
using System.Windows.Forms;

namespace RGD.WCS
{
    public partial class FrmModifyManage : Form
    {
        private string _manstatus = " F_Status<>-1 ";

        private static FrmModifyManage _formInstance;

        public static FrmModifyManage FormInstance
        {
            get
            {
                if (_formInstance == null)
                {
                    _formInstance = new FrmModifyManage();
                }
                return _formInstance;
            }
            set { _formInstance = value; }
        }

        public FrmModifyManage()
        {
            InitializeComponent();
            _formInstance = this;
        }

        private void FrmModifyManage_Load(object sender, EventArgs e)
        {
            rbmanRun_CheckedChanged(sender, e);
        }

        /// <summary>
        /// 运行任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rbmanRun_CheckedChanged(object sender, EventArgs e)
        {
            if (rbmanRun.Checked == true)
            {
                _manstatus = " F_Status>=1 ";
            }
            TSMrefresh_Click(sender, e);
        }

        /// <summary>
        /// 全部任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rbmanAll_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton rb = (RadioButton)sender;
            if (rb.Checked == true)
            {
                _manstatus = " F_Status<>-1 ";
            }
            TSMrefresh_Click(sender, e);
        }

        /// <summary>
        /// 等待任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rbmanWait_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton rb = (RadioButton)sender;
            if (rb.Checked == true)
            {
                _manstatus = " F_Status=0 ";
            }
            TSMrefresh_Click(sender, e);
        }

        private void TSMrefresh_Click(object sender, EventArgs e)
        {
            CStaticClass.RealRefresh = true;
            this.dgvManager.DataSource = DbHelperSQL.Query("select * from V_Manage_Task where " + _manstatus).Tables[0].DefaultView;
        }

        /// <summary>
        /// 开始查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            if (this.textBox1.Text.Trim().Length == 0) return;
            int index = 0;
            bool isint = int.TryParse(this.textBox1.Text.Trim(), out index);
            if (this.comboBox1.Text == "表箱条码")
            {
                //20091016
                _manstatus = " 表箱条码 like'%" + this.textBox1.Text.Trim() + "%' ";
            }

            if (this.comboBox1.Text == "调度任务索引")
            {
                if (isint == false)
                {
                    //MessageBox.Show("请输入数字！", "误操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    textBox1.Text = string.Empty;
                    return;
                }

                _manstatus = " 调度任务索引='" + this.textBox1.Text.Trim() + "' ";
            }
            TSMrefresh_Click(sender, e);
        }

        /// <summary>
        /// 显示全部
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            _manstatus = " F_Status<>-1 ";

            TSMrefresh_Click(sender, e);
        }

        private void dgvManager_DataSourceChanged(object sender, EventArgs e)
        {
            dgvManager.Columns["F_Status"].Visible = false;
        }

        private void dgvManager_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
        }

        private void dgvManager_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if ((e.RowIndex >= 0) && (e.Button == MouseButtons.Right) && (e.ColumnIndex >= 0))
            {
                dgvManager.ClearSelection();
                dgvManager.Rows[e.RowIndex].Selected = true;
                dgvManager.CurrentCell = dgvManager.Rows[e.RowIndex].Cells[e.ColumnIndex];
            }
        }

        /// <summary>
        /// 任务完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TSMmanagerOK_Click(object sender, EventArgs e)
        {
            try
            {
                char[] cc = new char[1] { '：' };
                string[] split = TSManager.Text.Split(cc);
                if ((split[1] == "") || (split[2] == ""))
                {
                    return;
                }
                char[] scc = new char[1] { '；' };
                string[] strsplit = split[1].Split(scc);
                int mti = 0;
                int fid = Convert.ToInt32(split[2]);
                if (strsplit[0] == "") return;
                switch (strsplit[0])
                {
                    case "调度任务":
                        mti = 1;
                        break;

                    case "自动任务":
                        mti = 2;
                        break;

                    case "临时任务":
                        mti = 3;
                        break;

                    case "手工任务":
                        mti = 4;
                        break;
                }
                string cap = strsplit[0];
                string hw = "";
                if (this.dgvManager.CurrentRow.Cells["终点货位"].Value.ToString() != "-")
                {
                    hw = ",终点货位:" + this.dgvManager.CurrentRow.Cells["终点货位"].Value.ToString();
                }
                //20100108
                if (MessageBox.Show("您确认表箱条码：“" + this.dgvManager.CurrentRow.Cells["表箱条码"].Value.ToString() + "”，" + cap + split[2] + "已经被搬运到终点设备“" + this.dgvManager.CurrentRow.Cells["终点"].Value.ToString() + hw + "”了吗？", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
                {
                    return;
                }
                CGetState cgs = new CGetState();
                DbHelperSQL.ExecuteSql("update T_Monitor_Task set F_STATUS=-1 where F_ManageTaskKindIndex=" + mti + " and F_ManageTaskIndex=" + fid + " and F_STATUS=0");
                DataView dv = DbHelperSQL.Query("SELECT F_ManageTaskKindIndex, F_ManageTaskIndex,F_DeviceIndex,F_MonitorIndex,F_Status,F_DeviceCommandIndex " +
                    ",F_NumParam2,F_NumParam5,F_TxtParam FROM T_Monitor_Task Where  F_ManageTaskIndex=" + fid + " and F_ManageTaskKindIndex= " +
                    mti).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    string sss = "调度任务索引:" + fid.ToString();
                    //20100108
                    CCarryConvert.WriteDarkCasket("调度任务管理", "调度任务手工报告完成", "表箱条码：" + this.dgvManager.CurrentRow.Cells["表箱条码"].Value.ToString(), sss);
                    for (int i = 0; i < dv.Count; i++)
                    {
                        if (Convert.ToInt32(dv[i]["F_DeviceIndex"]) == 1001)
                        {
                            cgs.ActionComplete(Convert.ToInt32(dv[i]["F_DeviceIndex"]), Convert.ToInt32(dv[i]["F_MonitorIndex"]), CGeneralFunction.TASKFINISH);
                            //1	辅料出库;2	空托盘回收;3残托盘回收
                            if (Convert.ToInt32(dv[i]["F_DeviceCommandIndex"]) == 1)
                            {
                                DataTable tableAGVGate = DbHelperSQL.Query("SELECT F_AGVGateDeviceIndex FROM T_BASE_AGV_GATE WHERE F_ADDRESS = " + Convert.ToInt32(dv[i]["F_NumParam5"]) + "").Tables[0];
                                if (tableAGVGate.Rows.Count > 0)
                                {
                                    DbHelperSQL.ExecuteSql("UPDATE T_BASE_DEVICE SET F_PALLETBARCODE='" + dv[i]["F_TxtParam"] + "',F_HAVEGOODS = 1 WHERE F_DEVICEINDEX = " + Convert.ToInt32(tableAGVGate.Rows[0]["F_AGVGateDeviceIndex"]) + "");
                                }
                            }
                            if ((Convert.ToInt32(dv[i]["F_DeviceCommandIndex"]) == 2) || (Convert.ToInt32(dv[i]["F_DeviceCommandIndex"]) == 3))
                            {
                                DataTable tableAGVGate = DbHelperSQL.Query("SELECT F_AGVGateDeviceIndex FROM T_BASE_AGV_GATE WHERE F_ADDRESS = " + Convert.ToInt32(dv[i]["F_NumParam2"]) + "").Tables[0];
                                if (tableAGVGate.Rows.Count > 0)
                                {
                                    DbHelperSQL.ExecuteSql("UPDATE T_BASE_DEVICE SET F_PALLETBARCODE='-',F_HAVEGOODS = 0 WHERE F_DEVICEINDEX = " + Convert.ToInt32(tableAGVGate.Rows[0]["F_AGVGateDeviceIndex"]) + "");
                                }
                            }
                        }
                        else
                        {
                            if (Convert.ToInt32(dv[i]["F_Status"]) >= 1)
                            {
                                cgs.ActionComplete(Convert.ToInt32(dv[i]["F_DeviceIndex"]), Convert.ToInt32(dv[i]["F_MonitorIndex"]), 1);
                            }
                            else
                            {
                                cgs.ActionComplete(Convert.ToInt32(dv[i]["F_DeviceIndex"]), Convert.ToInt32(dv[i]["F_MonitorIndex"]), CGeneralFunction.TASKFINISH);
                            }
                        }
                    }
                }
                else
                {
                    if (mti == 1)
                    {
                        int startdevice = Convert.ToInt32(this.dgvManager.CurrentRow.Cells["起点"].Value);
                        int enddevice = Convert.ToInt32(this.dgvManager.CurrentRow.Cells["终点"].Value);

                        if (dgvManager.CurrentRow.Cells["起点货位"].Value.ToString() != "-" || dgvManager.CurrentRow.Cells["终点货位"].Value.ToString() != "-")
                        {
                            string sResult = "";
                            string IO_FLAG;
                            string LOC_NO;
                            if (dgvManager.CurrentRow.Cells["起点货位"].Value.ToString() == "-")
                            {//入库
                                IO_FLAG = "02";
                                LOC_NO = dgvManager.CurrentRow.Cells["终点货位"].Value.ToString();
                            }
                            else
                            {//出库
                                IO_FLAG = "01";
                                LOC_NO = dgvManager.CurrentRow.Cells["起点货位"].Value.ToString();
                            }
                            RGD.MdsAPI.WMS.uploadStackIODet ss = new RGD.MdsAPI.WMS.uploadStackIODet();
                            ss.Notify(fid.ToString(), IO_FLAG, LOC_NO, out sResult);
                        }
                    }
                    //回写管理表
                    cgs.ReturnManageInfo(fid, mti, true);
                }
                this.dgvManager.DataSource = DbHelperSQL.Query("select * from V_Manage_Task where " + _manstatus).Tables[0].DefaultView;
            }
            catch (Exception ex)
            {
                //throw ex;
                if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("调度任务手工完成时：" + ex.Message) < 0)
                {
                    FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "调度任务手工完成时：" + ex.Message, true);
                }
            }
        }

        /// <summary>
        /// 分解任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TSMmanagerDisassemble_Click(object sender, EventArgs e)
        {
            try
            {
                char[] cc = new char[1] { '：' };
                string[] split = TSManager.Text.Split(cc);
                if ((split[1] == "") || (split[2] == ""))
                {
                    return;
                }
                char[] scc = new char[1] { '；' };
                string[] strsplit = split[1].Split(scc);
                int mti = 0;
                int fid = Convert.ToInt32(split[2]);
                if (strsplit[0] == "") return;
                switch (strsplit[0])
                {
                    case "调度任务":
                        mti = 1;
                        break;

                    case "自动任务":
                        mti = 2;
                        break;

                    case "临时任务":
                        mti = 3;
                        break;

                    case "手工任务":
                        mti = 4;
                        break;
                }
                if (mti == 1)
                {
                    DbHelperSQL.ExecuteSql("update T_Manage_Task set FIntoStepOK='0' where FID=" + fid + " and FIntoStepOK='-' ");
                }
            }
            catch (Exception ex)
            {
                //throw ex;
                if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("手工拆分调度任务时：" + ex.Message) < 0)
                {
                    FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "手工拆分调度任务时：" + ex.Message, true);
                }
            }
        }

        /// <summary>
        /// 任务删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            //删除调度任务900
            try
            {
                char[] cc = new char[1] { '：' };
                string[] split = TSManager.Text.Split(cc);
                if ((split[1] == "") || (split[2] == ""))
                {
                    return;
                }
                char[] scc = new char[1] { '；' };
                string[] strsplit = split[1].Split(scc);
                int mti = 0;
                int fid = Convert.ToInt32(split[2]);
                if (strsplit[0] == "") return;
                switch (strsplit[0])
                {
                    case "调度任务":
                        mti = 1;
                        break;

                    case "自动任务":
                        mti = 2;
                        break;

                    case "临时任务":
                        mti = 3;
                        break;

                    case "手工任务":
                        mti = 4;
                        break;
                }
                string hw = "";
                if (this.dgvManager.CurrentRow.Cells["起点货位"].Value.ToString() != "-")
                {
                    hw = ",起点货位:" + this.dgvManager.CurrentRow.Cells["起点货位"].Value.ToString();
                }
                string cap = strsplit[0];
                if (MessageBox.Show("您确认表箱条码：“" + this.dgvManager.CurrentRow.Cells["表箱条码"].Value.ToString() + "”，" + cap + split[2] + "已经被取消操作，而且人工搬运托盘退回到起点设备“" + this.dgvManager.CurrentRow.Cells["起点"].Value.ToString() + hw + "”了吗？", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
                {
                    return;
                }
                CGetState cgs = new CGetState();
                //20090902
                DbHelperSQL.ExecuteSql("update T_Manage_Task set FExceptionNO=" + CGeneralFunction.TASKDELETE + " where (F_ManageTaskKindIndex = " + mti + ") AND (FID = " + fid + ")");

                DbHelperSQL.ExecuteSql("update T_Monitor_Task set F_STATUS=-1 where F_ManageTaskKindIndex=" + mti + " and F_ManageTaskIndex=" + fid + " and F_STATUS=0");
                DataView dv = DbHelperSQL.Query("SELECT F_ManageTaskKindIndex, F_ManageTaskIndex,F_DeviceIndex,F_MonitorIndex,F_Status,F_DeviceCommandIndex " +
                    ",F_NumParam2,F_NumParam5,F_TxtParam FROM T_Monitor_Task Where  F_ManageTaskIndex=" + fid + " and F_ManageTaskKindIndex= " +
                    mti).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    string sss = "调度任务索引:" + fid.ToString();
                    //20100108
                    CCarryConvert.WriteDarkCasket("调度任务管理", "调度任务被手工删除！", "表箱条码：" + this.dgvManager.CurrentRow.Cells["表箱条码"].Value.ToString(), sss);
                    for (int i = 0; i < dv.Count; i++)
                    {
                        if (Convert.ToInt32(dv[i]["F_DeviceIndex"]) == 1001)
                        {
                            cgs.ActionComplete(Convert.ToInt32(dv[i]["F_DeviceIndex"]), Convert.ToInt32(dv[i]["F_MonitorIndex"]), CGeneralFunction.TASKDELETE);
                            //1	辅料出库;2	空托盘回收;3残托盘回收

                            if ((Convert.ToInt32(dv[i]["F_DeviceCommandIndex"]) == 2) || (Convert.ToInt32(dv[i]["F_DeviceCommandIndex"]) == 3))
                            {
                                DataTable tableAGVGate = DbHelperSQL.Query("SELECT F_AGVGateDeviceIndex FROM T_BASE_AGV_GATE WHERE F_ADDRESS = " + Convert.ToInt32(dv[i]["F_NumParam2"]) + "").Tables[0];
                                if (tableAGVGate.Rows.Count > 0)
                                {
                                    DbHelperSQL.ExecuteSql("UPDATE T_BASE_DEVICE SET F_PALLETBARCODE='" + dv[i]["F_TxtParam"] + "',F_HAVEGOODS = 1 WHERE F_DEVICEINDEX = " + Convert.ToInt32(tableAGVGate.Rows[0]["F_AGVGateDeviceIndex"]) + "");
                                }
                            }
                        }
                        else
                        {
                            if (Convert.ToInt32(dv[i]["F_Status"]) >= 1)
                            {
                                cgs.ActionComplete(Convert.ToInt32(dv[i]["F_DeviceIndex"]), Convert.ToInt32(dv[i]["F_MonitorIndex"]), 1);
                            }
                            else
                            {
                                cgs.ActionComplete(Convert.ToInt32(dv[i]["F_DeviceIndex"]), Convert.ToInt32(dv[i]["F_MonitorIndex"]), CGeneralFunction.TASKDELETE);
                            }
                        }
                    }
                }
                else
                {//20091107
                    if (this.dgvManager.CurrentRow.Cells["终点"].Value.ToString() == "2240")
                    {
                        DbHelperSQL.ExecuteSql("update T_Base_Device set F_CreateLock='0' where F_DeviceIndex=" + this.dgvManager.CurrentRow.Cells["终点"].Value);
                    }
                    if (mti == 1)
                    {
                    }
                    //回写管理表
                    cgs.ReturnManageInfo(fid, mti, false);
                }
                this.dgvManager.DataSource = DbHelperSQL.Query("select * from V_Manage_Task where " + _manstatus).Tables[0].DefaultView;
            }
            catch (Exception ex)
            {
                //throw ex;
                if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("调度任务手工完成时：" + ex.Message) < 0)
                {
                    FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "调度任务手工完成时：" + ex.Message, true);
                }
            }
        }
    }
}