using RGD.Common;
using RGD.DataService;
using RGD.DBUtility;
using System;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace RGD.WCS
{
    public partial class FrmHandPastCommand : Form
    {
        private CCommonFunction ccf = new CCommonFunction();

        public FrmHandPastCommand()
        {
            InitializeComponent();
        }

        private void FrmHandPastCommand_Load(object sender, EventArgs e)
        {
            DataView dv = DbHelperSQL.Query("select F_DeviceIndex,F_DeviceName from T_Base_Device where F_DeviceKindIndex=33").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                this.cbDeviceName.DisplayMember = "F_DeviceName";
                this.cbDeviceName.ValueMember = "F_DeviceIndex";
                this.cbDeviceName.DataSource = dv;

                this.cbDeviceName.Text = "";
                this.cbDeviceName.SelectedIndex = 0;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox6.Text == "")
            {
                MessageBox.Show("请输入箱条码！", "操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            //20090910
            if (cbDeviceName.SelectedValue == null || this.cbDeviceName.Text.Trim() == "")
            {
                MessageBox.Show("请选择设备！", "操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.cbDeviceName.Focus();
                return;
            }

            int routeIDsub = GetRouteIDsub(Convert.ToInt32(cbDeviceName.SelectedValue));

            if (routeIDsub == -1)
            {
                MessageBox.Show("您选择的设备错误！", "操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            DataSet dss = DbHelperSQL.Query("SELECT T_Base_Device.F_DeviceKindIndex, F_DeviceCommandName,F_DeviceCommandIndex FROM " +
            "T_Base_Device , T_Base_Device_Command WHERE T_Base_Device.F_DeviceKindIndex" +
            "= T_Base_Device_Command.F_DeviceKindIndex and F_DeviceIndex=" +
            Convert.ToInt32(cbDeviceName.SelectedValue) + " and F_DeviceCommandIndex=" + (tabControl1.SelectedIndex + 1) + " and F_DeviceCommandIndex <> -1");
            if (dss.Tables[0].DefaultView.Count <= 0)
            {
                MessageBox.Show("请选择设备和对应的有效命令！", "操作提示：", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            //20101028
            string dtime = DateTime.Now.ToString("u");
            dtime = dtime.Substring(0, dtime.Length - 1);
            string qcell = string.Empty, scell = string.Empty;
            int hidx = 0;
            int hmindx = 0; int rehidx = 0;
            //20101028
            int z = 0, x = 0, y = 0, z1 = 0, x1 = 0, y1 = 0;
            //2	将取,3	将送,4	取货,5	送货
            int devicekind = BaseDeviceService.GetDeviceKindIdx(Convert.ToInt32(cbDeviceName.SelectedValue));

            //20101028
            hidx = GetManageHandIdx();
            hmindx = ccf.GetMonitorIndex(hidx, 4);
            string Sql = "insert into T_Monitor_Task(F_RouteID,F_ManageTaskIndex,F_ManageTaskKindIndex,F_MonitorIndex," +
                    "F_DeviceIndex,F_DeviceCommandIndex,F_NumParam1,F_NumParam4,F_TxtParam,F_PickUpLocation) " +
                    "values(" + routeIDsub + "," + hidx + ",4," + hmindx + "," + Convert.ToInt32(cbDeviceName.SelectedValue)
                    + "," + (tabControl1.SelectedIndex + 1) + ",0,0,'" + textBox6.Text + "'," + tbNUM.Text + ")";
            DbHelperSQL.ExecuteSql(Sql);

            foreach (DataRow dr in dataSet1.Tables[0].Rows)
            {
                DbHelperSQL.ExecuteSql(string.Format("insert into IO_VISION_DETAIL (box_barcode,goods_barcode,goods_location,user_no,user_add,user_name) values('{0}','{1}',{2},'{3}','{4}','{5}')", textBox6.Text, dr["barcode"], dr["location"], dr["user_no"], dr["user_add"], dr["user_name"]));
            }

            DbHelperSQL.ExecuteSql("insert into T_Manage_Task(FID,F_ManageTaskKindIndex,F_RELATIVECONTORLID,FIntoStepOK,FSTARTDEVICE,FREMARK,FSTARTCELL,FENDDEVICE,FENDCELL,FBEGTIME,FPALLETBARCODE) values(" +
                hidx + ",4,-1,1," + Convert.ToInt32(cbDeviceName.SelectedValue) + ",'" + (tabControl1.SelectedIndex + 1) + "','" + z.ToString() + "-" + x.ToString() + "-" + y.ToString()
                + "'," + Convert.ToInt32(cbDeviceName.SelectedValue) + ",'" + z1.ToString() + "-" + x1.ToString() + "-" + y1.ToString() + "','" + dtime + "','" + textBox6.Text + "')");

            if (rehidx > 0)
            {
                DbHelperSQL.ExecuteSql("update T_Manage_Task set F_RELATIVECONTORLID=" + rehidx + " where F_ManageTaskKindIndex=4 and FID=" + hidx);
                DbHelperSQL.ExecuteSql("update T_Manage_Task set F_RELATIVECONTORLID=" + hidx + " where F_ManageTaskKindIndex=4 and FID=" + rehidx);
            }
            RecordMaxHandTaskFID(hidx);
        }

        private int GetRouteIDsub(int device)
        {
            DataView dv = DbHelperSQL.Query("SELECT F_RouteIDSub, F_DeviceIndex, F_RouteID FROM T_Base_Route_Device where F_DeviceIndex=" + device + "").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                return Convert.ToInt32(dv[0]["F_RouteIDSub"]);
            }
            else
            {
                return -1;
            }
        }

        private int GetManageHandIdx()
        {
            DataSet ds = DbHelperSQL.Query("SELECT F_ManageTaskKindIndex, max(FID) as mFID FROM T_Manage_Task Where F_ManageTaskKindIndex=4 group by F_ManageTaskKindIndex");
            if (ds.Tables[0].DefaultView.Count > 0)
            {
                return (Convert.ToInt32(ds.Tables[0].DefaultView[0]["mFID"]) + 1);
            }
            else
            {
                DataSet dss = DbHelperSQL.Query("SELECT F_ManageTaskIndex FROM T_Base_Manage_Task_Index_Hand_Task");
                if (dss.Tables[0].DefaultView.Count > 0)
                {
                    if ((Convert.ToInt32(dss.Tables[0].DefaultView[0]["F_ManageTaskIndex"]) + 1) >= 29998)
                    {
                        return 20001;
                    }
                    else
                    {
                        return (Convert.ToInt32(dss.Tables[0].DefaultView[0]["F_ManageTaskIndex"]) + 1);
                    }
                }
                else
                {
                    return 20001;
                }
            }
        }

        private void RecordMaxHandTaskFID(int fid)
        {
            DataSet ds = DbHelperSQL.Query("select F_ManageTaskIndex from T_Base_Manage_Task_Index_Hand_Task");
            DataView dv = ds.Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                if (fid == 29998)
                {
                    DbHelperSQL.ExecuteSql("UPDATE T_Base_Manage_Task_Index_Hand_Task SET F_ManageTaskIndex =20001");
                    return;
                }
                if (fid > Convert.ToInt32(dv[0]["F_ManageTaskIndex"]))
                {
                    DbHelperSQL.ExecuteSql("UPDATE T_Base_Manage_Task_Index_Hand_Task SET F_ManageTaskIndex =" + fid);
                    return;
                }
            }
            else
            {
                DbHelperSQL.ExecuteSql("INSERT INTO T_Base_Manage_Task_Index_Hand_Task (F_ManageTaskIndex)VALUES (" + fid + ")");
                return;
            }
        }

        private Button button = new Button();

        private void btn_Click(object sender, EventArgs e)
        {
            button = (Button)sender;

            if (button.BackColor == SystemColors.ControlLight)
            {
                textBox5.Text = button.Text;
            }
            else
            {
                DataRow dr = dataSet1.Tables[0].Select("LOCATION=" + button.Text)[0];
                dataSet1.Tables[0].Rows.Remove(dr);
                button.BackColor = SystemColors.ControlLight;
            }
            compute();
        }

        private void compute()
        {
            int H, L;
            if (tabControl1.SelectedIndex == 0)
            {
                L = I(D1) + I(D2) * 2 + I(D3) * 4 + I(D4) * 8 + I(D5) * 16 + I(D6) * 32 + I(D7) * 64 + I(D8) * 128;
                H = I(D9) + I(D10) * 2 + I(D11) * 4 + I(D12) * 8;
            }
            else
            {
                L = I(S1) + I(S2) * 2 + I(S3) * 4 + I(S4) * 8;
                H = 0;
            }
            tbDEC.Text = H + " " + L;
            tbNUM.Text = (H * 256 + L).ToString();
            tbBIN.Text = Convert.ToString(H, 2).PadLeft(8, '0') + " " + Convert.ToString(L, 2).PadLeft(8, '0');
        }

        private int I(Button button)
        {
            if (button.BackColor == SystemColors.ControlLight)
                return 0;
            else
                return 1;
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            Clear();
            compute();
        }

        private void Clear()
        {
            D1.BackColor = D2.BackColor = D3.BackColor = D4.BackColor
                = D5.BackColor = D6.BackColor = D7.BackColor = D8.BackColor
                = D9.BackColor = D10.BackColor = D11.BackColor = D12.BackColor
                = S1.BackColor = S2.BackColor = S3.BackColor = S4.BackColor = SystemColors.ControlLight;
            dataSet1.Tables[0].Clear();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Clear();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (textBox5.Text == "")
                return;

            DataRow dr = dataSet1.Tables[0].NewRow();

            dr["LOCATION"] = textBox5.Text;
            dr["BARCODE"] = textBox1.Text;
            dr["USER_NO"] = textBox2.Text;
            dr["USER_ADD"] = textBox3.Text;
            dr["USER_NAME"] = textBox4.Text;

            dataSet1.Tables[0].Rows.Add(dr);

            button.BackColor = SystemColors.ActiveCaption;

            compute();

            textBox5.Text = "";
        }

        private void button4_Click(object sender, EventArgs e)
        {
            string user_no = textBox2.Text;
            string user_add = textBox3.Text;

            #region 绘制图片

            double dpmm = 11.811;
            int height = (int)(20 * dpmm);
            int width = (int)(35 * dpmm);

            Bitmap image = new Bitmap(width, height);

            Graphics g = Graphics.FromImage(image);
            g.Clear(Color.LightGray);
            int y = 0;

            Font f0 = new Font("宋体", 24, FontStyle.Bold);
            Bitmap imgA = BarcodeUtils.CreateImage(user_no, f0);
            g.DrawImage(imgA, 0, 0);
            y = imgA.Height;

            Font f1 = new Font("宋体", 24, FontStyle.Bold);
            string ss = "";
            int sscount = 0;
            int rowcount = 0;
            for (int i = 0; i < user_add.Length; i++)
            {
                char c = user_add[i];
                byte[] bytes = System.Text.Encoding.Unicode.GetBytes(c.ToString());

                int H = Convert.ToInt32(bytes[1]);
                int L = Convert.ToInt32(bytes[0]);

                // 得到unicode编码
                int value = H * 256 + L;

                // 是全角
                if (value >= 12288 && value <= 65374)
                {
                    sscount = sscount + 2;
                    ss += c;
                }
                else
                {
                    sscount = sscount + 1;
                    ss += c;
                }

                if (sscount > 22 || (i + 1) == user_add.Length)
                {
                    Bitmap img = BarcodeUtils.CreateImage(ss, f1);
                    g.DrawImage(img, 0, y);
                    y += img.Height;
                    ss = "";
                    sscount = 0;
                    rowcount++;
                }
            }
            image.RotateFlip(RotateFlipType.Rotate270FlipNone);

            #endregion 绘制图片

            StringBuilder ZPL = new StringBuilder("");
            ZPL.Append("\r\n");

            ZPL.Append(BarcodeUtils.CreateBmpZLP(image, BarcodeUtils.ConvertImageToCode(image), "100"));

            //加入相关设置
            ZPL.Append("^XA");
            ZPL.Append("\r\n");
            ZPL.Append("^MMP");
            ZPL.Append("\r\n");
            //ZPL.Append("^POI");
            //ZPL.Append("\r\n");

            //开始打印
            ZPL.Append("^FT0,0^XG100.GRF,1,1^FS");
            ZPL.Append("\r\n");

            //释放资源
            ZPL.Append("^PQ1,0,1,Y^XZ");
            ZPL.Append("\r\n");

            ZPL.Append("^XA^ID100.GRF^FS^XZ");
            ZPL.Append("\r\n");

            pictureBox1.Image = image;
            textBox7.Text = ZPL.ToString();
            image.Save("d:\\a.bmp");
        }
    }
}