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 SystemConfig
{
    public partial class FrmRouteDeviceEdit : Form
    {
        DBOperator dbo = CStaticClass.dbo;
        private static FrmRouteDeviceEdit _formInstance;

        public static FrmRouteDeviceEdit FormInstance
        {
            get
            {
                if (_formInstance == null)
                {
                    _formInstance = new FrmRouteDeviceEdit();

                }
                return _formInstance;
            }
            set { _formInstance = value; }
        }
        public FrmRouteDeviceEdit()
        {
            InitializeComponent();
            _formInstance = this;
            DataView dv = dbo.ExceSQL("select * from T_Base_Route ").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                this.comboBox1.ValueMember = "F_RouteID";
                this.comboBox1.DisplayMember = "F_RouteName";
                this.comboBox1.DataSource = dv;
                
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DataView dv = dbo.ExceSQL("SELECT  F_StartDevice, F_EndDevice,F_RouteKind FROM T_Base_Route where F_RouteID=" + this.comboBox1.SelectedValue).Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                List<List<int>> devs = SearchNextDevices(Convert.ToInt32(dv[0]["F_StartDevice"]), Convert.ToInt32(dv[0]["F_EndDevice"]), dv[0]["F_RouteKind"].ToString());
                if (devs.Count > 0)
                {
                    for (int i = 0; i <devs.Count; i++)
                    {
                        
                        List<int> devline = devs[i];
                        ListViewItem lvi = new ListViewItem(this.comboBox1.SelectedValue.ToString());
                        lvi.SubItems.Add(this.comboBox1.Text + "的路径:" + (i + 1).ToString());
                        for (int j = (devline.Count - 1); j >= 0; j--)
                        {
                            if (listView1.Columns.Count <= devline.Count+1)
                            {
                                for (int kk = 0; kk <= (devline.Count - listView1.Columns.Count+2); kk++)
                                {
                                    listView1.Columns.Add("columnsHeader");
                                }
                            }
                            lvi.SubItems.Add(devline[j].ToString());
                        }
                        listView1.Items.Add(lvi);
                    }
                }
                else
                {

                }
                
            }
            
        }
        List< List<int>> SearchNextDevices(int startdev, int enddev, string  RouteKind)
        {
            List<List<int>> rets = new List<List<int>>();
            List<List<int>> rets0 = new List<List<int>>();
            List<List<int>> rets1 = new List<List<int>>();
            switch (RouteKind)
            {
                case "1"://入库，只在入库的方向F_InputNextDevice查找设备
                    rets = RecursionDevices(startdev, enddev, "F_InputNextDevice");
                    break;
                case "2"://出库，只出库的方向F_OutputNextDevice查找设备
                    rets = RecursionDevices(startdev, enddev, "F_OutputNextDevice");
                    break;
                case "3"://移库，遇到堆垛机、RGV、AGV等设备要考虑转换设备入库F_InputNextDevice和出库F_OutputNextDevice方向属性
                    #region 移库
                    
                    if (checkBox1.Checked == true)
                    {
                        if (comboBox2.Text !=null)
                        {
                            rets0 = RecursionDevices(startdev, Convert.ToInt32(comboBox2.Text), "F_InputNextDevice");
                            if (rets0.Count > 0)
                            {
                                rets1 = RecursionDevices(Convert.ToInt32(comboBox2.Text), enddev, "F_OutputNextDevice");
                                if (rets1.Count > 0)
                                {
                                    for (int i = 0; i < rets1.Count; i++)
                                    {
                                        List<int> rets1line = rets1[i];
                                        for (int j = 0; j < rets0.Count; j++)
                                        {
                                            List<int> rets0line = rets0[j];
                                            for (int k = 0; k < rets0line.Count; k++)
                                            {
                                                int rets0element = rets0line[k];
                                                if (rets1line.Contains(rets0element) == false)
                                                {
                                                    rets1line.Add(rets0element);
                                                }
                                            }
                                        }
                                        rets.Add(rets1line);
                                    }
                                }
                            }
                            else
                            {
                                rets0 = RecursionDevices(startdev, Convert.ToInt32(comboBox2.Text), "F_OutputNextDevice");
                                if (rets0.Count > 0)
                                {
                                    rets1 = RecursionDevices(Convert.ToInt32(comboBox2.Text), enddev, "F_InputNextDevice");
                                    if (rets1.Count > 0)
                                    {
                                        for (int i = 0; i < rets1.Count; i++)
                                        {
                                            List<int> rets1line = rets1[i];
                                            for (int j = 0; j < rets0.Count; j++)
                                            {
                                                List<int> rets0line = rets0[j];
                                                for (int k = 0; k < rets0line.Count; k++)
                                                {
                                                    int rets0element = rets0line[k];
                                                    if (rets1line.Contains(rets0element) == false)
                                                    {
                                                        rets1line.Add(rets0element);
                                                    }
                                                }
                                            }
                                            rets.Add(rets1line);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    #endregion
                    break;
                    
                default:
                    break;
                    
            }
            return rets;
        }
        /// <summary>
        /// 递归形成List< List<int>>的倒序的设备串集合的集合
        /// </summary>
        /// <param name="startdev"></param>
        /// <param name="enddev"></param>
        /// <param name="IONextDevice"></param>
        /// <returns></returns>
        List< List<int>> RecursionDevices(int startdev, int enddev, string IONextDevice)
        {
            string sql = "";
            DataView dv;
            string nextdev = "";
            string[] spl;
            char[] cc = new char[1] { ';' }; 
            List<List<int>> routedevs = new List<List<int>>();
            sql = "SELECT " + IONextDevice + " FROM T_Base_Device where F_DeviceIndex=" + startdev;
            dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                nextdev = dv[0][IONextDevice].ToString();

                if (nextdev.Length > 0)
                {
                    spl = nextdev.Split(cc);
                    for (int i = spl.GetLowerBound(0); i <= spl.GetUpperBound(0);i++ )
                    {

                        List< List<int>> rs = RecursionSingle(Convert.ToInt32( spl[i]), enddev, IONextDevice);
                        if (rs.Count > 0)
                        {
                            //返回多条路经设备集合的集合
                            List<int> rss=new List<int>();
                            for (int ii = 0; ii < rs.Count; ii++)
                            {
                                rss = rs[ii];
                                if (rss.Contains(Convert.ToInt32(spl[i])) == false)
                                {
                                    rss.Add(Convert.ToInt32(spl[i]));
                                }
                                
                                if (rss.Contains(startdev) == false)
                                {
                                    rss.Add(startdev);
                                }
                                if (routedevs.Contains(rss) == false)
                                {
                                    routedevs.Add(rss);
                                }
                            }
                            //Predicate<List<int>> FindValue = delegate(List<int> obj) { return obj.Contains(Convert.ToInt32(spl[i])); };

                            
                            
                        }
                        
                    }

                    return routedevs;
                    //返回值

                }
                
            }
            return routedevs;
            //返回值
        }
        List< List<int>> RecursionSingle(int startdev, int enddev, string IONextDevice)
        {
            
            char[] cc = new char[1] { ';' };
            List<int> routedevs = new List<int>();
            List<List<int>> mutiRoute = new List<List<int>>();

            #region 递归获得多条路径详细设备集合

            if (startdev == enddev)//找到了终点设备
            {

             
                string sqllast = "SELECT " + IONextDevice + " FROM T_Base_Device where F_DeviceIndex=" + startdev;
               DataView  dv = dbo.ExceSQL(sqllast).Tables[0].DefaultView;
                if (dv.Count >0)
                {
                    string  nextdev = dv[0][IONextDevice].ToString();
                    if (nextdev == "19001")
                    {
                        routedevs.Add(19001);
                    }
                }

                if (routedevs.Contains(enddev) == false)
                {
                    routedevs.Add(enddev);
                }
                if (routedevs.Contains(startdev) == false)
                {
                    routedevs.Add(startdev);
                }
                mutiRoute.Add(routedevs);
                return mutiRoute;
            }
            else//接着找
            {
                List< List<int>> mutireturndevs = RecursionDevices(startdev, enddev, IONextDevice);
                if (mutireturndevs.Count > 0)
                {
                    for (int k = 0; k < mutireturndevs.Count; k++)
                    {
                        //List<int> returndevs = mutireturndevs[k];
                        //if (returndevs.Count > 0)
                        //{
                        //    for (int j = 0; j < returndevs.Count; j++)
                        //    {

                        //        if (routedevs.Contains(returndevs[j]) == false)
                        //        {
                        //            routedevs.Add(returndevs[j]);

                        //        }

                        //    }
                        //    if (routedevs.Contains(startdev) == false)
                        //    {
                        //        routedevs.Add(startdev);

                        //    }
                        //    mutiRoute.Add(routedevs);
                            
                        //}
                        if (mutireturndevs[k].Contains(startdev) == false)
                        {
                            mutireturndevs[k].Add(startdev);

                        }
                        mutiRoute.Add(mutireturndevs[k]);
                    }
                }
                return mutiRoute;

            }
            #endregion
        }

        private void button2_Click(object sender, EventArgs e)
        {

            for (int i = 0; i < listView1.Items.Count; i++)
            {
                ListViewItem lvi = listView1.Items[i];
                if (lvi.Checked == true)
                {
                    //增加对F_RouteIDSub值的判断：
                    //如果表中存在F_RouteID那么F_RouteIDSub的取值就是对应的F_RouteIDSub+1
                    //否则，F_RouteIDSub的值就是F_RouteID+"001"
                    int routeIDSub = GetRouteIDSub(Convert.ToInt32( lvi.Text));
                    int sn = 0;
                    for (int j = 2; j < lvi.SubItems.Count; j++)
                    {
                        int max = GetMaxRouteDeviceIndex();
                        sn = sn + 1;
                        string sql = "INSERT INTO T_Base_Route_Device "+
                            "(F_RouteDeviceIndex, F_RouteID, F_DeviceIndex, F_SerialNumber,F_RouteIDSub)VALUES " +
                            "(" + max + "," + lvi.Text + "," + lvi.SubItems[j].Text + "," + sn + "," + routeIDSub + ")";
                        dbo.ExceSQL(sql);

                    }
                }
            }
        }
        int GetMaxRouteDeviceIndex()
        {
            DataView dv = dbo.ExceSQL("SELECT MAX(F_RouteDeviceIndex) AS MaxIndex FROM T_Base_Route_Device").Tables[0].DefaultView; ;
            if (dv.Count > 0)
            {
                if (dv[0]["MaxIndex"].ToString().Length > 0)
                {
                    return (Convert.ToInt32(dv[0]["MaxIndex"]) + 1);
                }
                else
                {
                    return 1;
                }
            }
            else
            {
                return 1;
            }
        }

        int GetRouteIDSub(int routeID)
        {
            DataView dv = dbo.ExceSQL("SELECT F_RouteIDSub  FROM T_Base_Route_Device where F_RouteID=" + routeID + " order by F_RouteIDSub desc").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
               return  (Convert.ToInt32(dv[0]["F_RouteIDSub"]) + 1);
            }
            else
            {
               return  Convert.ToInt32 (routeID.ToString() + "001");
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox1.SelectedValue.ToString().Length <= 0) return;
            comboBox2.Items.Clear();
            DataView dv = dbo.ExceSQL("SELECT F_OutsideAltDevice, F_InsideAltDevice FROM T_Base_Route WHERE (F_RouteID = " + comboBox1.SelectedValue.ToString() + ")").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                if (dv[0]["F_OutsideAltDevice"].ToString().Length > 0)
                {
                    comboBox2.Items.Add(dv[0]["F_OutsideAltDevice"]);
                }
                if (dv[0]["F_InsideAltDevice"].ToString().Length > 0)
                {
                    comboBox2.Items.Add(dv[0]["F_InsideAltDevice"]);
                }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            listView1.Items.Clear();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            DataView dv = dbo.ExceSQL("SELECT F_routeID,f_routename, F_StartDevice, F_EndDevice,F_RouteKind FROM T_Base_Route  order by F_routeID asc").Tables[0].DefaultView;
            for(int k=0;k<dv.Count;k++)
            {
                List<List<int>> devs = SearchNextDevices(Convert.ToInt32(dv[k]["F_StartDevice"]), Convert.ToInt32(dv[k]["F_EndDevice"]), dv[k]["F_RouteKind"].ToString());
                if (devs.Count > 0)
                {
                    for (int i = 0; i < devs.Count; i++)
                    {
                        List<int> devline = devs[i];
                        ListViewItem lvi = new ListViewItem(dv[k]["F_routeID"].ToString());
                        lvi.SubItems.Add(dv[k]["F_routeID"].ToString() + "的路径:" + (i + 1).ToString());
                        for (int j = (devline.Count - 1); j >= 0; j--)
                        {
                            if (listView1.Columns.Count <= devline.Count + 1)
                            {
                                for (int kk = 0; kk <= (devline.Count - listView1.Columns.Count + 2); kk++)
                                {
                                    listView1.Columns.Add("columnsHeader");
                                }
                            }
                            lvi.SubItems.Add(devline[j].ToString());
                        }
                        listView1.Items.Add(lvi);
                    }
                }
                else
                {

                }

            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < listView1.Items.Count; i++)
            {
                listView1.Items[i].Checked = true;
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < listView1.Items.Count; i++)
            {
                listView1.Items[i].Checked = false;
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            string [] str =this.comboBox1.Text.ToString ().Split('-');
            string str_route = string.Empty;
            string end_route = string.Empty;
            if(str.Length <=2)
            {
                return ;
            }
            else
            {
                 str_route =str[0].ToString ()+"-"+str[1].ToString ();
                 end_route= str[1].ToString ()+"-"+str[2].ToString ();

                 DataView dv = dbo.ExceSQL("   select F_DeviceIndex from T_Base_Route_Device where F_RouteID = (select F_RouteID from T_Base_Route where F_RouteName ='" + str_route + "')    union all        select F_DeviceIndex from T_Base_Route_Device where F_RouteID = (select F_RouteID from T_Base_Route where F_RouteName ='" + end_route + "')").Tables[0].DefaultView;

               
                    
                    // List<int> devline = devs[i];
                     ListViewItem lvi = new ListViewItem(this.comboBox1.SelectedValue.ToString());
                     lvi.SubItems.Add(this.comboBox1.Text + "的路径:" + ( 1).ToString());
                     for (int j = 0; j < dv.Count; j++)
                     {
                         //if (listView1.Columns.Count <= dv.Count + 1)
                         //{
                         //    for (int kk = 0; kk <= (dv.Count - listView1.Columns.Count + 2); kk++)
                         //    {
                                 listView1.Columns.Add("columnsHeader");
                         //    }
                         //}
                         lvi.SubItems.Add(dv[j]["F_DeviceIndex"].ToString());
                     }
                     listView1.Items.Add(lvi);
            }
        }






    }
}