using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;

namespace CheckSheet.checkinput
{
    public partial class _4M1E_input_check : System.Web.UI.Page
    {

        [System.Web.Services.WebMethod]
        public static string getsubdata(string id)
        {

            DataSet ds = new DataSet();
            string cmdhd = string.Empty;
            using (FcSql.Function fc = new FcSql.Function())
            {
                string str_getinput = string.Format("select itemno,itemname from InspectionItem Where item_main_no='{0}' and  inspection_type='4' order by convert(float,itemno) ", id);
                ds = fc.SQL_DataSet(str_getinput);
                fc.closeconnection();

            }
            return ds.GetXml();
        }

        [System.Web.Services.WebMethod]
        public static string getdata(string parahd)
        {

            DataSet ds = new DataSet();
            string cmdhd = string.Empty;
            string inspidid = string.Empty;
            string userapprove = string.Empty;
            using (FcSql.Function fc = new FcSql.Function())
            {
                byte[] datahd = System.Convert.FromBase64String(parahd);
                string base64Decoded = System.Text.ASCIIEncoding.UTF8.GetString(datahd);
                string[] strmt = base64Decoded.Split('|');
                try
                {
                    string partnumber = strmt[0].ToString();
                    string typeno = strmt[1].ToString();
                    string typename = strmt[2].ToString();

                    string str_getinput = string.Format("select inspidid, insp_piz,notice, detailchangepoint, result1, action1, result2, action2 from InspectionInput Where partnumber='{0}' and itemno='{1}' and inspectiontype='4' and itemname='{2}'  and inspectiondate between '{3} 08:00:00' and '{4} 07:59:59' ", partnumber, typeno, typename, DateTime.Now.ToString("yyyy-MM-dd", new CultureInfo("en-US")), DateTime.Now.AddDays(1).ToString("yyyy-MM-dd", new CultureInfo("en-US")));
                    ds = fc.SQL_DataSet(str_getinput);
                    fc.closeconnection();

                }
                catch { }
            }
            return ds.GetXml();
        }

