using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using foda;
using FacOneZPStation.WebReference;
using MESClassLibrary.BLL.BasicInfo;
using MESClassLibrary.BLL.Log;
using MESClassLibrary.BLL.ZPPlan;
using MESClassLibrary.Model;

namespace FacOneZPStation
{
    public partial class FrmChooseDamnPosition : Form
    {
        public FrmChooseDamnPosition()
        {
            InitializeComponent();
        }

        private static string position = "", reason = "";
        int count = 0; //缺陷图选择个数

        private void btnBack_Click(object sender, EventArgs e)
        {
            position = "";
            reason = "";
            count = 0;
            this.Close();
        }

        private void FrmChooseDamnPosition_Load(object sender, EventArgs e)
        {
            //try
            //{
                int row = 0, col = 0;
                string picture = "";
                string LineID = "";
                ProductBLL bll = new ProductBLL();

                #region 查找零件号查找图片

                DataTable dt = bll.SearchInfoByPartNo(FrmMain.PartNo);

                if (dt != null && dt.Rows.Count > 0)
                {
                    row = Convert.ToInt32(dt.Rows[0]["Rows"].ToString());
                    col = Convert.ToInt32(dt.Rows[0]["Cols"].ToString());
                    picture = dt.Rows[0]["PicturePath"].ToString();
                }

                #endregion

                #region Load PictureBox
                try
                {
                    if (picture != "" && picture != null)
                    {
                        if (!File.Exists(System.IO.Directory.GetCurrentDirectory() + @"\" + picture))
                        {
                            Ping p1 = new Ping();
                            bool status = false;

                            string strImageURL = "http://10.60.101.59:8001/PDF/" + picture;

                            System.Net.WebClient webClient = new System.Net.WebClient();
                            webClient.DownloadFile(strImageURL, Directory.GetCurrentDirectory() + @"\" + picture);
                        }

                        FileStream fs = new FileStream(System.Environment.CurrentDirectory + "\\" + picture,
                            FileMode.Open,
                            FileAccess.Read); //获取图片文件流
                        Image img = Image.FromStream(fs); // 文件流转换成Image格式
                        pictureBox1.Image = img; //给 图片框设置要显示的图片
                        fs.Close(); // 关闭流,释放图片资源
                    }

                }
                catch (Exception ex)
                {
                    LogErrBLL.AddInfo(ex.ToString(),MethodBase.GetCurrentMethod());
                }
                

                #endregion

                #region 缺陷图划分区域

                Label[] lb = new Label[5];
                string[] str =
                    {
                        "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
                        "U", "V", "W", "X", "Y", "Z"
                    };

                for (int i = 0; i < col; i++)
                {
                    for (int j = 0; j < row; j++)
                    {
                        lb[i] = new Label();
                        lb[i].Text = str[i + col * j].ToString();
                        lb[i].Font = new Font(lb[i].Font.FontFamily, 32, FontStyle.Bold);

                        lb[i].Size = new Size(pictureBox1.Width / col, pictureBox1.Height / row);
                        lb[i].Location = new Point(0 + i * lb[i].Size.Width, 0 + j * lb[i].Size.Height);
                        lb[i].BorderStyle = BorderStyle.FixedSingle;
                        lb[i].BackColor = Color.Transparent;
                        lb[i].TextAlign = ContentAlignment.MiddleCenter;
                        pictureBox1.Controls.Add(lb[i]);

                        lb[i].Click += new EventHandler(lblRoom_Click);
                    }
                }

                #endregion

                #region 缺陷原因

                StationBLL sbll = new StationBLL();
                DataTable sdt = sbll.SearchInfoByNo(ConfigurationManager.AppSettings["StationNo"].ToString());
                if (sdt != null && sdt.Rows.Count > 0)
                {
                    LineID = sdt.Rows[0]["LineID"].ToString();
                }

                sdt.Dispose();

                int drow = 0, dcol = 6;

                DefectBLL dbll = new DefectBLL();
                DataTable dt3 = dbll.SearchInfo(LineID);
                if (dt3 != null && dt3.Rows.Count > 0)
                {
                    drow = Convert.ToInt32(Math.Ceiling((double)dt3.Rows.Count / dcol));
                    Label[] dLb = new Label[7];
                    string[] dstr = new string[dt3.Rows.Count];


                    for (int i = 0; i < dt3.Rows.Count; i++)
                    {
                        dstr[i] = dt3.Rows[i]["DefectName"].ToString();
                    }

                    for (int i = 0; i < dcol; i++) //列
                    {
                        for (int j = 0; j < drow; j++) //行
                        {
                            dLb[i] = new Label();
                            if ((i + dcol * j) < dstr.Length)
                            {
                                dLb[i].Text = dstr[i + dcol * j].ToString();
                                dLb[i].Font = new Font(dLb[i].Font.FontFamily, 20, FontStyle.Bold);

                                dLb[i].Size = new Size(130, 50);
                                dLb[i].Location = new Point(20 + i * (dLb[i].Size.Width + 25),
                                    20 + j * (dLb[i].Size.Height + 20));
                                dLb[i].BorderStyle = BorderStyle.FixedSingle;
                                dLb[i].BackColor = Color.Transparent;
                                dLb[i].TextAlign = ContentAlignment.MiddleCenter;
                                panel3.Controls.Add(dLb[i]);
                                dLb[i].Click += new EventHandler(dLbRoom_Click);
                            }
                        }
                    }
                }

                #endregion
            //}
            //catch (Exception ex)
            //{
            //    LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            //}
        }

        /// <summary>
        /// 从远程服务器下载文件到本地
        /// </summary>
        /// <param name="src">下载到本地后的文件路径,包含文件的扩展名</param>
        /// <param name="dst">远程服务器路径(共享文件夹路径)</param>
        /// <param name="fileName">远程服务器(共享文件夹)中的文件名称,包含扩展名</param>
        public static void TransportRemoteToLocal(string src, string dst, string fileName)   //src:下载到本地后的文件路径     dst:远程服务器路径    fileName:远程服务器dst路径下的文件名
        {
            try
            {
                FileStream inFileStream = new FileStream(src, FileMode.Open); //远程服务器文件  此处假定远程服务器共享文件夹下确实包含本文件,否则程序报错

                if (!Directory.Exists(dst))
                {
                    Directory.CreateDirectory(dst);
                }
                dst = dst + fileName;
                FileStream outFileStream = new FileStream(dst, FileMode.OpenOrCreate);   //从远程服务器下载到本地的文件
                byte[] buf = new byte[inFileStream.Length];
                int byteCount;
                while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
                {
                    outFileStream.Write(buf, 0, byteCount);
                }
                inFileStream.Flush();
                inFileStream.Close();
                outFileStream.Flush();
                outFileStream.Close();
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

        void lblRoom_Click(object sender, EventArgs e)
        {
            Label a = (Label)sender;

            if (a.BackColor == Color.Transparent)
            {
                a.BackColor = Color.FromArgb(150, System.Drawing.Color.Chartreuse);
                count++;
            }
            else
            {
                a.BackColor = Color.Transparent;
                count--;
            }

        }


        void dLbRoom_Click(object sender, EventArgs e)
        {

            Label a = (Label)sender;

            string aa = a.Text;
            if (a.BackColor == Color.Transparent)
            {
                a.BackColor = Color.FromArgb(150, Color.Chartreuse);
                reason += a.Text + ";";
            }
            else
            {
                reason = reason.Replace(a.Text + ";", "");
                a.BackColor = Color.Transparent;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                #region 校验是否选择区域和原因

                foreach (Control c in pictureBox1.Controls)
                {
                    Label lab = c as Label;
                    if (lab.BackColor != Color.Transparent)
                    {
                        position += lab.Text + ";";
                    }
                }

                if (position == "")
                {
                    MessageBox.Show("请选择缺陷位置!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (reason == "")
                {
                    MessageBox.Show("请选择缺陷原因!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                #endregion

                #region 存缺陷

                BadZPBLL badbll = new BadZPBLL();
                BadZPModel badmd=new BadZPModel();

                badmd.ID = Guid.NewGuid().ToString();
                badmd.PlanID = FrmMain.planID;
                badmd.BadPosition = position;
                badmd.BadReason = reason;

                badbll.AddInfo(badmd);
                
                #endregion

                #region 减少产量

                ZPRecordBLL bll = new ZPRecordBLL();
                ZPPlanBLL planbll = new ZPPlanBLL();
                ZPRecordModel md = new ZPRecordModel();
                ZPPlanModel zmd = new ZPPlanModel();
                string OneBarCode = "";

                #region 是否有未打印的产品

                DataTable dt1 = bll.SearchPrint(FrmMain.planID);
                if (dt1 != null && dt1.Rows.Count > 0)
                {
                    md.IsOK = 0;
                    md.ID = dt1.Rows[0]["ID"].ToString();
                    OneBarCode = dt1.Rows[0]["OneBarCode"].ToString();
                    bll.UpdateBad(md);

                    zmd.ID = FrmMain.planID;
                    planbll.updateBad(zmd);

                    #region 调用wms接口

                    LogHelper.WriteSysLogBase("条码号:" + OneBarCode + "工位:" + ConfigurationManager.AppSettings["StationNo"] + ",调用WMS装配合格入库接口", MethodBase.GetCurrentMethod().Name);
                    WMSWebService ws = new WMSWebService();
                    string lineID = "";

                    #region 根据工位编号查询产线ID

                    StationBLL sbll=new StationBLL();
                    DataTable sdt = sbll.SearchInfoByNo(ConfigurationManager.AppSettings["StationNo"]);
                    if (sdt != null && sdt.Rows.Count > 0)
                    {
                        lineID = sdt.Rows[0]["LineName"].ToString();
                    }

                    #endregion

                    ws.Url = ConfigurationManager.AppSettings["WMSWebServiceURL"];
                    //bool aa = ws.WMSInterfaceStockIn(onebarCode, partNo, DateTime.Now.ToString("yyyyMMdd"), 1, lineID);
                    //if (!aa)
                    //{
                    //    DialogResult r = MessageBox.Show("调用WMS接口失败,是否重新调用!", "提示", MessageBoxButtons.YesNo);
                    //    if (r == DialogResult.Yes)
                    //    {
                    //        for (int i = 0; i < 3; i++)
                    //        {
                    //            if (ws.WMSInterfaceStockIn(onebarCode, partNo, DateTime.Now.ToString("yyyyMMdd"), 1, lineID))
                    //            {
                    //                break;
                    //            }
                    //        }
                    //    }
                    //}

                    #endregion
                }
                else
                {
                    MessageBox.Show("当前计划没有零件!", "提示", MessageBoxButtons.OK);
                    return;
                }

                #endregion

                #endregion


                position = "";
                reason = "";
                count = 0;
                this.Close();
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }
    }
}