using RGD.DataService;
using RGD.DBUtility;
using RGD.ZhiQianAPI.ZhiQianModel;
using RGD.ZhiQianAPI;
using System;
using System.Data;
using System.Windows.Forms;

namespace RGD.WCS
{
    public partial class FrmAutoCommand : Form
    {
        private Model.MDevice devinfo;
        private CCommonFunction ccf = new CCommonFunction();
        private int AutoManageIdx = 0;

        #region ====变量定义

        private 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()
        {
            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 = DbHelperSQL.Query("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;
            }

            buttonStart.Enabled = true;
            buttonStop.Enabled = false;
        }

        private void FrmAutoCommand_Load(object sender, EventArgs e)
        {
            if (cellPanel == null)
            {
                cellPanel = new UCellPanel(this, tbstartsite, null, tbFPALLETBARCODE, string.Empty);
                cellPanel.TaskType = "100";
                cellPanel.GoodsName = "";
                cellPanel.Dock = DockStyle.Fill;
                cellPanel.AllowWareHouseChanged = false;
                plCell.Controls.Add(cellPanel);
            }
            cellPanel.Visible = true;
        }

        private void FrmAutoCommand_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (_formInstance != null)
            {
                _formInstance = null;
            }
        }

        /// <summary>
        /// 下达自动任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        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;
            int startdevicekind = BaseDeviceService.GetDeviceKindIdx(Convert.ToInt32(_startposition));//20110411
            if ((this.tbstartsite.Enabled == true) && (startdevicekind == 10))
            {
                _startsite = tbstartsite.Text;
                flaneway = Convert.ToInt32(_startposition);
                if (DbHelperSQL.Exists("SELECT FID FROM ST_CELL where FCELLSTATUS<> '-1' and FLaneWay=" + flaneway + " and FCELLCODE='" + _startsite + "'") == false)
                {
                    MessageBox.Show("起始位置和起始货位编码在数据库中没有记录！", "误操作提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }
            if ((this.tbendsite.Enabled == true) && (BaseDeviceService.GetDeviceKindIdx(Convert.ToInt32(_endposition)) == 10))
            {
                _endsite = tbendsite.Text;
                flaneway = Convert.ToInt32(_endposition);
                if (DbHelperSQL.Exists("SELECT FID FROM ST_CELL where FCELLSTATUS<> '-1' and FLaneWay=" + flaneway + " and FCELLCODE='" + _endsite + "'") == false)
                {
                    MessageBox.Show("终点位置和终点货位编码在数据库中没有记录！", "误操作提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            #region AGV通道

            if ((this.tbstartsite.Enabled == true) && (BaseDeviceService.GetDeviceKindIdx(Convert.ToInt32(_startposition)) == 11))
            {
                _startsite = tbstartsite.SelectedValue.ToString();
                if (DbHelperSQL.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) && (BaseDeviceService.GetDeviceKindIdx(Convert.ToInt32(_endposition)) == 11))
            {
                _endsite = tbendsite.SelectedValue.ToString();
                if (DbHelperSQL.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 AGV通道

            //dbo.TransBegin();
            try
            {
                //20100304
                Sql = "SELECT F_RouteID FROM T_Base_Route WHERE (F_StartDevice = " + _startposition + ") AND (F_EndDevice = " + _endposition + ")";
                ds = DbHelperSQL.Query(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 = BaseDeviceService.GetDeviceInfo(FSTARTDEVICE);
                if (devinfo != null)
                {
                    if ((FSTARTDEVICE == 3801) || (FSTARTDEVICE == 2801))
                    {
                        UseAwayFork = DbHelperSQL.GetSingle("SELECT F_UseAwayFork FROM T_Base_AGV_Gate WHERE ( F_AGVGateDeviceIndex= " + FSTARTCELL + ")").ToString();
                    }
                    else
                    {
                        if (devinfo.DoubleFork == "1")
                        {
                            UseAwayFork = "0";
                        }
                        else if (devinfo.DoubleFork == "2")
                        {
                            UseAwayFork = "1";
                        }
                        //else if (devinfo.DeviceIndex==1101)
                        //{
                        //    UseAwayFork = "1";
                        //}
                    }
                }
                if (UseAwayFork == "-")
                {
                    devinfo = BaseDeviceService.GetDeviceInfo(FENDDEVICE);
                    if (devinfo != null)
                    {
                        if ((FENDDEVICE == 3801) || (FENDDEVICE == 2801))
                        {
                            UseAwayFork = DbHelperSQL.GetSingle("SELECT F_UseAwayFork FROM T_Base_AGV_Gate WHERE ( F_AGVGateDeviceIndex= " + FENDCELL + ")").ToString();
                        }
                        else
                        {
                            if (devinfo.DoubleFork == "1")
                            {
                                UseAwayFork = "0";
                            }
                            else if (devinfo.DoubleFork == "2")
                            {
                                UseAwayFork = "1";
                            }
                            //else if (devinfo.DeviceIndex == 1101)
                            //{
                            //    UseAwayFork = "1";
                            //}
                        }
                    }
                }
                stackno = Convert.ToInt32(DbHelperSQL.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(监控下的调度任务)：
                int startcol = 0, startlayer = 0;//20110411
                if (startdevicekind == 10)//出库或是巷道内移库任务
                {
                    startcol = Convert.ToInt32(_startsite.Substring(3, 2));
                    startlayer = Convert.ToInt32(_startsite.Substring(6, 2));
                }
                Sql = "insert into T_Manage_Task(FID,FPALLETBARCODE,FCONTROLTASKTYPE,F_ManageTaskKindIndex,FSTARTWAREHOUSE,FSTARTDEVICE,FSTARTCELL," +
                "FENDWAREHOUSE,FENDDEVICE,FENDCELL,FLANEWAY,FSTACK,FUseAwayFork,FBEGTIME,BOX_QUANTITY,UNPACK_QUANTITY,FStartCol,FStartLayer) " +
                "values(" + AutoManageIdx + ",'" + tbFPALLETBARCODE.Text + "','" + _tasktype + "',2,'" + new WarehouseService().GetWarehouseIndex() + "','" + _startposition + "','" + _startsite + "','" + new WarehouseService().GetWarehouseIndex() + "','"
                + _endposition + "','" + _endsite + "'," + flaneway + "," + stackno + ",'" + UseAwayFork + "','" + dtime + "',1,1," + startcol + "," + startlayer + ")";//20101028
                DbHelperSQL.ExecuteSql(Sql);
            }
            catch (Exception ex)
            {
                //dbo.TransRollback();
                throw ex;
            }
        }

        /// <summary>
        /// 任务类型
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbtasktype_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.tbFPALLETBARCODE.Enabled = true;
            this.tbFPALLETBARCODE.Text = "";
            CCommonFunction ccf = new CCommonFunction();
            int IOtype = Convert.ToInt32(new CommonService().GetIOType(this.cbtasktype.SelectedValue.ToString()));
            DataView dvs = DbHelperSQL.Query("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 = DbHelperSQL.Query("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 = DbHelperSQL.Query("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 UCellPanel(this, tbstartsite, null, tbFPALLETBARCODE, 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 = DbHelperSQL.Query("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 = DbHelperSQL.Query("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 = DbHelperSQL.Query("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 UCellPanel(this, tbendsite, null, tbFPALLETBARCODE, 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 = DbHelperSQL.Query("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 = DbHelperSQL.Query("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;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            CompleteOrder completeOrder = new CompleteOrder();
            if(textBox1.Text!=null && textBox1.Text != "")
            {
                completeOrder.taskid = int.Parse(textBox1.Text);
            }
            else
            {
                completeOrder.taskid = FrmMain.taskId;
            }
            
            AppendCompleteCancelResponse completeResponse = SendDataToAgv.SendStopAppendTaskToAgv(completeOrder);
        }
    }
}