        [System.Web.Services.WebMethod]
        public static string savedetail(string parahd)
        {


         


            string cmdhd = string.Empty;
            string inspidid = string.Empty;
            string userapprove = string.Empty;
            using (FcSql.Function fc = new FcSql.Function())
            {
                byte[] datahd = System.Convert.FromBase64String(parahd);
                string base64Decoded = System.Text.ASCIIEncoding.UTF8.GetString(datahd);
                string[] strmt = base64Decoded.Split('|');
                try
                {
                    string partnumber = strmt[1].ToString();
                    string typeno = strmt[2].ToString();
                    string typename = strmt[3].ToString();
                    string model = strmt[4].ToString();
                    string itemno = strmt[5].ToString();
                    string itemname = strmt[6].ToString();
                    string result = strmt[7].ToString();
                    string user = strmt[8].ToString();

                    string lamp=string.Empty;
                    string linename=string.Empty;

                    string strlamp = string.Format("select lamp,linename from LineGroupMaster where model = '{0}' and partnumber='{1}'", model, partnumber);
                    DataTable dtlamp = fc.SQL_DataTable(strlamp);
                    if(dtlamp.Rows.Count>0)
                    {
                        lamp = dtlamp.Rows[0]["lamp"].ToString();
                        linename = dtlamp.Rows[0]["linename"].ToString();

                    }
                 
                    string chkid = string.Format("select inspidid from InspectionInput Where partnumber='{0}' and equid='0' and   itemno='{1}'  and inspectiontype='4' and inspectiondate between '{2} 08:00:00' and '{3} 07:59:59' ", partnumber, itemno, DateTime.Now.ToString("yyyy-MM-dd", new CultureInfo("en-US")),DateTime.Now.AddDays(1).ToString("yyyy-MM-dd", new CultureInfo("en-US")));
                    DataTable dtchkid = fc.SQL_DataTable(chkid.ToString());
                    if (dtchkid.Rows.Count > 0)
                    {
                        inspidid = dtchkid.Rows[0]["inspidid"].ToString();

                    }

                    string docno = lamp + "-" + linename + "-" + model + "-" +  DateTime.Now.ToString("yyyy-MM-dd", new CultureInfo("en-US"));


                    if (inspidid.Length == 0)
                    {

                        string _pv = string.Empty;
                        string _id = string.Empty;
                        string _q = string.Format(" select max(convert(real,inspidid)) as id from InspectionInput ");
                        DataTable dtgenid = fc.SQL_DataTable(_q.ToString());
                        if (dtgenid.Rows.Count == 0)
                        {
                            _id = "1";
                        }
                        else
                        {
                            foreach (DataRow dr in dtgenid.Rows)
                            {
                                if (dr[0].ToString() == "")
                                {
                                    _id = "1";
                                }
                                else
                                {
                                    _id = (int.Parse(dr[0].ToString()) + 1).ToString();
                                }
                            }
                        }

                        inspidid = _id;


                    }



                    string crdate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", new CultureInfo("en-US"));


                    string shift_id = string.Empty;
                    string shift_name = string.Empty;

                    string str_shift = string.Format("select  shift_id,shift_name from Work_shift as a inner join LineGroupMaster as b on a.linegroupid=b.linegroupid  Where b.lamp='{0}' and b.model='{1}' and b.linename='{2}' 	and '{3}' between shift_timestart and shift_timeend",lamp,model,linename, DateTime.Now.ToString("HH:mm:ss", new CultureInfo("en-US")));
                    DataTable dtshift = fc.SQL_DataTable(str_shift);
                    if (dtshift.Rows.Count > 0)
                    {
                        shift_id = dtshift.Rows[0]["shift_id"].ToString();
                        shift_name = dtshift.Rows[0]["shift_name"].ToString();

                    }
                    else
                    {
                        shift_id = "2";
                        shift_name = "Night";

                    }

                    if (shift_id.Length == 0)
                    {
                        shift_id = "1";
                        shift_name = "Day";

                    }

                    string equid = "0";
                    string inspectid = string.Empty;
                    string str_inspect = string.Format("select inspectid,equid from InspectionItem  Where itemno='{0}' and inspectiontype='4' ", itemno);
                    DataTable dtinspect = fc.SQL_DataTable(str_inspect);
                    if (dtinspect.Rows.Count > 0)
                    {
                        inspectid = dtinspect.Rows[0]["inspectid"].ToString();
                        equid = dtinspect.Rows[0]["equid"].ToString();

                    }

                    string inspection_date = string.Empty;
                    int chktime = DateTime.Now.Hour;
                    if (chktime >= 0 && chktime < 8)
                    {
                        inspection_date = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd", new CultureInfo("en-US")) + " " + DateTime.Now.ToString("HH:mm:ss", new CultureInfo("en-US"));



                    }
                    else
                    {


                        inspection_date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", new CultureInfo("en-US"));



                    }


                    string inst_mt = string.Format(" insert into InspectionInput (inspidid,equid,inspectid,itemno,itemname,partnumber, inspectiondate, inspectiontype,resultstatus, flagdel, create_user, create_datetime,insp_status,shift_id,shift_name,idrefno) VALUES ('" + inspidid + "','" + equid + "','" + inspectid + "', '" + itemno + "','" + itemname + "','" + partnumber + "','" + inspection_date + "','4','" + result + "',0,'" + user + "','" + crdate + "','W'," + shift_id + ",'" + shift_name + "','"+docno+"')");
                    string up_mt = string.Format(" update InspectionInput SET equid='" + equid + "',inspectid='" + inspectid + "',itemno='" + itemno + "',itemname='" + itemname + "', partnumber= '" + partnumber + "',inspectiondate= '" + inspection_date + "',inspectiontype= '4',resultstatus= '" + result + "',flagdel=0,Update_user= '" + user + "',Update_Datetime= '" + crdate + "',insp_status='W',shift_id=" + shift_id + ",shift_name='" + shift_name + "',idrefno='"+docno+"' Where inspidid= '" + inspidid + "' ");




                    cmdhd = fc.ExecSQLStatement(inst_mt.ToString());
                    if (cmdhd.ToLower().IndexOf("duplicate") != -1)
                    {
                        cmdhd = fc.ExecSQLStatement(up_mt.ToString());
                    }
                    fc.closeconnection();

                }
                catch { };

            }

            //string cmdsendmail = string.Empty;
            //clsControlUI.sendemail("1", "Scrap document waiting for approval.", userapprove);

            //cmdhd = inspidid + "|" + cmdhd;

            return cmdhd;


        }


