using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DBFactory;
namespace wcfControlMonitorClient
{
    public partial class FrmLaneTest : Form
    {
        private static FrmLaneTest _formInstance;

        public static FrmLaneTest FormInstance
        {
            get
            {
                if (_formInstance == null)
                {
                    _formInstance = new FrmLaneTest();
                }
                return _formInstance;
            }
            set { _formInstance = value; }
        }
        WcfControlMonitorLib.CCommonFunction ccf = new WcfControlMonitorLib.CCommonFunction();
        DBOperator dbo = CStaticClass.dbo;
        public FrmLaneTest()
        {
            InitializeComponent();
            _formInstance = this;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                int Laneindex = Convert.ToInt32(tLane1.Text);//巷道--1
                string device = cbEndDevice1.Text;//终点货位---2
                string CellCode = tCell1.Text;//出库终点设备---3


                if (BuildOutTask(Laneindex, device, CellCode))//生成出库任务---4
                {
                    //btteststart1.Enabled = false;//----5
                    //btteststop1.Enabled = true;//-------6

                    //设置开始测试

                }
                StopTest(Laneindex, false);
                StopOut(Laneindex, false);
                StopIn(Laneindex, false);
                WcfControlMonitorLib.CStaticClass.TestKind = 2;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "异常提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                int Laneindex = Convert.ToInt32(tLane2.Text);//巷道--1
                string device = cbEndDevice2.Text;//终点货位---2
                string CellCode = tCell2.Text;//出库终点设备---3


                if (BuildOutTask(Laneindex, device, CellCode))//生成出库任务---4
                {
                    //btteststart2.Enabled = false;//----5
                    //btteststop2.Enabled = true;//-------6

                }
                //设置开始测试
                StopTest(Laneindex, false);
                StopOut(Laneindex, false);
                StopIn(Laneindex, false);
                WcfControlMonitorLib.CStaticClass.TestKind = 2;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "异常提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }


        string GetNextCell(int lane, string cell)
        {
            char[] cc = new char[1] { '-'};
            string[] sp = cell.Split(cc);
            if (sp.Length > 2)
            {
                DataView dv= dbo.ExceSQL("SELECT * FROM ST_CELL WHERE (FLaneWay=" + lane + " and F_Z=" +
                                sp[0] + " and F_X=" + sp[1] + " and F_Y=" + sp[2] + ")").Tables[0].DefaultView ;
                if (dv.Count > 0)
                {
                    DataView dv0 = dbo.ExceSQL("SELECT * FROM ST_CELL WHERE (FLaneWay=" + lane + ") and (FID>"+dv[0]["FID"]+") order by fid asc").Tables[0].DefaultView ;
                    if (dv0.Count > 0)
                    {
                        return dv0[0]["FCELLCODE"].ToString();
                    }
                    else
                    {
                        return "1-1-1";
                    }
                }
                else
                {
                    return "1-1-1";
                }
            }
            else
            {
                return "1-1-1";
            }
        }
        string GetStackNo(int lane)
        {
            DataView dv = dbo.ExceSQL("SELECT F_StackIndex, F_LaneNo FROM T_Base_StackInfo WHERE F_LaneNo like '%"+lane.ToString()+"%'").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                return dv[0]["F_StackIndex"].ToString();
            }
            else
            {
                return "2801";
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            try
            {
                int Laneindex = Convert.ToInt32(tLane1.Text);//巷道--1

                //btteststart1.Enabled = true;//----2
                //btteststop1.Enabled = false;//-------3

                //设置开始测试
                StopTest(Laneindex,true);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "异常提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }





        private bool BuildOutTask(int Laneindex, string device, string CellCode)
        {
            try
            {
                if (device.Length == 0)
                {
                    //MessageBox.Show("请选择终点设备!", "误操作提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                    return false;
                }
                if (WcfControlMonitorLib.CStaticClass.TestEndDevice.ContainsKey(Laneindex) == false)
                {
                    WcfControlMonitorLib.CStaticClass.TestEndDevice.Add(Laneindex, device);
                }

                WcfControlMonitorLib.CStaticClass.TestEndDevice[Laneindex] = device;


                int enddevice = Convert.ToInt32(device);//出库到入库口

                //判断货位是否合法
                if (dbo.Exists("SELECT FID FROM ST_CELL where FCELLSTATUS<> '-1'and FLaneWay=" + Laneindex + " and FCELLCODE='" + CellCode + "'") == false)
                {
                    MessageBox.Show("您输入的货位不存在,请重新输入!", "误操作提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                    return false;
                }

                //根据终点设备编码,获得到托盘类型
                //string GBDevice = "14205;14215;14225;14235;14245;14255;15205;15221;15231;15247";
                //string LT1Device = "15211;15237";
                //string LT2Device = "15253";
                //int boxtype = 1;

                //if (GBDevice.Contains(enddevice.ToString()))
                //{
                //    boxtype = 1;
                //}
                //else
                //    if (LT1Device.Contains(enddevice.ToString()))
                //    {
                //        boxtype = 2;
                //    }
                //    else
                //        if (LT2Device.Contains(enddevice.ToString()))
                //        {
                //            boxtype = 3;
                //        }
                //        else
                //        {
                //            MessageBox.Show("选择的终点设备有误,请重新选择!", "误操作提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                //            return false;
                //        }

                //
                    //if (!CheckCellIfOK(Laneindex, device, boxtype, CellCode))
                    //{
                    //    MessageBox.Show("开始货位坐标与终点设备(托盘类型)不匹配,请重新选择!", "误操作提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                    //    return false;
                    //}

                    //if (MessageBox.Show("请确认开始货位坐标与终点设备(托盘类型)之间的关系,不要输错!确认开始测试吗?", "操作提示:", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
                    //{
                    //    return false;
                    //}

                    string dtimes = DateTime.Now.ToString("u");//20101028
                    dtimes = dtimes.Substring(0, dtimes.Length - 1);//20101028
                    //string stack = "0";//堆垛机FSTACK

                    string stack = CStaticClass.GetStackIndexFromLaneInfo(Laneindex).ToString();
                    int AutoManageIdx = ccf.GetTempManageIdx();//调度任务索引

                    string barcode = AutoManageIdx.ToString();//托盘条码
                    int ifrevolve = 1;
                    int controltype = 2;//出库


                    string sqlstr = string.Format("insert into T_Manage_Task(FID,FPALLETBARCODE,FCONTROLTASKTYPE,F_ManageTaskKindIndex,FSTARTWAREHOUSE,FSTARTDEVICE,FSTARTCELL,FENDWAREHOUSE,FENDDEVICE,FENDCELL,FLANEWAY,FSTACK,FUseAwayFork,FBEGTIME,FStartCol,FStartLayer,FLOGIC_AREA) values ({0},'{1}',{2},{3},{4},{5},'{6}',{7},{8},'{9}',{10},{11},'{12}','{13}',{14},{15},'{16}')", AutoManageIdx, barcode, controltype, 2, 1, Laneindex, CellCode, 1, enddevice, "-", Laneindex, stack, "0", dtimes, 0, 0, enddevice);

                    dbo.ExceSQL(sqlstr);

                    dbo.ExceSQL("update ST_CELL set FRunStatus = 1,FUCONVEYOR = 1   where FLaneWay= " + Laneindex + "  and   fcellcode = '" + CellCode + "'");


                    //保存上次使用的货位编码
                    if (WcfControlMonitorLib.CStaticClass.TestCell.ContainsKey(Laneindex) == false)
                    {
                        WcfControlMonitorLib.CStaticClass.TestCell.Add(Laneindex, CellCode);
                    }

                    WcfControlMonitorLib.CStaticClass.TestCell[Laneindex] = CellCode;

                    return true ;
                

            }
            catch (Exception ex)
            { 
                
                return   false;
            }

        }
        private bool CheckCellIfOK(int lane, string device, int boxtype, string CellCode)
        {

            char[] cc = new char[1] { '-' };
            string[] sp = CellCode.Split(cc);
            string sqlstr = string.Empty;
            string sqlshort = "1=1";
            bool checkresult = true;

            if (sp.Length > 2)
            {
                if (lane == 18001 || lane == 18002)//14801,14802
                {
                    //只存储GB
                    //不受限制的分配货位
                    checkresult = true;
                }
                else
                    if (lane == 15801)
                    {
                        //判断GB /LT1
                        //GB
                        if (boxtype == 1)
                        {
                            checkresult = true;
                            //不受限制
                        }
                        else
                            if (boxtype == 2)//LT1
                            {
                                sqlshort = "( F_X>=3  And  F_X<81  And F_X%3=0 ) ";

                            }
                    }
                    else//15802
                    {
                        //判断GB,LT1,LT2
                        if (boxtype == 1)
                        {
                            //不受限制
                            checkresult = true;
                        }
                        else//LT1
                            if (boxtype == 2)
                            {

                                sqlshort = "((F_Z=7 And F_X>=2 And F_X<80 And F_X%3=2 )or (F_Z=8 And F_X>=3 And F_X<34 And F_X%8=3 ) or (F_Z=8 And F_X>=34 And F_X<76 And F_X%3=1 )) ";
                            }
                            else//LT2
                                if (boxtype == 3)
                                {
                                    sqlshort = "(F_Z=8 And F_X>=2 And F_X<34 And F_X%4=2 ) ";
                                }


                    }
                //判读是否满足条件
                sqlstr = string.Format("SELECT  * FROM ST_CELL WHERE (FLaneWay = {0}) and (FCELLCODE='{1}')  and {2}  ORDER BY F_Y asc,F_Z,F_X asc", lane, CellCode, sqlshort);
                    //DataView dv0 = dbo.ExceSQL("SELECT * FROM ST_CELL WHERE  (FCELLSTATUS = 0) and (FLaneWay=" + lane + ") and (FID>" + dv[0]["FID"] + ") order by fid asc").Tables[0].DefaultView;

                    DataView dv0 = dbo.ExceSQL(sqlstr).Tables[0].DefaultView;
                    if (dv0.Count > 0)
                    {
                        checkresult = true;
                    }
                    else
                    {
                        checkresult = false;
                    }
            }
            else
            {
                checkresult = false;
            }
            return checkresult;
 
        }





        private void button2_Click_1(object sender, EventArgs e)
        {
            try
            {
                int Laneindex = Convert.ToInt32(tLane1.Text);//巷道--1
                dbo.ExceSQL("update ST_CELL set FUCONVEYOR = 0  where FLaneWay= " + Laneindex);



            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "异常提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void button3_Click_1(object sender, EventArgs e)
        {
            try
            {
                int Laneindex = Convert.ToInt32(tLane2.Text);//巷道--1
                dbo.ExceSQL("update ST_CELL set FUCONVEYOR = 0  where FLaneWay= " + Laneindex);



            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "异常提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }



        private void btteststop2_Click(object sender, EventArgs e)
        {
            try
            {
                int Laneindex = Convert.ToInt32(tLane2.Text);//巷道--1

                //btteststart2.Enabled = true;//----2
                //btteststop2.Enabled = false;//-------3
                //设置开始测试
                StopTest(Laneindex, true);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "异常提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }



        private void button5_Click(object sender, EventArgs e)
        {

                try
                {
                    int Laneindex = Convert.ToInt32(tbLane1.Text);
                    if (cbLane1Count.Text.Length >0)
                    {


                        int[] station = new int[] { 12013, 12012, 12011, 12010, 12009, 12008, 12007 };
                        int count = 1;


                        int stationcount = Convert.ToInt32(cbLane1Count.Text);

                        int[] newstation = new int[stationcount];
                        for (int i = 0; i < stationcount && i < station.Length; i++)
                        {
                            if (WcfControlMonitorLib.CStaticClass.ContainAGV)
                            {
                            newstation[i] = 12009;
                            }
                            else
                           {
                               newstation[i] = station[i];
                            }
                        }
                        BuildOutTask(Laneindex, newstation, count);
                    }
                    StopTest(Laneindex,false);
                    StopOut(Laneindex, false);
                    StopIn(Laneindex, false);
                    WcfControlMonitorLib.CStaticClass.TestKind = 1;
                        
                }
            catch(Exception ex )              
                {
                    MessageBox.Show(ex.Message, "异常提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
               }


        }

        private static void StopTest(int Laneindex,bool flag)
        {
            //设置开始测试
            if (WcfControlMonitorLib.CStaticClass.StopTest.ContainsKey(Laneindex) == false)
            {
                WcfControlMonitorLib.CStaticClass.StopTest.Add(Laneindex, flag);
            }

            WcfControlMonitorLib.CStaticClass.StopTest[Laneindex] = flag;
        }

        private int BuildOutTask(int Laneindex,int [] station, int taskcount)
        {

            try
            {
                string dtime = DateTime.Now.ToString("u");//20101028
                dtime = dtime.Substring(0, dtime.Length - 1);//20101028
                int truecount=0;
                for (int i = 0;i<station.Length ; i++)
                {

                    int enddevice = station[i];//出库到入库口
                    bool findcell = true ;
                    for (int k = 0; k < taskcount;k++ )
                    {
                        string CellCode = WcfControlMonitorLib.CStaticClass.SelectGoodsCell(Laneindex, enddevice);
                        if (CellCode != "-")
                        {
                            string stack = CStaticClass.GetStackIndexFromLaneInfo(Laneindex).ToString();
                            string barcode = WcfControlMonitorLib.CStaticClass.GetCellBarCode(CellCode, Laneindex);//托盘条码

                            int AutoManageIdx = ccf.GetTempManageIdx();//调度任务索引
                            //int ifrevolve = 0;// ccf.GetIFRevolve(startdevice, string.Empty, enddevice, string.Empty);

                            //int boxtype = 1;

                            string sqlstr = string.Format("insert into T_Manage_Task(FID,FPALLETBARCODE,FCONTROLTASKTYPE,F_ManageTaskKindIndex,FSTARTWAREHOUSE,FSTARTDEVICE,FSTARTCELL,FENDWAREHOUSE,FENDDEVICE,FENDCELL,FLANEWAY,FSTACK,FUseAwayFork,FBEGTIME,FStartCol,FStartLayer,FLOGIC_AREA) values ({0},'{1}',{2},{3},{4},{5},'{6}',{7},{8},'{9}',{10},{11},'{12}','{13}',{14},{15},'{16}')", AutoManageIdx, barcode, 2, 2, 1, Laneindex, CellCode, 1, enddevice, "-", Laneindex, stack, "0", dtime, 0, 0, enddevice);

                            dbo.ExceSQL(sqlstr);
                            truecount++;
                            findcell = true;
                        }
                        else
                        {
                            findcell = false;
                            break;
                        }
                    }
                    if(!findcell)
                    {
                        break;
                    }

                }
                return truecount;
            }
            catch (Exception ex)
            {
                throw ex;
            }



        }

        private void button10_Click(object sender, EventArgs e)
        {
            int Laneindex = Convert.ToInt32(tbLane2.Text);
            StopIn(Laneindex, true);
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            int Laneindex = Convert.ToInt32(tbLane1.Text);
            StopOut(Laneindex,true);
        }

        void StopOut(int Laneindex,bool flag)
        {

            if (WcfControlMonitorLib.CStaticClass.StopOut.ContainsKey(Laneindex) == false)
            {
                WcfControlMonitorLib.CStaticClass.StopOut.Add(Laneindex, flag);
            }

            WcfControlMonitorLib.CStaticClass.StopOut[Laneindex] = flag;
        }
        void StopIn(int Laneindex,bool flag)
        {

            if (WcfControlMonitorLib.CStaticClass.StopIn.ContainsKey(Laneindex) == false)
            {
                WcfControlMonitorLib.CStaticClass.StopIn.Add(Laneindex, flag);
            }

            WcfControlMonitorLib.CStaticClass.StopIn[Laneindex] = flag;
        }
        private void button4_Click(object sender, EventArgs e)
        {
            int Laneindex = Convert.ToInt32(tbLane1.Text);
            StopIn(Laneindex,true);
        }

        private void button9_Click(object sender, EventArgs e)
        {
            int Laneindex = Convert.ToInt32(tbLane1.Text);
            StopTest(Laneindex, true);
            StopOut(Laneindex, true);
            StopIn(Laneindex, true);
        }

        private void button6_Click_1(object sender, EventArgs e)
        {
            try
            {
                int Laneindex = Convert.ToInt32(tbLane2.Text);
                if (cbLane2Count.Text.Length > 0)
                {


                    int[] station = new int[] { 12114, 22116 };



                    int count = Convert.ToInt32(cbLane2Count.Text);


                    BuildOutTask(Laneindex, station, count);
                }
                StopTest(Laneindex, false);
                StopOut(Laneindex, false);
                StopIn(Laneindex, false);
                WcfControlMonitorLib.CStaticClass.TestKind = 1;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "异常提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            int Laneindex = Convert.ToInt32(tbLane2.Text);
            StopOut(Laneindex, true);
        }

        private void button8_Click(object sender, EventArgs e)
        {
            int Laneindex = Convert.ToInt32(tbLane2.Text);
            StopTest(Laneindex, true);
            StopOut(Laneindex, true);
            StopIn(Laneindex, true);
        }

        private void button11_Click(object sender, EventArgs e)
        {
            int Laneindex = Convert.ToInt32(tLane1.Text);//巷道--1
            StopOut(Laneindex, true);
        }

        private void button13_Click(object sender, EventArgs e)
        {
            int Laneindex = Convert.ToInt32(tLane2.Text);//巷道--1
            StopOut(Laneindex, true);
        }

        private void button12_Click(object sender, EventArgs e)
        {
            int Laneindex = Convert.ToInt32(tLane1.Text);//巷道--1
            StopIn(Laneindex, true);
        }

        private void button14_Click(object sender, EventArgs e)
        {
            int Laneindex = Convert.ToInt32(tLane2.Text);//巷道--1
            StopIn(Laneindex, true);
        }

        private void button15_Click(object sender, EventArgs e)
        {
            WcfControlMonitorLib.CStaticClass.ContainAGV = true;//携带AGV

        }

        private void button16_Click(object sender, EventArgs e)
        {
            WcfControlMonitorLib.CStaticClass.ContainAGV = false;//禁止携带AGV
        }

        private void button17_Click(object sender, EventArgs e)
        {
            ccf.GetAvailableCellCode(12017, "18001,18002");
        }

        private void button17_Click_1(object sender, EventArgs e)
        {
            //ccf.GetNextCell("01-25-01", 18001);

        }
        
    }
}