using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace SSLMS.MobileUI.uc
{
    public partial class ucCell : UserControl
    {

        private double dRoundW = 1;

        private double dRoundH = 1.5;

        private int iFill = 0;

        private DataTable dtCellSize;

        private DataTable dtCell;

        private int iMaxX = 0;

        private int iMaxY = 0;

        private int iMinX = 0;

        private int iMinY = 0;

        private int iBorderW = 0;

        private int iBorderH = 0;

        private int iDeepRackMove = 5;

        private int iYTransform = 0;

        private int iXTransform = 0;

        private WH_CELL mST_CELL = null;

        int iCurrentPage = 1;

        int iRowPerPage =10;

        public bool EmptySelect = false;


        public bool PalletSelect = false;



        private int iFillW
        {
            get { return Convert.ToInt32(iFill * dRoundW); }
        }

        private int iFillH
        {
            get { return Convert.ToInt32(iFill * dRoundH); }
        }

        private Bitmap imgCell;

        private Rectangle[] recCell = null;

        private string[] strCellCode = null;

        private string CellStorageStatus = string.Empty;

        private string CellRunStatus = string.Empty;

        private Rectangle rectSelect = Rectangle.Empty;

        public delegate void CELLDoubleClickHandler(WH_CELL mWH_CELL);


        public event CELLDoubleClickHandler CellDoubleClick;

        public ucCell()
        {
            InitializeComponent();
        }


        public void Init()
        {
            this.iBorderW = 1;

            this.iBorderH = 1;

            this.iFill = 20;

            this.iCurrentPage = 1;

            this.cmbWAREHOUSE_Bind();

            this.InitCell();

            this.tscbCELL_Z.SelectedValueChanged += new EventHandler(tscbCELL_Z_SelectedValueChanged);
        }

        private void cmbWAREHOUSE_Bind()
        {
            tscbWAREHOUSE.DisplayMember = "WAREHOUSE_NAME";

            tscbWAREHOUSE.ValueMember = "WAREHOUSE_ID";

            tscbWAREHOUSE.DataSource = Program._I_PDAService.GetList(string.Format(@"SELECT WAREHOUSE_ID,WAREHOUSE_NAME FROM WH_WAREHOUSE 
                                                        WHERE {0} {1}",
                                                        Program._USER.USER_ID == 0 ? "1=1" : string.Format(@"(WAREHOUSE_ID IN(SELECT RELATION_ID2 
                                                        FROM V_SYS_RELATION WHERE RELATION_CODE='SYS_USER-WH_WAREHOUSE'
                                                        AND RELATION_ID1= {0}))", Program._USER.USER_ID),
                                                        string.Empty)); ;
        }

        private void tscbCELL_Z_Bind(string WAREHOUSE_ID)
        {
            tscbCELL_Z.DisplayMember = "CELL_Z_NAME";

            tscbCELL_Z.ValueMember = "CELL_Z";

            tscbCELL_Z.DataSource = Program._I_PDAService.GetList(string.Format("SELECT * FROM V_WH_CELL_Z WHERE WAREHOUSE_ID ={0} ORDER BY CELL_Z", WAREHOUSE_ID));
        }

        void tscbCELL_Z_SelectedValueChanged(object sender, EventArgs e)
        {
            try
            {
                this.InitCell();
            }
            catch (Exception ex)
            {
                MessageBox.Show("初始化货位失败!\n" + ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.None,MessageBoxDefaultButton.Button1);

            }
        }

        private void InitCell()
        {
            this.dtCellSize = Program._I_PDAService.GetList(string.Format( @"SELECT MIN(CELL_X) AS MIN_CELL_X,
                                                                            MAX(CELL_X) AS MAX_CELL_X,
                                                                            MIN(CELL_Y) AS MIN_CELL_Y,
                                                                            MAX(CELL_Y) AS MAX_CELL_Y 
                                                                            FROM  V_WH_CELL  
                                                                            WHERE  warehouse_id={0} and cell_z={1} ",this.tscbWAREHOUSE.SelectedValue.ToString(), this.tscbCELL_Z.SelectedValue.ToString()));

            this.dtCell = Program._I_PDAService.GetList(string.Format("SELECT * FROM WH_CELL WHERE 1=1 {0} {1} {2} {3} {4}",
                                                                        string.IsNullOrEmpty(this.tscbWAREHOUSE.SelectedValue.ToString()) ? string.Empty : string.Format("  AND WAREHOUSE_ID ={0}", this.tscbWAREHOUSE.SelectedValue.ToString()),
                                                                         string.Empty ,
                                                                        string.IsNullOrEmpty(SSLMS.Model.CELL_TYPE.Cell.ToString()) ? string.Empty : string.Format(" AND CELL_TYPE LIKE '{0}'", SSLMS.Model.CELL_TYPE.Cell.ToString()),
                                                                        string.IsNullOrEmpty(this.tscbCELL_Z.SelectedValue.ToString()) ? string.Empty : string.Format(" AND CELL_Z = {0}", this.tscbCELL_Z.SelectedValue.ToString()),
                                                                        string.Format(" AND CELL_x BETWEEN {0} AND {1} ", (this.iCurrentPage - 1) * this.iRowPerPage + 1, (this.iCurrentPage) * this.iRowPerPage)
                                                                        ));
                                                                        

            //this.dtCell = Program._I_WHService.CellGetPageLogicalLineCellList(this.tscbWAREHOUSE.SelectedValue.ToString(), 
            //                                                                       string.Empty, 
            //                                                                       SSLMS.Model.CELL_TYPE.cell.ToString(),
            //                                                                       this.tscbCELL_Z.SelectedValue.ToString(), (this.iCurrentPage - 1) * this.iRowPerPage +1, (this.iCurrentPage) * this.iRowPerPage);

            this.iMaxY = Convert.ToInt32(dtCellSize.Rows[0]["MAX_CELL_Y"]);

            this.iMinY = Convert.ToInt32(dtCellSize.Rows[0]["MIN_CELL_Y"]);

            this.iMaxX = Convert.ToInt32(dtCellSize.Rows[0]["MAX_CELL_X"]);

            this.iMinX = Convert.ToInt32(dtCellSize.Rows[0]["MIN_CELL_X"]);

            this.pictureBox1.Width = (this.iRowPerPage+1 )* iFillW;

            this.pictureBox1.Height = (iFillH) * (iMaxY + 1);

            //this.pictureBox1.Width = (iMaxX) * (iFillW) > this.pictureBox1.Parent.Width ? (iMaxX + 2) * (iFillW) : this.pictureBox1.Parent.Width - 20;

            //this.pictureBox1.Height = (iFillH) * (iMaxY + 2) > this.pictureBox1.Parent.Height ? (iFillH) * (iMaxY + 2) : this.pictureBox1.Parent.Height - 20;

            imgCell = new Bitmap(this.pictureBox1.Width, this.pictureBox1.Height);

            

            this.iYTransform = this.pictureBox1.Height - this.iFillH;

            this.iXTransform = (this.iCurrentPage - 1) * this.iRowPerPage * this.iFillW;

            this.pictureBox1.Image = imgCell;

            this.DrawCell();
        }

        private void DrawCell()
        {
            Graphics g = Graphics.FromImage(imgCell);

            g.FillRectangle(new SolidBrush(Color.Gray), 0, 0, this.imgCell.Width, this.imgCell.Height);

            //x轴刻度
            for (int x = (this.iCurrentPage-1) * this.iRowPerPage + 1; x <= this.iCurrentPage * this.iRowPerPage; x++)
            {
                g.DrawLine(new Pen(Color.FromArgb(0, 0, 255)), x * this.iFillW, iYTransform, x * this.iFillW, -2 +iYTransform);

                g.FillRectangle(new SolidBrush(Color.Gray), (x % this.iRowPerPage == 0 ? this.iRowPerPage : x % this.iRowPerPage) * this.iFillW, iYTransform, this.iFillW, this.iFillH);

                g.DrawString(x.ToString(),new Font(FontFamily.GenericSerif, this.iFill / 2,FontStyle.Regular), new SolidBrush(Color.Blue) ,  (x%this.iRowPerPage==0 ? this.iRowPerPage: x%this.iRowPerPage) * this.iFillW, iYTransform);
            }

            // y轴刻度
            for (int y = this.iMaxY; y > 0; y--)
            {
                g.DrawLine(new Pen(Color.FromArgb(0, 0, 255)), this.iFillW, -y * this.iFillH + iYTransform, this.iFillW - 2, -y * this.iFillH + iYTransform);

                g.DrawString(y.ToString().PadLeft(this.iMaxY.ToString().Length), new Font(FontFamily.GenericSerif, this.iFill / 2, FontStyle.Regular), new SolidBrush(Color.Blue), this.iFillW - (this.iMaxY.ToString().Length * this.iFill / 2), -y * this.iFillH + iYTransform);
            }

            this.recCell = new Rectangle[this.dtCell.Rows.Count];

            this.strCellCode = new string[this.dtCell.Rows.Count];

            //货位
            for (int i = 0; i < this.dtCell.Rows.Count; i++)
            {
                int x = Convert.ToInt32(dtCell.Rows[i]["CELL_X"]);

                int y = Convert.ToInt32(dtCell.Rows[i]["CELL_Y"]);

                int z = Convert.ToInt32(dtCell.Rows[i]["CELL_Z"]);

                int CELL_ID = Convert.ToInt32(dtCell.Rows[i]["CELL_ID"]);

                string CELL_STATUS = dtCell.Rows[i]["CELL_STATUS"].ToString();

                Color clr = new Color();

                switch (CELL_STATUS)
                {
                    case "have":

                        clr = Color.Chocolate;

                        break;

                    case "nohave":

                        clr = Color.Silver;

                        break;

                    case "exception":

                        clr = Color.FromArgb(255, 0, 0);

                        break;
                    case "pallet":

                        clr = Color.ForestGreen;

                        break;
                    default:

                        clr = Color.FromArgb(192, 192, 192);

                        break;
                }



                if (dtCell.Rows[i]["CELL_Z"].ToString() != dtCell.Rows[i]["SHELF_NEIGHBOUR"].ToString())
                {
                    if (dtCell.Rows[i]["SHELF_TYPE"].ToString() == SSLMS.Model.SHELF_TYPE.deep.ToString())


                        recCell[i] = new Rectangle(x * (this.iFillW) + this.iBorderW + this.iDeepRackMove  - this.iXTransform,
                                                              -y * (this.iFillH) + this.iBorderH + this.iYTransform,
                                                              this.iFillW - 2 * this.iBorderW,
                                                              (this.iFillH - 2 * this.iBorderH) / 2);
                    else
                        recCell[i] = new Rectangle(x * (this.iFillW) + this.iBorderW - this.iXTransform,
                                                             -y * (this.iFillH) + this.iBorderH + (this.iFillH - 2 * this.iBorderH) / 2 + iYTransform,
                                                             this.iFillW - 2 * this.iBorderW,
                                                              (this.iFillH - 2 * this.iBorderH) / 2);
                }
                else
                {
                    recCell[i] = new Rectangle(x * (this.iFillW) + this.iBorderW - this.iXTransform,
                                                          -y * (this.iFillH) + this.iBorderH + iYTransform,
                                                          this.iFillW - 2 * this.iBorderW,
                                                            this.iFillH - 2 * this.iBorderH);

                }

                strCellCode[i] = dtCell.Rows[i]["CELL_CODE"].ToString();

                g.FillRectangle(new SolidBrush(clr), recCell[i]);

                g.DrawRectangle(new Pen(Color.Black), recCell[i]);

                g.DrawString(dtCell.Rows[i]["RUN_STATUS"].ToString().Substring(0, 1).ToUpper(),
                                  new Font(FontFamily.GenericSerif, recCell[i].Width / 3,FontStyle.Regular), new SolidBrush(Color.Black),
                                  recCell[i].Left + recCell[i].Width / 3, recCell[i].Top + recCell[i].Height / 3);

            }
        }

        private void tscbWAREHOUSE_SelectedValueChanged(object sender, EventArgs e)
        {
            if (this.tscbWAREHOUSE.SelectedValue != null)
            {
                string WAREHOUSE_ID = Convert.ToString(this.tscbWAREHOUSE.SelectedValue);

                this.tscbCELL_Z_Bind(WAREHOUSE_ID);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Init();
        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            Graphics g = Graphics.FromImage(imgCell);


            int i = 0;

            for (; i < recCell.Length; i++)
            {
                if (recCell[i].Contains(e.X, e.Y))
                {
                    mST_CELL = Program._I_PDAService.GetModelCellCode(strCellCode[i].ToString());

                    this.txtRow.Text = mST_CELL.CELL_Z.ToString().PadLeft(2, '0');

                    this.txtLine.Text = mST_CELL.CELL_X.ToString().PadLeft(2, '0');

                    this.txtFloor.Text = mST_CELL.CELL_Y.ToString().PadLeft(2, '0');

                    this.CellStorageStatus = mST_CELL.CELL_STATUS.ToString();

                    this.CellRunStatus = mST_CELL.RUN_STATUS.ToString();



                    g.DrawRectangle(new Pen(Color.Red), recCell[i]);

                    if (rectSelect != Rectangle.Empty && rectSelect != recCell[i])
                    {
                        g.DrawRectangle(new Pen(Color.Black), rectSelect);

                    }

                    this.rectSelect = recCell[i];

                    break;
                }
            }

            if (i >= recCell.Length)
            {
                this.txtRow.Text = string.Empty;

                this.txtLine.Text = string.Empty;

                this.txtFloor.Text = string.Empty;

                this.CellStorageStatus = string.Empty;

                this.CellRunStatus = string.Empty;
            }

            this.pictureBox1.Image = imgCell;
        }

        private void btnFirst_Click(object sender, EventArgs e)
        {
            this.iCurrentPage = 1;

            try
            {
                this.InitCell();
            }
            catch (Exception ex)
            {
                MessageBox.Show("初始化货位失败 !\n" + ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);

            }
        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            if (this.iCurrentPage == 1)
                return;

            this.iCurrentPage--;

            try
            {
                this.InitCell();
            }
            catch (Exception ex)
            {
                MessageBox.Show("初始化货位失败 !\n" + ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);

            }

        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (this.iCurrentPage * this.iRowPerPage > this.iMaxX)
                return;

            this.iCurrentPage++;

            try
            {
                this.InitCell();
            }
            catch (Exception ex)
            {
                MessageBox.Show("初始化货位失败 !\n" + ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);

            }
        }

        private void btnLast_Click(object sender, EventArgs e)
        {
            this.iCurrentPage = this.iMaxX / this.iRowPerPage+1;

            try
            {
                this.InitCell();
            }
            catch (Exception ex)
            {
                MessageBox.Show("初始化货位失败 !\n" + ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);

            }
        }

        private void pictureBox1_DoubleClick(object sender, EventArgs e)
        {
            if (this.EmptySelect)
            {
                if (this.CellStorageStatus != SSLMS.Model.CELL_STATUS.nohave.ToString() || this.CellRunStatus != SSLMS.Model.RUN_STATUS.enable.ToString())
                {
                    MessageBox.Show(" 请选择可用的空货位 ", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);
                    return;
                }

                if (mST_CELL == null)
                    return;


                if (mST_CELL.SHELF_TYPE.TrimEnd() == SSLMS.Model.SHELF_TYPE.normal.ToString() && mST_CELL.CELL_Z.ToString() != mST_CELL.SHELF_NEIGHBOUR.ToString())
                {
                   WH_CELL mST_CELL_INNER = Program._I_PDAService.GetModelCellCode(string.Format("{0}-{1}-{2}", mST_CELL.SHELF_NEIGHBOUR.ToString().PadLeft(2, '0'), mST_CELL.CELL_X.ToString().PadLeft(2, '0'), mST_CELL.CELL_Y.ToString().PadLeft(2, '0')));

                    if (mST_CELL_INNER != null && mST_CELL_INNER.CELL_STATUS == SSLMS.Model.CELL_STATUS.nohave.ToString() && mST_CELL_INNER.RUN_STATUS == SSLMS.Model.RUN_STATUS.enable.ToString())
                    {
                        MessageBox.Show(string.Format(" 请优先选择内侧货位 {0} ", mST_CELL_INNER.CELL_CODE), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);

                        this.mST_CELL.CELL_CODE = string.Empty;

                        return;
                    }

                }
            }

            if (this.PalletSelect)
            {
                if (this.CellStorageStatus != SSLMS.Model.CELL_STATUS.pallet.ToString() || this.CellRunStatus != SSLMS.Model.RUN_STATUS.enable.ToString())
                {
                    MessageBox.Show(" 请选择可用的托盘货位 ", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);
                    return;
                }

                if (mST_CELL == null)
                    return;



            }



            CellDoubleClick(this.mST_CELL);

        }

        private void btRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                this.InitCell();
            }
            catch (Exception ex)
            {
                MessageBox.Show("初始化货位失败 !\n" + ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);

            }
        }


    }
}