        [System.Web.Services.WebMethod]
        public static string save(string parahd)
        {


            string cmdhd = string.Empty;
            string inspidid = string.Empty;

            using (FcSql.Function fc = new FcSql.Function())
            {
                byte[] datahd = System.Convert.FromBase64String(parahd);
                string base64Decoded = System.Text.ASCIIEncoding.UTF8.GetString(datahd);
                string[] strmt = base64Decoded.Split('|');
                try
                {


           


                    string partnumber = strmt[1].ToString();
                    string typeno = strmt[2].ToString();
                    string typename = strmt[3].ToString();
                    string detail = strmt[4].ToString();
                    string type = strmt[5].ToString();
                    string result1 = strmt[6].ToString();
                    string case1 = strmt[7].ToString();
                    string result2 = strmt[8].ToString();
                    string case2 = strmt[9].ToString();
                    string notice = strmt[10].ToString();
                    string user = strmt[11].ToString();
                    string piz = strmt[12].ToString();
                    string lotno = strmt[13].ToString();
                    string orderqty = strmt[14].ToString();
                    string wasteqty = strmt[15].ToString();


                    string chkid = string.Format("select inspidid from InspectionInput Where partnumber='{0}' and itemno='{1}' and inspectiontype='4' and itemname='{2}' and inspectiondate between '{3} 08:00:00' and '{4} 07:59:59' ", partnumber, typeno, typename, DateTime.Now.ToString("yyyy-MM-dd", new CultureInfo("en-US")), DateTime.Now.AddDays(1).ToString("yyyy-MM-dd", new CultureInfo("en-US")));
                    DataTable dtchkid = fc.SQL_DataTable(chkid.ToString());
                    if (dtchkid.Rows.Count > 0)
                    {
                        inspidid = dtchkid.Rows[0]["inspidid"].ToString();

                    }

                    string lamp = string.Empty;
                    string linename = string.Empty;
                    string model = string.Empty;

                    string strlamp = string.Format("select lamp,linename,model from LineGroupMaster where partnumber='{0}'",partnumber);
                    DataTable dtlamp = fc.SQL_DataTable(strlamp);
                    if (dtlamp.Rows.Count > 0)
                    {
                        lamp = dtlamp.Rows[0]["lamp"].ToString();
                        linename = dtlamp.Rows[0]["linename"].ToString();
                        model = dtlamp.Rows[0]["model"].ToString();

                    }

                    string docno = lamp + "-" + linename + "-" + model + "-" + DateTime.Now.ToString("yyyy-MM-dd", new CultureInfo("en-US"));

                    if (inspidid.Length == 0)
                    {

                        string _pv = string.Empty;
                        string _id = string.Empty;
                        string _q = string.Format(" select max(convert(real,inspidid)) as id from InspectionInput ");
                        DataTable dtgenid = fc.SQL_DataTable(_q.ToString());
                        if (dtgenid.Rows.Count == 0)
                        {
                            _id = "1";
                        }
                        else
                        {
                            foreach (DataRow dr in dtgenid.Rows)
                            {
                                if (dr[0].ToString() == "")
                                {
                                    _id = "1";
                                }
                                else
                                {
                                    _id = (int.Parse(dr[0].ToString()) + 1).ToString();
                                }
                            }
                        }

                        inspidid = _id;


                    }

                    string equid = string.Empty;
                    string inspectid = string.Empty;
                    string str_inspect = string.Format("select inspectid,equid from InspectionItem  Where itemno='{0}' and itemname='{1}'",typeno, typename);
                    DataTable dtinspect = fc.SQL_DataTable(str_inspect);
                    if (dtinspect.Rows.Count > 0)
                    {
                        inspectid = dtinspect.Rows[0]["inspectid"].ToString();
                        equid = dtinspect.Rows[0]["equid"].ToString();

                    }


                    string crdate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", new CultureInfo("en-US"));
                    if(equid.Length==0)
                    {
                        equid = "0";

                    }


                    string shift_id = string.Empty;
                    string shift_name = string.Empty;

                    string str_shift = string.Format("select  shift_id,shift_name from Work_shift as a inner join EquipmentList as b on a.linegroupid=b.linegroupid  Where '{1}' between shift_timestart and shift_timeend", equid, DateTime.Now.ToString("HH:mm:ss", new CultureInfo("en-US")));
                    DataTable dtshift = fc.SQL_DataTable(str_shift);
                    if (dtshift.Rows.Count > 0)
                    {
                        shift_id = dtshift.Rows[0]["shift_id"].ToString();
                        shift_name = dtshift.Rows[0]["shift_name"].ToString();

                    }

                    if (shift_id.Length == 0)
                    {
                        shift_id = "1";
                        shift_name = "Day";

                    }


                    if (piz.Length == 0)
                    {
                        string str_lastpiz = string.Format("select top 1 insp_piz from InspectionInput Where inspectiontype='4' and equid='{0}' and inspectid='{1}' order by create_datetime desc", equid, inspectid);
                        DataTable dtlastpiz = fc.SQL_DataTable(str_lastpiz);
                        if (dtlastpiz.Rows.Count > 0)
                        {
                            piz = dtlastpiz.Rows[0][0].ToString();

                        }

                    }


                    string inspection_date = string.Empty;
                    int chktime = DateTime.Now.Hour;
                    if (chktime >= 0 && chktime < 8)
                    {
                        inspection_date = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd", new CultureInfo("en-US")) + " " + DateTime.Now.ToString("HH:mm:ss", new CultureInfo("en-US"));



                    }
                    else
                    {


                        inspection_date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", new CultureInfo("en-US"));



                    }





                    string inst_mt = string.Format(" insert into InspectionInput (inspidid,equid,inspectid,itemno,itemname,partnumber, inspectiondate, inspectiontype, result1,action1,result2,action2, notice, flagdel, create_user, create_datetime,insp_piz,detailchangepoint,insp_status,shift_id,shift_name,lotno,orderqty,wasteqty,idrefno) VALUES ('" + inspidid + "','" + equid + "','" + inspectid + "', '" + typeno + "','" + typename + "','" + partnumber + "','" + inspection_date + "','4','" + result1 + "','" + case1 + "','" + result2 + "','" + case2 + "','" + notice + "',0,'" + user + "','" + crdate + "','" + piz + "','" + detail + "','W'," + shift_id + ",'" + shift_name + "','"+lotno+"','"+orderqty+"','"+wasteqty+"','"+docno+"')");
                    string up_mt = string.Format(" update InspectionInput SET equid='" + equid + "',inspectid='" + inspectid + "',itemno='" + typeno + "',itemname='" + typename + "', partnumber= '" + partnumber + "',inspectiondate= '" + inspection_date + "',inspectiontype= '4',result1= '" + result1 + "',action1='" + case1 + "',result2='" + result2 + "',action2='" + case2 + "',notice= '" + notice + "',flagdel=0,Update_user= '" + user + "',Update_Datetime= '" + crdate + "',insp_piz='" + piz + "',detailchangepoint='" + detail + "',insp_status='W',shift_id=" + shift_id + ",shift_name='" + shift_name + "',lotno='"+lotno+"',orderqty='"+orderqty+"',wasteqty='"+wasteqty+"',idrefno='"+docno+"' Where inspidid= '" + inspidid + "' ");

                    cmdhd = fc.ExecSQLStatement(inst_mt.ToString());
                    if(cmdhd.Length==0)
                    {

                        try
                        {
                            string userapprove = clsControlUI.getuserapprove("1", "4", partnumber);
                            clsControlUI.sendemail("1", "Check sheet document waiting for approval.", userapprove, "4");
                        }
                        catch { };


                    }
                    if (cmdhd.ToLower().IndexOf("duplicate") != -1)
                    {
                        cmdhd = fc.ExecSQLStatement(up_mt.ToString());
                    }
                    fc.closeconnection();




                }
                catch { };

            }

            //string cmdsendmail = string.Empty;
            //clsControlUI.sendemail("1", "Scrap document waiting for approval.", userapprove);

            //cmdhd = inspidid + "|" + cmdhd;

            return cmdhd;


        }

        protected void Page_Load(object sender, EventArgs e)
        {

        }

       
        protected void btnrequestapprove_Click(object sender, EventArgs e)
        {
            Response.Redirect("../CheckItemSelect?para=" + Request["para"].ToString());
        }

        protected void btnback_Click(object sender, EventArgs e)
        {
            Response.Redirect("../CheckItemSelect?para=" + Request["para"].ToString());
        }
    }
}