using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DBFactory;
using Microsoft.VisualBasic;
namespace ControlSystem
{
    /// <summary>
    /// Creator:Richard.liu
    /// 模仿管理下达自动任务
    /// </summary>
    public partial class FrmAutoCommand : Form
    {
        Model.MDevice devinfo;
        DBOperator dbo = CStaticClass.dbo;
        CCommonFunction ccf = new CCommonFunction();
        int AutoManageIdx = 0;
        #region ====变量定义

        CommonClassLib.UCellPanel cellPanel = null;

        #endregion
        private static FrmAutoCommand _formInstance;

        public static FrmAutoCommand FormInstance
        {
            get 
            {
                if (_formInstance == null)
                {
                    _formInstance = new FrmAutoCommand();
                }
                return _formInstance;
            }
            set { _formInstance = value; }
        }
        public FrmAutoCommand()
        {
            dbo.Open();
            InitializeComponent();
            _formInstance = this;
            ////特殊命令:堆垛机取坐标001,送坐标002;条码比对003;称重回传004;
            ////搬运木块码盘005(一个主搬运木块任务,拆分成多个单一搬运任务)
            //this.cbKind.Items.Add("");
            //this.cbKind.Items.Add("条码比对");
            //this.cbKind.Items.Add("称重回传");
            ////this.cbKind.Items.Add("机器人码盘");
            //this.cbKind.Text="条码比对";
            ////cbtasktype
            DataSet ds = dbo.ExceSQL("select * from T_ITEMTASKTYPE where FCODE !='-'");
            if (ds.Tables[0].DefaultView.Count > 0)
            {
                cbtasktype.ValueMember = "FCODE";
                cbtasktype.DisplayMember = "FNAME";
                cbtasktype.DataSource = ds.Tables[0].DefaultView;

            }
            
        }
        
