using System;
using System.Data;
using System.Text;
using System.Windows.Forms;
using UAS_MES_NEW.CustomControl.TextBoxWithIcon;
using UAS_MES_NEW.DataOperate;
using UAS_MES_NEW.Entity;
using UAS_MES_NEW.PublicMethod;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using UAS_MES_NEW.PublicForm;

namespace UAS_MES_NEW.Make
{
    public partial class Make_PreFeedingCollection : Form
    {
        //工艺路线编号
        string ErrorMessage = "";

        List<string> TSN = new List<string>();

        Dictionary<string, string> CheckBarcode = new Dictionary<string, string>();

        //用于提醒的序列B
        string[] RemainList = new string[0];
        //提醒序列的索引
        int RemainIndex = 0;

        DataHelper dh;
        LogStringBuilder sql = new LogStringBuilder();
        DataTable DBFind;
        //保存ListB中的数据
        DataTable dt1;

        AutoSizeFormClass asc = new AutoSizeFormClass();

        List<string> CollectData = new List<string>();

        List<string> CollectDataSonCode = new List<string>();

        List<string> SPID = new List<string>();

        int CollectCount = 0;

        public Make_PreFeedingCollection()
        {
            InitializeComponent();
        }

        private void Make_FeedingCollection_Load(object sender, EventArgs e)
        {
            asc.controllInitializeSize(this);
            string cachenum = BaseUtil.GetCacheData("ProdCodeNum").ToString();
            ProdNum.Value = decimal.Parse(cachenum == "" ? "1" : cachenum);
            LockMakeCode.GetMakeCodeCtl(ma_code);
            ma_code.SetLockCheckBox(LockMakeCode);
            //工单号放大镜配置
            ma_code.TableName = "make left join product on ma_prodcode=pr_code";
            ma_code.SelectField = "ma_code # 工单号,ma_prodcode # 产品编号,ma_qty # 工单数量,ma_craftcode # 途程编号,pr_spec # 产品名称,ma_bomversion # Bom版本,ma_softversion # 软件版本,ma_ecncode # ECN号";
            ma_code.FormName = Name;
            ma_code.DBTitle = "工单查询";
            ma_code.SetValueField = new string[] { "ma_code", "ma_prodcode", "ma_qty", "pr_spec", "ma_craftcode", "ma_bomversion", "ma_softversion", "ma_ecncode" };
            ma_code.Condition = "ma_statuscode='STARTED'";
            ma_code.DbChange += Ma_code_DBChange;
            code.Focus();
            dh = SystemInf.dh;
        }

        private void Ma_code_DBChange(object sender, EventArgs e)
        {
            DBFind = ma_code.ReturnData;
            BaseUtil.SetFormValue(this.Controls, DBFind);
            GetItem();
        }

        private void Make_FeedingCollection_SizeChanged(object sender, EventArgs e)
        {
            asc.controlAutoSize(this);
        }

        private void Clean_Click(object sender, EventArgs e)
        {
            OperateResult.Clear();
        }

        private void Confirm_Click(object sender, EventArgs e)
        {
            KeyEventArgs e2 = new KeyEventArgs(Keys.Enter);
            code_KeyDown(sender, e2);
        }

        bool GetMainCode = false;