        private void button1_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("您确认要增加自动任务吗?", "操作提示:", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) !=DialogResult.OK)
            {
                return;
            }
            if (tbFPALLETBARCODE.Text.Trim().Length < 10)
            {
                MessageBox.Show("托盘条码不够十位字符!", "误操作提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                
                return;
            }
           
            if ((this.cbtasktype.Text.Trim().Length == 0) || (this.cbstartposition.Text.Trim().Length == 0) || (this.cbendposition.Text.Trim().Length == 0))
            {
                MessageBox.Show("搬运任务类型、起点位置、终点位置都不允许保持空值!", "误操作提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if ((tbstartsite.Enabled == true) && (tbstartsite.Text.Trim().Length == 0))
            {
                MessageBox.Show("起点位置是巷道,所以必须指定货架位置!", "误操作提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if ((tbendsite.Enabled == true) && (tbendsite.Text.Trim().Length == 0))
            {
                MessageBox.Show("终点位置是巷道,所以必须指定货架位置!", "误操作提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if ((cbKind.Text.Trim().Length > 0) &&(txtparm.Text.Trim().Length==0))
            {
                MessageBox.Show("特殊命令如果不是空值,必须指定特殊参数!", "误操作提示", MessageBoxButtons.OK,MessageBoxIcon.Warning );
                return;
            }

            string Sql, _tasktype, _startposition, _startsite = "-", _endposition, _endsite = "-";
            
            DataSet ds;
            _tasktype = cbtasktype.SelectedValue.ToString();
            _startposition = cbstartposition.SelectedValue.ToString();
            _endposition = cbendposition.SelectedValue.ToString();
            int flaneway = 0;
            int stackno = 0;
            
            if ((this.tbstartsite.Enabled == true)&&(ccf.GetDeviceKindIdx(Convert.ToInt32( _startposition))==10))
            {
                _startsite = tbstartsite.Text;
                flaneway = Convert.ToInt32(_startposition);
                if (dbo.Exists("SELECT FID FROM ST_CELL where FLaneWay="+flaneway +" and FCELLCODE='"+_startsite+"'") == false)
                {
                    MessageBox.Show("起始位置和起始货位编码在数据库中没有记录!", "误操作提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

            }
            if ((this.tbendsite.Enabled == true) && (ccf.GetDeviceKindIdx(Convert.ToInt32( _endposition)) == 10))
            {
                _endsite = tbendsite.Text;
                flaneway = Convert.ToInt32(_endposition);
                if (dbo.Exists("SELECT FID FROM ST_CELL where FLaneWay=" + flaneway + " and FCELLCODE='" + _endsite + "'") == false)
                {
                    MessageBox.Show("终点位置和终点货位编码在数据库中没有记录!", "误操作提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }
            #region AGV通道
            
            if ((this.tbstartsite.Enabled == true) && (ccf.GetDeviceKindIdx(Convert.ToInt32( _startposition)) == 11))
            {
                _startsite = tbstartsite.SelectedValue.ToString();
                if (dbo.Exists("SELECT F_AGVGateDeviceIndex FROM T_Base_AGV_Gate WHERE (F_ChannelsIndex = " + _startposition + ") AND (F_AGVGateDeviceIndex = "+_startsite+")") == false)
                {
                    MessageBox.Show("AGV站点设备在数据库中没有记录!", "误操作提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

            }
            if ((this.tbendsite.Enabled == true) && (ccf.GetDeviceKindIdx(Convert.ToInt32(  _endposition)) == 11))
            {
                _endsite = tbendsite.SelectedValue.ToString();
                if (dbo.Exists("SELECT F_AGVGateDeviceIndex FROM T_Base_AGV_Gate WHERE (F_ChannelsIndex = " + _endposition + ") AND (F_AGVGateDeviceIndex = " + _endsite + ")") == false)
                {
                    MessageBox.Show("AGV站点设备在数据库中没有记录!", "误操作提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            #endregion
            //dbo.TransBegin();
            try
            {
                //20100304
                Sql = "SELECT F_RouteID FROM T_Base_Route WHERE (F_StartDevice = " + _startposition + ") AND (F_EndDevice = " + _endposition + ")";
                ds = dbo.ExceSQL(Sql).Tables[0].DataSet;
                if (ds.Tables[0].DefaultView.Count <= 0)
                {
                    MessageBox.Show("起始位置和结束位置不在有效路径的范围内!", "误操作提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                //20100625本地下达的自动不写堆垛机编号任务

                //string sss = "SELECT F_StackIndex, F_LaneNo FROM T_Base_StackInfo " +
                //    " where (F_LaneNo='" + flaneway + "') OR (F_LaneNo like '%" + ";" + flaneway + "') OR (F_LaneNo='" + flaneway + ";" + "%') ";
                //DataView dv = dbo.ExceSQL(sss).Tables[0].DefaultView;
                //if (dv.Count > 0)
                //{
                //    stackno = Convert.ToInt32(dv[0]["F_StackIndex"]);
                //}
                string FSTARTCELL = _startsite,FENDCELL = _endsite,UseAwayFork="-";
                int FSTARTDEVICE =Convert.ToInt32( _startposition); int FENDDEVICE = Convert.ToInt32(_endposition );
                devinfo = Model.CGetInfo.GetDeviceInfo(FSTARTDEVICE);
                if (devinfo != null)
                {//20110412
                    int uc=0;
                    if (int.TryParse(FSTARTCELL, out uc) == true)
                    {
                        UseAwayFork = dbo.GetSingle("SELECT F_UseAwayFork FROM T_Base_AGV_Gate WHERE ( F_AGVGateDeviceIndex= " + uc + ")").ToString();

                    }
                    if ((UseAwayFork == "-")||(UseAwayFork == null))
                    {
                        if (devinfo.DoubleFork == "1")
                        {
                            UseAwayFork = "0";
                        }
                        else if (devinfo.DoubleFork == "2")
                        {
                            UseAwayFork = "1";
                        }
                        //else if (devinfo.DeviceIndex==1101)
                        //{
                        //    UseAwayFork = "1";
                        //}
                    }
                    
                }
                if ((UseAwayFork == "-") || (UseAwayFork == null))
                {//20110412
                    devinfo = Model.CGetInfo.GetDeviceInfo(FENDDEVICE);
                    if (devinfo != null)
                    {
                        int uc=0;
                        if (int.TryParse(FENDCELL, out uc) == true)
                        {
                            UseAwayFork = dbo.GetSingle("SELECT F_UseAwayFork FROM T_Base_AGV_Gate WHERE ( F_AGVGateDeviceIndex= " + uc + ")").ToString();
                        }

                        if ((UseAwayFork == "-") || (UseAwayFork == null))
                        {
                            if (devinfo.DoubleFork == "1")
                            {
                                UseAwayFork = "0";
                            }
                            else if (devinfo.DoubleFork == "2")
                            {
                                UseAwayFork = "1";
                            }
                            //else if (devinfo.DeviceIndex == 1101)
                            //{
                            //    UseAwayFork = "1";
                            //}
                        }

                    }
                }
                //stackno =Convert.ToInt32( dbo.GetSingle("SELECT F_StackIndex FROM T_Base_LaneInfo WHERE (F_LaneDeviceIndex = "+flaneway+")"));//20101028
                string dtime = DateTime.Now.ToString("u");//20101028
                dtime = dtime.Substring(0, dtime.Length - 1);//20101028
                AutoManageIdx = ccf.GetTempManageIdx();
                //插入临时调度任务T_Manage_Task(监控下的调度任务):
                Sql = "insert into T_Manage_Task(FID,FPALLETBARCODE,FCONTROLTASKTYPE,F_ManageTaskKindIndex,FSTARTWAREHOUSE,FSTARTDEVICE,FSTARTCELL," +
                "FENDWAREHOUSE,FENDDEVICE,FENDCELL,FLANEWAY,FSTACK,FUseAwayFork,FBEGTIME) " +
                "values(" + AutoManageIdx + ",'" + tbFPALLETBARCODE.Text + "','" + _tasktype + "',2,'" + ccf.GetWarehouseIndex() + "','" + _startposition + "','" + _startsite + "','" + ccf.GetWarehouseIndex() + "','"
                + _endposition + "','" + _endsite + "'," + flaneway + "," + stackno + ",'" + UseAwayFork + "','" + dtime + "')";//20101028
                ds = dbo.ExceSQL(Sql);
                FrmControlMonitor.FormInstance.ManagerRefresh();//20110222
            }
            catch (Exception ex)
            {
                //dbo.TransRollback();
                throw ex;
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            string Sql, _kind, _txtparm;
            DataSet ds;
            //dbo.TransBegin();
            try
            {
                
                //插入IO_CONTROLDETAIL
                //特殊命令:堆垛机取坐标001,送坐标002;条码比对003;称重回传004;
                switch (this.cbKind.Text.Trim())
                {
                    case "条码比对":
                        _kind = "003";
                        break;
                    case "称重回传":
                        _kind = "004";
                        break;
                    //case "机器人码盘":
                    //    _kind = "005";
                    //    break;
                    default:
                        _kind = "003";
                        break;
                }
                _txtparm = this.txtparm.Text.Trim();
                if (_kind == "005")
                {

                }
                else
                {
                    int fid=GetIOControlDetailFid(1, AutoManageIdx);
                    Sql = "insert into IO_CONTROLDETAIL(FID,FCONTROLID,F_ManageTaskKindIndex,FKIND,FINDEX,FVALUE) " +
                    "values("+fid+"," + AutoManageIdx + ",1,'" + _kind + "',0,'" + _txtparm + "')";
                    ds = dbo.ExceSQL(Sql);
                }
                //dbo.TransCommit();
            }
            catch (Exception ex)
            {
                //dbo.TransRollback();
                throw ex;
            }
        }
        private void FrmAutoCommand_Load(object sender, EventArgs e)
        {
            
               
            if (cellPanel == null)
            {
                cellPanel = new CommonClassLib.UCellPanel(this, tbstartsite, null, string.Empty);
                cellPanel.TaskType = "100";
                cellPanel.GoodsName = "";
                cellPanel.Dock = DockStyle.Fill;
                cellPanel.AllowWareHouseChanged = false;
                plCell.Controls.Add(cellPanel);

            }
            cellPanel.Visible = true; 
        }
        
        private void cbtasktype_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.tbFPALLETBARCODE.Enabled = true;
            this.tbFPALLETBARCODE.Text = "";
            CCommonFunction ccf=new CCommonFunction();
            int IOtype =Convert.ToInt32( ccf.GetIOType(this.cbtasktype.SelectedValue.ToString()));
            DataView dvs = dbo.ExceSQL("SELECT DISTINCT F_StartDevice,F_DeviceName FROM T_Base_Route,T_Base_Device where F_StartDevice = F_DeviceIndex and T_Base_Route.F_RouteKind = " + IOtype).Tables[0].DefaultView ;
            //cbstartposition
            cbstartposition.ValueMember = "F_StartDevice";
            cbstartposition.DisplayMember = "F_DeviceName";
            cbstartposition.DataSource = dvs;
            
            DataView dvs1 = dbo.ExceSQL("SELECT DISTINCT F_EndDevice,F_DeviceName FROM T_Base_Route,T_Base_Device where F_EndDevice = F_DeviceIndex and T_Base_Route.F_RouteKind = " + IOtype).Tables[0].DefaultView;
            //cbendposition
            cbendposition.ValueMember = "F_EndDevice";
            cbendposition.DisplayMember = "F_DeviceName";
            cbendposition.DataSource = dvs1;
            
                
            
        }

        private void cbstartposition_SelectedIndexChanged(object sender, EventArgs e)
        {
            tbstartsite.DataSource = null;
            tbstartsite.Text = "";
            //如果是巷道设备tbstartsite.enable=true
            DataSet ds = dbo.ExceSQL("select F_DeviceIndex,F_DeviceKindIndex from T_Base_Device where F_DeviceKindIndex=10 and  F_DeviceIndex=" +Convert.ToInt32( cbstartposition.SelectedValue )+ "");
            if (ds.Tables[0].DefaultView.Count > 0)
            {
                
                tbstartsite.Enabled = true;

                plCell.Enabled = true;

                if (cellPanel == null)
                {
                    cellPanel = new CommonClassLib.UCellPanel(this, tbstartsite, null, string.Empty);
                    cellPanel.TaskType = "100";
                    cellPanel.GoodsName = "";
                    cellPanel.Dock = DockStyle.Fill;
                    cellPanel.AllowWareHouseChanged = false;
                    plCell.Controls.Add(cellPanel);

                }
                cellPanel.ControlCellCode = tbstartsite;
                cellPanel.Laneway = this.cbstartposition.SelectedValue.ToString();
                cellPanel.Visible = plCell.Visible;
            }
            else
            {
                plCell.Enabled = false;
                tbstartsite.Enabled = false;
            }
            DataView dv = dbo.ExceSQL("select F_DeviceIndex,F_DeviceKindIndex from T_Base_Device where F_DeviceKindIndex=11 and  F_DeviceIndex=" + Convert.ToInt32(cbstartposition.SelectedValue) + "").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                tbstartsite.Enabled = true;
                dv = dbo.ExceSQL("SELECT T_Base_Device.F_DeviceName, T_Base_Device.F_DeviceIndex FROM T_Base_AGV_Gate,T_Base_Device WHERE T_Base_AGV_Gate.F_AGVGateDeviceIndex = T_Base_Device.F_DeviceIndex and F_ChannelsIndex=" + cbstartposition.SelectedValue + "").Tables[0].DefaultView;
                tbstartsite.DisplayMember = "F_DeviceName";
                tbstartsite.ValueMember = "F_DeviceIndex";
                tbstartsite.DataSource = dv;
            }
        }

        private void cbendposition_SelectedIndexChanged(object sender, EventArgs e)
        {
            tbendsite.DataSource = null;
            tbendsite.Text = "";
            //如果是巷道设备tbstartsite.enable=true
            DataSet ds = dbo.ExceSQL("select F_DeviceIndex,F_DeviceKindIndex from T_Base_Device where F_DeviceKindIndex=10 and  F_DeviceIndex= " +Convert.ToInt32( cbendposition.SelectedValue) + "");
            if (ds.Tables[0].DefaultView.Count > 0)
            {
                tbendsite.Enabled = true;

                plCell.Enabled = true;
                
                if (cellPanel == null)
                {
                    cellPanel = new CommonClassLib.UCellPanel(this, tbendsite, null, string.Empty);
                    cellPanel.TaskType = "100";
                    cellPanel.GoodsName = "";
                    cellPanel.Dock = DockStyle.Fill;
                    cellPanel.AllowWareHouseChanged = false;
                    plCell.Controls.Add(cellPanel);

                }
                cellPanel.ControlCellCode = tbendsite;
                cellPanel.Laneway = this.cbendposition.SelectedValue.ToString();
                cellPanel.Visible = plCell.Visible;
            }
            else
            {
                plCell.Enabled = false;
                tbendsite.Enabled = false; 
            }
            DataView dv = dbo.ExceSQL("select F_DeviceIndex,F_DeviceKindIndex from T_Base_Device where F_DeviceKindIndex=11 and  F_DeviceIndex=" + Convert.ToInt32(cbendposition.SelectedValue) + "").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                tbendsite.Enabled = true;
                dv = dbo.ExceSQL("SELECT T_Base_Device.F_DeviceName, T_Base_Device.F_DeviceIndex FROM T_Base_AGV_Gate,T_Base_Device WHERE T_Base_AGV_Gate.F_AGVGateDeviceIndex = T_Base_Device.F_DeviceIndex and F_ChannelsIndex=" + cbendposition.SelectedValue + "").Tables[0].DefaultView;
                tbendsite.DisplayMember = "F_DeviceName";
                tbendsite.ValueMember = "F_DeviceIndex";
                tbendsite.DataSource = dv;
            }
        }

        
        int GetIOControlDetailFid(int ManageTaskKindIndex,int FCONTROLID)
        {

            DataSet ds = dbo.ExceSQL("SELECT MAX(FID) AS MaxFID FROM IO_CONTROLDETAIL GROUP BY F_ManageTaskKindIndex, FCONTROLID HAVING (F_ManageTaskKindIndex = " + ManageTaskKindIndex + ") AND (FCONTROLID = " + FCONTROLID + ")");
            if (ds.Tables[0].DefaultView.Count > 0)
            {
                return (Convert.ToInt32(ds.Tables[0].DefaultView[0]["MaxFID"]) + 1);
            }
            else
            {
                return 1;
            }

        }
        

        
    }
}