        private void code_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (LogicHandler.CheckStepAttribute(Tag.ToString(), User.UserSourceCode, out ErrorMessage))
                {
                    if (Loading.Checked)
                    {
                        string Count = dh.getFieldDataByCondition("BEFOREHANDPROCESS", "count(distinct bhp_maincode)", "bhp_makecode='" + ma_code.Text + "'").ToString();
                        mcd_inqty1.Text = Count;
                        if (int.Parse(ma_qty.Text) + 1 < int.Parse(Count))
                        {
                            OperateResult.AppendText(">>预加工数量" + Count + "已达到工单数量" + ma_qty.Text + "\n", Color.Red);
                            return;
                        }
                        if (code.Text.Replace(" ", "") == "")
                        {
                            OperateResult.AppendText(">>采集数据不可为空\n", Color.Red);
                            return;
                        }
                        else
                        {
                            if (mainbarcode.Text == "")
                            {
                                mainbarcode.Text = code.Text;
                                GetMainCode = true;
                                OperateResult.AppendText(">> 获取条码" + code.Text + "成功\n");
                                GetItem();
                            }
                            else
                            {
                                GetMainCode = false;
                            }
                            string sp_soncode = "";
                            string sp_fsoncode = "";
                            string sp_prefix = "";
                            string sp_regex = "";
                            string length = "";
                            string sp_id = "";
                            string sp_ifrepeat = "";
                            string sp_ifforsn = "";
                            string sp_barcoderule = "";
                            string sp_checkbarcode = "";
                            string sp_checksalecode = "";
                            bool needload = false;
                            for (int i = 0; i < LabelDataGridView.Rows.Count; i++)
                            {
                                object value = LabelDataGridView.Rows[i].Cells["BarCode"].Value;
                                if (value == null || (value != null && value.ToString() == ""))
                                {
                                    RemainIndex = i;
                                    needload = true;
                                    sp_soncode = dt1.Rows[i]["sp_soncode"].ToString();
                                    sp_fsoncode = dt1.Rows[i]["sp_fsoncode"].ToString();
                                    sp_prefix = dt1.Rows[i]["sp_prefix"].ToString();
                                    sp_regex = dt1.Rows[i]["sp_regex"].ToString();
                                    length = dt1.Rows[i]["sp_length"].ToString();
                                    sp_id = dt1.Rows[i]["sp_id"].ToString();
                                    sp_ifrepeat = dt1.Rows[i]["sp_ifrepeat"].ToString();
                                    sp_ifforsn = dt1.Rows[i]["sp_ifforsn"].ToString();
                                    sp_barcoderule = dt1.Rows[i]["sp_barcoderule"].ToString();
                                    sp_checkbarcode = dt1.Rows[i]["sp_checkbarcode"].ToString();
                                    sp_checksalecode = dt1.Rows[i]["sp_checksalecode"].ToString();
                                    break;
                                }
                            }
                            if (GetMainCode && RemainIndex != 0)
                            {
                                code.Clear();
                                return;
                            }
                            if (!needload)
                            {
                                OperateResult.AppendText(">>没有需要采集的物料,请重新采集\n", Color.Red, code);
                                mainbarcode.Clear();
                                SetCheck set = new SetCheck("NG", Color.Red);
                                BaseUtil.SetFormCenter(set);
                                set.ShowDialog();
                                return;
                            }
                            if (LogicHandler.CheckSNBeforeLoad(ma_code.Text, code.Text, sp_fsoncode, sp_soncode, sp_barcoderule, sp_prefix, length, sp_ifrepeat, sp_checksalecode, out ErrorMessage))
                            {
                                //查询条码是否存在预加工列表
                                if (dh.CheckExist("BEFOREHANDPROCESS", "bhp_barcode='" + code.Text + "'"))
                                {
                                    OperateResult.AppendText(">> 条码" + code.Text + "已经上料\n", Color.Red, code);
                                    return;
                                }
                                //获取的主条码和绑定条码必须一致
                                if (RemainIndex == 0)
                                {
                                    if (code.Text != mainbarcode.Text)
                                    {
                                        OperateResult.AppendText(">>获取的主条码" + mainbarcode.Text + "和" + code.Text + "不一致\n", Color.Red, code);
                                        SetCheck set = new SetCheck("NG", Color.Red);
                                        BaseUtil.SetFormCenter(set);
                                        set.ShowDialog();
                                        return;
                                    }
                                }
                                LabelDataGridView.Rows[RemainIndex].Cells["BarCode"].Value = code.Text;
                                string maincode = LabelDataGridView.Rows[0].Cells["BarCode"].Value.ToString();
                                sql.Clear();
                                sql.Append("insert into BEFOREHANDPROCESS(bhp_id,bhp_maincode,bhp_barcode,bhp_prodcode,bhp_indate,bhp_inman,bhp_makecode)");
                                sql.Append("values(BEFOREHANDPROCESS_seq.nextval,'" + maincode + "','" + code.Text + "','" + sp_fsoncode + "',sysdate,'" + User.UserCode + "','" + ma_code.Text + "')");
                                dh.ExecuteSql(sql.GetString(), "insert");
                                OperateResult.AppendText(">> 条码" + code.Text + "上料成功\n", Color.Green, code);
                                code.Clear();
                                CollectCount = CollectCount + 1;
                                if (CollectCount == ProdNum.Value || RemainIndex == LabelDataGridView.Rows.Count - 1)
                                {
                                    LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, ma_code.Text, User.UserLineCode, User.UserSourceCode, "预加工采集", "上料物料" + mainbarcode.Text, "", "");
                                    mainbarcode.Text = "";
                                    CollectCount = 0;
                                    SetCheck set = new SetCheck("OK", Color.Green);
                                    BaseUtil.SetFormCenter(set);
                                    set.ShowDialog();
                                }
                            }
                            else
                            {
                                OperateResult.AppendText(">>" + ErrorMessage + "\n", Color.Red, code);
                                SetCheck set = new SetCheck("NG", Color.Red);
                                BaseUtil.SetFormCenter(set);
                                set.ShowDialog();
                            }
                        }
                    }
                    else if (UnLoading.Checked)
                    {
                        mainbarcode.Text = code.Text;
                        GetItem();
                        bool finddata = false;
                        for (int i = 0; i < LabelDataGridView.Rows.Count; i++)
                        {
                            object value = LabelDataGridView.Rows[i].Cells["BarCode"].Value;
                            if (value != null && value.ToString() != "")
                            {
                                if (code.Text == value.ToString())
                                {
                                    finddata = true;
                                    //拆解主物料,全部解绑
                                    if (i == 0)
                                    {
                                        string yes_or_no = MessageBox.Show(this.ParentForm, "是否解绑所有物料", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
                                        if (yes_or_no == "Yes")
                                        {
                                            sql.Clear();
                                            sql.Append("delete from BEFOREHANDPROCESS where bhp_maincode='" + code.Text + "'");
                                            dh.ExecuteSql(sql.GetString(), "delete");
                                            mainbarcode.Text = "";
                                            GetItem();
                                            OperateResult.AppendText(">> 条码" + code.Text + "下料成功\n", Color.Green, code);
                                        }
                                    }
                                    else
                                    {
                                        sql.Clear();
                                        sql.Append("delete from BEFOREHANDPROCESS where bhp_barcode='" + code.Text + "'");
                                        dh.ExecuteSql(sql.GetString(), "delete");
                                        LabelDataGridView.Rows[i].Cells["BarCode"].Value = "";
                                        OperateResult.AppendText(">> 条码" + code.Text + "下料成功\n", Color.Green, code);
                                    }
                                }
                            }
                        }
                        if (!finddata)
                        {
                            OperateResult.AppendText(">>条码" + code.Text + "未上料\n", Color.Red, code);
                        }
                    }
                }
                else OperateResult.AppendText(">>" + ErrorMessage + "\n", Color.Red, code);
            }
        }

        private void SaveData()
        {
            List<string> pr_code = new List<string>();
            List<string> barcode = new List<string>();
        }

        private void GetItem()
        {
            //单独用一个DataTable存储一个
            dt1 = new DataTable();
            if (mainbarcode.Text == "")
            {
                sql.Clear();
                sql.Append("select max(sp_id)sp_id,max(sp_detno)sp_detno,min(sp_ifrepeat)sp_ifrepeat,max(sp_checkbarcode)sp_checkbarcode,min(sp_checksalecode)sp_checksalecode,");
                sql.Append("sp_fsoncode,max(sp_barcoderule)sp_barcoderule,wm_concat(sp_soncode) sp_soncode,max(sp_ifuseregex)sp_ifuseregex,max(sp_ifforsn)");
                sql.Append("sp_ifforsn,max(sp_length)sp_length,max(sp_type)sp_type,replace(wm_concat(sp_prefix),',','|')sp_prefix,max(sp_regex)");
                sql.Append("sp_regex,max(substr(pr_spec,0,20))pr_detail from stepproduct left join stepbom on sb_bomversion=sp_bomversion and sp_craftcode=sb_craftcode ");
                sql.Append("left join product on pr_code=sp_fsoncode  where ");
                sql.Append("sp_mothercode ='" + ma_prodcode.Text + "' and sp_craftcode='" + ma_craftcode.Text + "' and  sp_stepcode='" + User.CurrentStepCode + "' and sp_tracekind=1 and sp_ifbeforhandle=-1  group by sp_fsoncode order by SP_DETNO asc");
            }
            else
            {
                sql.Clear();
                sql.Append("select max(sp_id)sp_id,max(sp_detno)sp_detno,min(sp_ifrepeat)sp_ifrepeat,max(sp_checkbarcode)sp_checkbarcode,min(sp_checksalecode)sp_checksalecode,");
                sql.Append("sp_fsoncode,max(sp_barcoderule)sp_barcoderule,wm_concat(sp_soncode) sp_soncode,max(sp_ifuseregex)sp_ifuseregex,max(sp_ifforsn)");
                sql.Append("sp_ifforsn,max(sp_length)sp_length,max(sp_type)sp_type,replace(wm_concat(sp_prefix),',','|')sp_prefix,max(sp_regex)");
                sql.Append("sp_regex,max(substr(pr_spec,0,20))pr_detail,max(bhp_barcode)bhp_barcode from stepproduct left join stepbom on sb_bomversion=sp_bomversion and sp_craftcode=sb_craftcode  ");
                sql.Append("left join product on pr_code=sp_fsoncode left join (select * from BEFOREHANDPROCESS where bhp_maincode='" + mainbarcode.Text + "') on bhp_prodcode=sp_fsoncode where ");
                sql.Append("sp_mothercode ='" + ma_prodcode.Text + "' and sp_craftcode='" + ma_craftcode.Text + "' and sp_stepcode='" + User.CurrentStepCode + "' and sp_tracekind=1 and sp_ifbeforhandle=-1 and (bhp_maincode='" + mainbarcode.Text + "' or bhp_maincode is null)  group by sp_fsoncode order by SP_DETNO asc");
            }
            dt1 = (DataTable)dh.ExecuteSql(sql.GetString(), "select");
            BaseUtil.FillDgvWithDataTable(LabelDataGridView, dt1);
            string Count = dh.getFieldDataByCondition("BEFOREHANDPROCESS", "count(distinct bhp_maincode)", "bhp_makecode='" + ma_code.Text + "'").ToString();
            mcd_inqty1.Text = Count;
        }

        private void ma_code_UserControlTextChanged(object sender, EventArgs e)
        {
            if (ma_code.Text.Length > 5)
            {
                string ErrMessage = "";
                if (LogicHandler.CheckMakeStatus(ma_code.Text, out ErrMessage))
                {
                    string Count = dh.getFieldDataByCondition("BEFOREHANDPROCESS", "count(distinct bhp_maincode)", "bhp_makecode='" + ma_code.Text + "'").ToString();
                    mcd_inqty1.Text = Count;
                    mcd_remainqty.Text = "";
                    sql.Clear();
                    sql.Append("select mcd_inqty,ma_qty-mcd_inqty mcd_remainqty ");
                    sql.Append("from make left join makecraftdetail on mcd_macode=ma_code where ");
                    sql.Append("ma_code='" + ma_code.Text + "' and mcd_stepcode='" + User.CurrentStepCode + "'");
                    DataTable dt = (DataTable)dh.ExecuteSql(sql.GetString(), "select");
                    if (dt.Rows.Count > 0)
                        BaseUtil.SetFormValue(Controls, dt);
                }
            }
        }

        private void ClearSn_code_Click(object sender, EventArgs e)
        {
            mainbarcode.Clear();
            code.Clear();
            if (dt1 != null)
                BaseUtil.CleanDataTableData(dt1);
            RemainIndex = 0;
            BaseUtil.CleanDGVData(LabelDataGridView);
            OperateResult.AppendText(">>请采集条码\n", Color.Black);
            GetItem();
        }

        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            BaseUtil.SetCacheData("ProdCodeNum", ProdNum.Value.ToString());
        }
    }
}