using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Globalization;
using System.Collections;
using System.Threading;
using System.Resources;
using System.ComponentModel;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using System.Net;
using System.Net.Mail;
using System.Xml;



namespace CheckSheet
{
    public class clsControlUI
    {
        public static string create_master_id(string tbl,string col)
        {

         
            string _id = string.Empty;
            using (FcSql.Function fc = new FcSql.Function())
            {
                string _q = string.Format(" select max(convert(real,{1})) as id from {0} ", tbl, col);
                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();
                        }
                    }
                }
                fc.closeconnection();
            }


            return _id;
        }
    
        public static string getuserapprove(string level,string inspectiontype,string partnumber)
        {
            string userapprove = string.Empty;
            using(FcSql.Function fc =new FcSql.Function())
            {
                string str_approve_filter = string.Format("select approve_userid from mst_Approve Where inspectiontype='{0}' and approve_level={1} and  partnumber='{2}'", inspectiontype, level, partnumber);
                string str_approve = string.Format("select approve_userid from mst_Approve Where inspectiontype='{0}' and approve_level={1}", inspectiontype, level);
                DataTable dt_approve = fc.SQL_DataTable(str_approve_filter);
                if (dt_approve.Rows.Count > 0)
                {

                    userapprove = dt_approve.Rows[0][0].ToString();

                }
                else
                {

                    dt_approve = fc.SQL_DataTable(str_approve);
                    if (dt_approve.Rows.Count > 0)
                    {

                        userapprove = dt_approve.Rows[0][0].ToString();

                    }

                }



            }



            return userapprove;
        }
        public static string getEmpName(string userid)
        {
            string empname = string.Empty;
            using (FcSql.Function fc = new FcSql.Function())
            {
                string str_approve = string.Format("select usercode,firstname+' '+lastname as fullname from Users Where usercode='{0}' ", userid);
                DataTable dt_approve = fc.SQL_DataTable(str_approve);
                if (dt_approve.Rows.Count > 0)
                {

                    empname = dt_approve.Rows[0]["fullname"].ToString();

                }



            }



            return empname;


        }
        public static string sendemail(string level,string subject,string userapproveid,string inspectiontype)
        {
            Thread myNewThread = new Thread(() => thredsendemail(level,subject,userapproveid,inspectiontype));
            myNewThread.Start();


            return "";

        }

        private static void thredsendemail(string level, string subject, string userapproveid,string inspectiontype)
        {
            string cmd = string.Empty;


            string docno = clsControlUI.GetXML("docno");
            string hostip = clsControlUI.GetXML("hostip");
            string smtp = clsControlUI.GetXML("smtp");
            string email = clsControlUI.GetXML("email");
            string passwordconfig = clsControlUI.GetXML("password");


            string strDecriptPassword = clsControlUI.decriptpassword(email, passwordconfig);
            string smtpAddress = smtp;
            string emailFrom = email;
            string password = strDecriptPassword;

            string str_body = string.Empty;
            string data_body = string.Empty;
            string data_header = string.Empty;
            string linegroupid = string.Empty;
            string linegroupname = string.Empty;
            string partnumber = string.Empty;
            string month = string.Empty;
            string year = string.Empty;
            if(level=="1")
            {

                string seq = string.Empty;
                using (FcSql.Function fc = new FcSql.Function())
                {
                    string str_user = string.Format(" select approve_userid,approve_level,approve_username,approve_seq from mst_Approve  Where approve_userid='{0}' and inspectiontype='{1}' ", userapproveid, inspectiontype);
                    DataTable dt_user = fc.SQL_DataTable(str_user);
                    if (dt_user.Rows.Count > 0)
                    {

                        seq = dt_user.Rows[0]["approve_seq"].ToString();
                    }

                    fc.closeconnection();

                }
                if(inspectiontype=="1" || inspectiontype=="2")
                {
                    data_header = "<tr><th style='border: 1px solid;'>Machine<br/>ID</th><th style='border: 1px solid;'>Machine</th><th style='border: 1px solid;'>No.</th><th style='border: 1px solid;'>Inspection<br/>Item</th><th style='border: 1px solid;'>Inspection<br/>Date</th><th style='border: 1px solid;'>Result</th><th style='border: 1px solid;'>Notice</th></tr>";
                    str_body = string.Format("select b.machineid,c.machinename,a.itemno,a.itemname,a.inspectiondate,case when resultvalue is NULL then resultstatus else  convert(varchar(10),resultvalue) end as result,notice,b.linegroupid,b.partnumber,d.linename from InspectionInput as a inner join EquipmentList as b on a.equid=b.equid  inner  join MachineMaster as c on b.machineid=c.machineid inner join LineGroupMaster as d on b.linegroupid=d.linegroupid Where inspectiontype='{0}'	and insp_status='W' and check{1}_status is NULL  ", inspectiontype, seq);
                    using (FcSql.Function fc = new FcSql.Function())
                    {
                        DataTable dtbody = fc.SQL_DataTable(str_body);
                        foreach (DataRow dr in dtbody.Rows)
                        {
                            data_body = data_body + "<tr><td style='border: 1px solid;'>" + dr["machineid"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["machinename"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["itemno"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["itemname"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + DateTime.Parse(dr["inspectiondate"].ToString()).ToString("dd/MM/yy", new CultureInfo("en-US")) + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["result"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["notice"].ToString() + "</td></tr>";

                            linegroupid = dr["linegroupid"].ToString();
                            linegroupname = dr["linename"].ToString();
                            partnumber = dr["partnumber"].ToString();
                            month = DateTime.Parse(dr["inspectiondate"].ToString()).ToString("MM", new CultureInfo("en-US"));
                            year = DateTime.Parse(dr["inspectiondate"].ToString()).ToString("yyyy", new CultureInfo("en-US"));


                        }

                        data_body = "<table style='border: 1px solid;width:100%;border-collapse: collapse;'>" + data_header + data_body + "</table>";

                        fc.closeconnection();

                    }

                }
                else if(inspectiontype=="3")
                {
                    data_header = "<tr><th style='border: 1px solid;'>Machine<br/>ID</th><th style='border: 1px solid;'>Machine</th><th style='border: 1px solid;'>Part<br/>number</th><th style='border: 1px solid;'>Serial<br/>number</th><th style='border: 1px solid;'>Tool name</th><th style='border: 1px solid;'>Inspection<br/>Date</th><th style='border: 1px solid;'>Result</th><th style='border: 1px solid;'>Notice</th></tr>";
                    str_body = string.Format("select b.machineid,c.machinename,a.partnumber,a.serialnumber as itemno,a.toolname as itemname,a.inspectiondate,case when resultvalue is NULL then resultstatus else  convert(varchar(10),resultvalue) end as result,notice,b.linegroupid,b.partnumber,d.linename from InspectionInput as a inner join EquipmentList as b on a.jigid=b.jigid  inner  join MachineMaster as c on b.machineid=c.machineid inner join LineGroupMaster as d on b.linegroupid=d.linegroupid Where inspectiontype='{0}'	and insp_status='W' and check{1}_status is NULL ", inspectiontype, seq);
                    using (FcSql.Function fc = new FcSql.Function())
                    {
                        DataTable dtbody = fc.SQL_DataTable(str_body);
                        foreach (DataRow dr in dtbody.Rows)
                        {
                            data_body = data_body + "<tr><td style='border: 1px solid;'>" + dr["machineid"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["machinename"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["partnumber"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["itemno"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["itemname"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + DateTime.Parse(dr["inspectiondate"].ToString()).ToString("dd/MM/yy", new CultureInfo("en-US")) + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["result"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["notice"].ToString() + "</td></tr>";

                            linegroupid = dr["linegroupid"].ToString();
                            linegroupname = dr["linename"].ToString();
                            partnumber = dr["partnumber"].ToString();

                            month = DateTime.Parse(dr["inspectiondate"].ToString()).ToString("MM", new CultureInfo("en-US"));
                            year = DateTime.Parse(dr["inspectiondate"].ToString()).ToString("yyyy", new CultureInfo("en-US"));


                        }

                        data_body = "<table style='border: 1px solid;width:100%;border-collapse: collapse;'>" + data_header + data_body + "</table>";
                        fc.closeconnection();


                    }

                }
                else
                {
                    data_header = "<tr><th style='border: 1px solid;'>Machine<br/>ID</th><th style='border: 1px solid;'>Machine</th><th style='border: 1px solid;'>No.</th><th style='border: 1px solid;'>Inspection<br/>Item</th><th style='border: 1px solid;'>Inspection<br/>Date</th><th style='border: 1px solid;'>Detail</th><th style='border: 1px solid;'>Result 1</th><th style='border: 1px solid;'>Action 1</th><th style='border: 1px solid;'>Result 2</th><th style='border: 1px solid;'>Action 2</th><th style='border: 1px solid;'>Notice</th></tr>";

                    str_body = string.Format("select b.machineid,c.machinename,a.itemno,a.itemname,a.inspectiondate,detailchangepoint,result1,action1,result2,action2,notice,b.linegroupid,b.partnumber,d.linename from InspectionInput as a inner join EquipmentList as b on a.equid=b.equid  inner  join MachineMaster as c on b.machineid=c.machineid inner join LineGroupMaster as d on b.linegroupid=d.linegroupid Where inspectiontype='{0}'	and insp_status='W' and check{1}_status is NULL ", inspectiontype, seq);
                    using (FcSql.Function fc = new FcSql.Function())
                    {
                        DataTable dtbody = fc.SQL_DataTable(str_body);
                        foreach (DataRow dr in dtbody.Rows)
                        {
                            data_body = data_body + "<tr><td style='border: 1px solid;'>" + dr["machineid"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["machinename"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["itemno"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["itemname"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + DateTime.Parse(dr["inspectiondate"].ToString()).ToString("dd/MM/yy", new CultureInfo("en-US")) + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["detailchangepoint"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["result1"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["action1"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["result2"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["action2"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["notice"].ToString() + "</td></tr>";

                            linegroupid = dr["linegroupid"].ToString();
                            linegroupname = dr["linename"].ToString();
                            partnumber = dr["partnumber"].ToString();
                            month = DateTime.Parse(dr["inspectiondate"].ToString()).ToString("MM", new CultureInfo("en-US"));
                            year = DateTime.Parse(dr["inspectiondate"].ToString()).ToString("yyyy", new CultureInfo("en-US"));


                        }

                        data_body = "<table style='border: 1px solid;width:100%;border-collapse: collapse;'>" + data_header + data_body + "</table>";

                        fc.closeconnection();

                    }

                }


            }
            else
            {
                string seq = string.Empty;
                using (FcSql.Function fc = new FcSql.Function())
                {
                    string str_user = string.Format(" select approve_userid,approve_level,approve_username,approve_seq from mst_Approve  Where approve_userid='{0}' and inspectiontype='{1}' ", userapproveid, inspectiontype);
                    DataTable dt_user = fc.SQL_DataTable(str_user);
                    if (dt_user.Rows.Count > 0)
                    {

                        seq = dt_user.Rows[0]["approve_seq"].ToString();
                    }

                    fc.closeconnection();

                }
                if (inspectiontype == "1" || inspectiontype == "2")
                {
                    data_header = "<tr><th style='border: 1px solid;'>Machine<br/>ID</th><th style='border: 1px solid;'>Machine</th><th style='border: 1px solid;'>No.</th><th style='border: 1px solid;'>Inspection<br/>Item</th><th style='border: 1px solid;'>Inspection<br/>Date</th><th style='border: 1px solid;'>Result</th><th style='border: 1px solid;'>Notice</th></tr>";
                    str_body = string.Format("select b.machineid,c.machinename,a.itemno,a.itemname,a.inspectiondate,case when resultvalue is NULL then resultstatus else  convert(varchar(10),resultvalue) end as result,notice,b.linegroupid,b.partnumber,d.linename from InspectionInput as a inner join EquipmentList as b on a.equid=b.equid  inner  join MachineMaster as c on b.machineid=c.machineid inner join LineGroupMaster as d on b.linegroupid=d.linegroupid Where inspectiontype='{0}'	and insp_status='W' and check{1}_status='Y'  ", inspectiontype, seq);
                    using (FcSql.Function fc = new FcSql.Function())
                    {
                        DataTable dtbody = fc.SQL_DataTable(str_body);
                        foreach (DataRow dr in dtbody.Rows)
                        {
                            data_body = data_body + "<tr><td style='border: 1px solid;'>" + dr["machineid"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["machinename"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["itemno"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["itemname"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + DateTime.Parse(dr["inspectiondate"].ToString()).ToString("dd/MM/yy", new CultureInfo("en-US")) + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["result"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["notice"].ToString() + "</td></tr>";

                            linegroupid = dr["linegroupid"].ToString();
                            linegroupname = dr["linename"].ToString();
                            partnumber = dr["partnumber"].ToString();
                            month = DateTime.Parse(dr["inspectiondate"].ToString()).ToString("MM", new CultureInfo("en-US"));
                            year = DateTime.Parse(dr["inspectiondate"].ToString()).ToString("yyyy", new CultureInfo("en-US"));


                        }

                        data_body = "<table style='border: 1px solid;width:100%;border-collapse: collapse;'>" + data_header + data_body + "</table>";

                        fc.closeconnection();

                    }

                }
                else if (inspectiontype == "3")
                {
                    data_header = "<tr><th style='border: 1px solid;'>Machine<br/>ID</th><th style='border: 1px solid;'>Machine</th><th style='border: 1px solid;'>Part<br/>number</th><th style='border: 1px solid;'>Serial<br/>number</th><th style='border: 1px solid;'>Tool name</th><th style='border: 1px solid;'>Inspection<br/>Date</th><th style='border: 1px solid;'>Result</th><th style='border: 1px solid;'>Notice</th></tr>";
                    str_body = string.Format("select b.machineid,c.machinename,a.partnumber,a.serialnumber as itemno,a.toolname as itemname,a.inspectiondate,case when resultvalue is NULL then resultstatus else  convert(varchar(10),resultvalue) end as result,notice,b.linegroupid,b.partnumber,d.linename from InspectionInput as a inner join EquipmentList as b on a.jigid=b.jigid  inner  join MachineMaster as c on b.machineid=c.machineid inner join LineGroupMaster as d on b.linegroupid=d.linegroupid Where inspectiontype='{0}'	and insp_status='W' and check{1}_status='Y' ", inspectiontype, seq);
                    using (FcSql.Function fc = new FcSql.Function())
                    {
                        DataTable dtbody = fc.SQL_DataTable(str_body);
                        foreach (DataRow dr in dtbody.Rows)
                        {
                            data_body = data_body + "<tr><td style='border: 1px solid;'>" + dr["machineid"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["machinename"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["partnumber"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["itemno"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["itemname"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + DateTime.Parse(dr["inspectiondate"].ToString()).ToString("dd/MM/yy", new CultureInfo("en-US")) + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["result"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["notice"].ToString() + "</td></tr>";

                            linegroupid = dr["linegroupid"].ToString();
                            linegroupname = dr["linename"].ToString();
                            partnumber = dr["partnumber"].ToString();
                            month = DateTime.Parse(dr["inspectiondate"].ToString()).ToString("MM", new CultureInfo("en-US"));
                            year = DateTime.Parse(dr["inspectiondate"].ToString()).ToString("yyyy", new CultureInfo("en-US"));


                        }

                        data_body = "<table style='border: 1px solid;width:100%;border-collapse: collapse;'>" + data_header + data_body + "</table>";
                        fc.closeconnection();


                    }

                }
                else
                {
                    data_header = "<tr><th style='border: 1px solid;'>Machine<br/>ID</th><th style='border: 1px solid;'>Machine</th><th style='border: 1px solid;'>No.</th><th style='border: 1px solid;'>Inspection<br/>Item</th><th style='border: 1px solid;'>Inspection<br/>Date</th><th style='border: 1px solid;'>Detail</th><th style='border: 1px solid;'>Result 1</th><th style='border: 1px solid;'>Action 1</th><th style='border: 1px solid;'>Result 2</th><th style='border: 1px solid;'>Action 2</th><th style='border: 1px solid;'>Notice</th></tr>";

                    str_body = string.Format("select b.machineid,c.machinename,a.itemno,a.itemname,a.inspectiondate,detailchangepoint,result1,action1,result2,action2,notice,b.linegroupid,b.partnumber,d.linename from InspectionInput as a inner join EquipmentList as b on a.equid=b.equid  inner  join MachineMaster as c on b.machineid=c.machineid inner join LineGroupMaster as d on b.linegroupid=d.linegroupid Where inspectiontype='{0}'	and insp_status='W' and check{1}_status='Y' ", inspectiontype, seq);
                    using (FcSql.Function fc = new FcSql.Function())
                    {
                        DataTable dtbody = fc.SQL_DataTable(str_body);
                        foreach (DataRow dr in dtbody.Rows)
                        {
                            data_body = data_body + "<tr><td style='border: 1px solid;'>" + dr["machineid"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["machinename"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["itemno"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["itemname"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + DateTime.Parse(dr["inspectiondate"].ToString()).ToString("dd/MM/yy", new CultureInfo("en-US")) + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["detailchangepoint"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["result1"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["action1"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["result2"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["action2"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["notice"].ToString() + "</td></tr>";

                            linegroupid = dr["linegroupid"].ToString();
                            linegroupname = dr["linename"].ToString();
                            partnumber = dr["partnumber"].ToString();
                            month = DateTime.Parse(dr["inspectiondate"].ToString()).ToString("MM", new CultureInfo("en-US"));
                            year = DateTime.Parse(dr["inspectiondate"].ToString()).ToString("yyyy", new CultureInfo("en-US"));


                        }

                        data_body = "<table style='border: 1px solid;width:100%;border-collapse: collapse;'>" + data_header + data_body + "</table>";

                        fc.closeconnection();

                    }

                }
                

            }

           
            string cc = string.Empty;
            string body = string.Empty;
            using (var message = new MailMessage())
            {
                string emailTo = string.Empty;
                string emailNameTo = string.Empty;

                using (FcSql.Function fc = new FcSql.Function())
                {
                    string str_approve = string.Format("select distinct approve_email,approve_userid,approve_username,approve_position from mst_Approve Where approve_level={0} and inspectiontype='{1}' and approve_userid='{2}'", level.ToString(), inspectiontype, userapproveid);
                    DataTable dt_apprve = fc.SQL_DataTable(str_approve);
                    if (dt_apprve.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt_apprve.Rows)
                        {
                            emailTo = dr["approve_email"].ToString();
                            emailNameTo = dr["approve_username"].ToString();
                            message.To.Add(new MailAddress(emailTo, emailNameTo));


                            string strdata = dr["approve_userid"].ToString() + "|" + dr["approve_username"].ToString() + "|" + dr["approve_position"].ToString() + "|" + linegroupid + "|" + linegroupname + "|" + partnumber + "|" + month + "|" + year + "|";
                            byte[] encrypt = Encoding.UTF8.GetBytes(strdata.Replace("#", ""));
                            string ecypt_userapprove = Convert.ToBase64String(encrypt);
                       
                            if (inspectiontype == "1")
                            {
                                body = string.Format("<a href='{0}/approve/Machine_inspection_result?user={1}' target='_blank'>Please click to check approval information.</a><br/><br/>{2}", hostip, ecypt_userapprove, data_body);


                            }
                            else if (inspectiontype == "2")
                            {
                                body = string.Format("<a href='{0}/approve/XR_inspection_result?user={1}' target='_blank'>Please click to check approval information.</a><br/><br/>{2}", hostip, ecypt_userapprove, data_body);


                            }
                            else if (inspectiontype == "3")
                            {
                                body = string.Format("<a href='{0}/approve/Jig_inspection_result?user={1}' target='_blank'>Please click to check approval information.</a><br/><br/>{2}", hostip, ecypt_userapprove, data_body);


                            }
                            else if (inspectiontype == "4")
                            {
                                body = string.Format("<a href='{0}/approve/4m1e_inspection_result?user={1}' target='_blank'>Please click to check approval information.</a><br/><br/>{2}", hostip, ecypt_userapprove, data_body);


                            }


                        }
                    }
                    else
                    {

                        str_approve = string.Format("select distinct approve_email,approve_userid,approve_username,approve_position from mst_Approve Where approve_level={0} and inspectiontype='{1}' ", level.ToString(), inspectiontype);
                        dt_apprve = fc.SQL_DataTable(str_approve);
                        foreach (DataRow dr in dt_apprve.Rows)
                        {
                            emailTo = dr["approve_email"].ToString();
                            emailNameTo = dr["approve_username"].ToString();
                            message.To.Add(new MailAddress(emailTo, emailNameTo));
                            string strdata = dr["approve_userid"].ToString() + "|" + dr["approve_username"].ToString() + "|" + dr["approve_position"].ToString() + "|" + linegroupid + "|" + partnumber + "|" + month + "|" + year + "|";
                            byte[] encrypt = Encoding.UTF8.GetBytes(strdata.Replace("#", ""));
                            string ecypt_userapprove = Convert.ToBase64String(encrypt);
                         

                            if (inspectiontype == "1")
                            {
                                body = string.Format("<a href='{0}/approve/Machine_inspection_result?user={1}' target='_blank'>Please click to check approval information.</a><br/><br/>{2}", hostip, ecypt_userapprove, data_body);


                            }
                            else if (inspectiontype == "2")
                            {
                                body = string.Format("<a href='{0}/approve/XR_inspection_result?user={1}' target='_blank'>Please click to check approval information.</a><br/><br/>{2}", hostip, ecypt_userapprove, data_body);


                            }
                            else if (inspectiontype == "3")
                            {
                                body = string.Format("<a href='{0}/approve/Jig_inspection_result?user={1}' target='_blank'>Please click to check approval information.</a><br/><br/>{2}", hostip, ecypt_userapprove, data_body);


                            }
                            else if (inspectiontype == "4")
                            {
                                body = string.Format("<a href='{0}/approve/4m1e_inspection_result?user={1}' target='_blank'>Please click to check approval information.</a><br/><br/>{2}", hostip, ecypt_userapprove, data_body);


                            }
                        }
                    }

                    fc.closeconnection();

                }


                message.From = new MailAddress(emailFrom, "Check Sheet System");
                message.Subject = subject;
                message.Body = body;
                message.IsBodyHtml = true; // change to true if body msg is in html

                using (var client = new SmtpClient(smtpAddress))
                {
                    client.UseDefaultCredentials = false;
                    client.Port = int.Parse(clsControlUI.GetXML("port"));
                    client.Credentials = new NetworkCredential(emailFrom, password);
                    client.EnableSsl = true;

                    try
                    {
                        client.Send(message);

                    }
                    catch (Exception e)
                    {
                        using (FcSql.Function fc = new FcSql.Function())
                        {
                            string err = string.Format("insert into EmailSend_log (error_msg, log_datetime) values ('{0}','{1}')", e.ToString(), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", new CultureInfo("en-US")));
                            string errcmd = fc.ExecSQLStatement(err.ToString());
                            fc.closeconnection();
                        }

                       

                        cmd = "";
                    }
                }
            }

            //return cmd;
        }


        public static string sendreturnemail(string level, string subject, string userapproveid, string inspectiontype,string userreject)
        {
            Thread myNewThread = new Thread(() => thredsendreturnemail(level, subject, userapproveid, inspectiontype,userreject));
            myNewThread.Start();


            return "";

        }

        private static void thredsendreturnemail(string level, string subject, string userapproveid, string inspectiontype,string userreject)
        {
            string cmd = string.Empty;


            string docno = clsControlUI.GetXML("docno");
            string hostip = clsControlUI.GetXML("hostip");
            string smtp = clsControlUI.GetXML("smtp");
            string email = clsControlUI.GetXML("email");
            string passwordconfig = clsControlUI.GetXML("password");


            string strDecriptPassword = clsControlUI.decriptpassword(email, passwordconfig);
            string smtpAddress = smtp;
            string emailFrom = email;
            string password = strDecriptPassword;

            string str_body = string.Empty;
            string data_body = string.Empty;
            string data_header = string.Empty;


            string seq = string.Empty;
            using (FcSql.Function fc = new FcSql.Function())
            {
                string str_user = string.Format(" select approve_userid,approve_level,approve_username,approve_seq from mst_Approve  Where approve_userid='{0}' and inspectiontype='{1}' ", userreject, inspectiontype);
                DataTable dt_user = fc.SQL_DataTable(str_user);
                if (dt_user.Rows.Count > 0)
                {
                   
                    seq = dt_user.Rows[0]["approve_seq"].ToString();

                }

                fc.closeconnection();
            }


            if (level == "1")
            {
                if (inspectiontype == "1" || inspectiontype == "2")
                {
                    data_header = "<tr><th style='border: 1px solid;'>Machine<br/>ID</th><th style='border: 1px solid;'>Machine</th><th style='border: 1px solid;'>No.</th><th style='border: 1px solid;'>Inspection<br/>Item</th><th style='border: 1px solid;'>Inspection<br/>Date</th><th style='border: 1px solid;'>Result</th><th style='border: 1px solid;'>Notice</th><th style='border: 1px solid;'>Approve<br/>By</th><th style='border: 1px solid;'>Approve<br/>Date</th><th style='border: 1px solid;'>Approve<br/>Result</th><th style='border: 1px solid;'>Approve<br/>Notice</th></tr>";
                    str_body = string.Format("select b.machineid,c.machinename,a.itemno,a.itemname,a.inspectiondate,case when resultvalue is NULL then resultstatus else  convert(varchar(10),resultvalue) end as result,notice,check{1}_status,check{1}_date,check{1}_notice,check{1}_userid,confirm1_status,confirm1_date,confirm1_notice,confirm1_userid from InspectionInput as a inner join EquipmentList as b on a.equid=b.equid  inner  join MachineMaster as c on b.machineid=c.machineid Where inspectiontype='{0}'	and insp_status='R' and (check{1}_status='N' or confirm1_status='N') ", inspectiontype, seq);
                    using (FcSql.Function fc = new FcSql.Function())
                    {
                        DataTable dtbody = fc.SQL_DataTable(str_body);
                        foreach (DataRow dr in dtbody.Rows)
                        {
                            data_body = data_body + "<tr><td style='border: 1px solid;'>" + dr["machineid"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["machinename"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["itemno"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["itemname"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + DateTime.Parse(dr["inspectiondate"].ToString()).ToString("dd/MM/yy", new CultureInfo("en-US")) + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["result"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["notice"].ToString() + "</td>";
                            if (dr["check"+seq+"_date"].ToString()!="")
                            {

                                data_body = data_body + "<td style='border: 1px solid;'>" + clsControlUI.getEmpName(dr["check" + seq + "_userid"].ToString()) + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + DateTime.Parse(dr["check" + seq + "_date"].ToString()).ToString("dd/MM/yy", new CultureInfo("en-US")) + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + dr["check" + seq + "_status"].ToString() + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + dr["check" + seq + "_notice"].ToString() + "</td></tr>";
                            
                            }
                            else
                            {
                                data_body = data_body + "<td style='border: 1px solid;'>" + clsControlUI.getEmpName(dr["confirm1_userid"].ToString()) + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + DateTime.Parse(dr["confirm1_date"].ToString()).ToString("dd/MM/yy", new CultureInfo("en-US")) + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + dr["confirm1_status"].ToString() + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + dr["confirm1_notice"].ToString() + "</td></tr>";

                            }
                            
                    


                        }

                        data_body = "<table style='border: 1px solid;width:100%;border-collapse: collapse;'>" + data_header + data_body + "</table>";

                        fc.closeconnection();

                    }

                }
                else if (inspectiontype == "3")
                {
                    data_header = "<tr><th style='border: 1px solid;'>Machine<br/>ID</th><th style='border: 1px solid;'>Machine</th><th style='border: 1px solid;'>Part<br/>number</th><th style='border: 1px solid;'>Serial<br/>number</th><th style='border: 1px solid;'>Tool name</th><th style='border: 1px solid;'>Inspection<br/>Date</th><th style='border: 1px solid;'>Result</th><th style='border: 1px solid;'>Notice</th><th style='border: 1px solid;'>Approve<br/>By</th><th style='border: 1px solid;'>Approve<br/>Date</th><th style='border: 1px solid;'>Approve<br/>Result</th><th style='border: 1px solid;'>Approve<br/>Notice</th></tr>";
                    str_body = string.Format("select b.machineid,c.machinename,a.partnumber,a.serialnumber as itemno,a.toolname as itemname,a.inspectiondate,case when resultvalue is NULL then resultstatus else  convert(varchar(10),resultvalue) end as result,notice,check{1}_status,check{1}_date,check{1}_notice,check{1}_userid,confirm1_status,confirm1_date,confirm1_notice,confirm1_userid from InspectionInput as a inner join EquipmentList as b on a.jigid=b.jigid  inner  join MachineMaster as c on b.machineid=c.machineid Where inspectiontype='{0}'	and insp_status='R' and (check{1}_status='N' or confirm1_status='N') ", inspectiontype, seq);
                    using (FcSql.Function fc = new FcSql.Function())
                    {
                        DataTable dtbody = fc.SQL_DataTable(str_body);
                        foreach (DataRow dr in dtbody.Rows)
                        {
                            data_body = data_body + "<tr><td style='border: 1px solid;'>" + dr["machineid"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["machinename"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["partnumber"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["itemno"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["itemname"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + DateTime.Parse(dr["inspectiondate"].ToString()).ToString("dd/MM/yy", new CultureInfo("en-US")) + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["result"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["notice"].ToString() + "</td>";
                            if (dr["check" + seq + "_date"].ToString() != "")
                            {

                                data_body = data_body + "<td style='border: 1px solid;'>" + clsControlUI.getEmpName(dr["check" + seq + "_userid"].ToString()) + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + DateTime.Parse(dr["check" + seq + "_date"].ToString()).ToString("dd/MM/yy", new CultureInfo("en-US")) + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + dr["check" + seq + "_status"].ToString() + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + dr["check" + seq + "_notice"].ToString() + "</td>";

                            }
                            else
                            {
                                data_body = data_body + "<td style='border: 1px solid;'>" + clsControlUI.getEmpName(dr["confirm1_userid"].ToString()) + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + DateTime.Parse(dr["confirm1_date"].ToString()).ToString("dd/MM/yy", new CultureInfo("en-US")) + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + dr["confirm1_status"].ToString() + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + dr["confirm1_notice"].ToString() + "</td></tr>";

                            }

                        }

                        data_body = "<table style='border: 1px solid;width:100%;border-collapse: collapse;'>" + data_header + data_body + "</table>";
                        fc.closeconnection();


                    }

                }
                else
                {
                    data_header = "<tr><th style='border: 1px solid;'>Machine<br/>ID</th><th style='border: 1px solid;'>Machine</th><th style='border: 1px solid;'>No.</th><th style='border: 1px solid;'>Inspection<br/>Item</th><th style='border: 1px solid;'>Inspection<br/>Date</th><th style='border: 1px solid;'>Detail</th><th style='border: 1px solid;'>Result 1</th><th style='border: 1px solid;'>Action 1</th><th style='border: 1px solid;'>Result 2</th><th style='border: 1px solid;'>Action 2</th><th style='border: 1px solid;'>Notice</th><th style='border: 1px solid;'>Approve<br/>By</th><th style='border: 1px solid;'>Approve<br/>Date</th><th style='border: 1px solid;'>Approve<br/>Result</th><th style='border: 1px solid;'>Approve<br/>Notice</th></tr>";

                    str_body = string.Format("select b.machineid,c.machinename,a.itemno,a.itemname,a.inspectiondate,detailchangepoint,result1,action1,result2,action2,notice,check{1}_status,check{1}_date,check{1}_notice,check{1}_userid,confirm1_status,confirm1_date,confirm1_notice,confirm1_userid from InspectionInput as a inner join EquipmentList as b on a.equid=b.equid  inner  join MachineMaster as c on b.machineid=c.machineid Where inspectiontype='{0}'	and insp_status='R' and (check{1}_status='N' or confirm1_status='N') ", inspectiontype, seq);
                    using (FcSql.Function fc = new FcSql.Function())
                    {
                        DataTable dtbody = fc.SQL_DataTable(str_body);
                        foreach (DataRow dr in dtbody.Rows)
                        {
                            data_body = data_body + "<tr><td style='border: 1px solid;'>" + dr["machineid"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["machinename"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["itemno"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["itemname"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + DateTime.Parse(dr["inspectiondate"].ToString()).ToString("dd/MM/yy", new CultureInfo("en-US")) + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["detailchangepoint"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["result1"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["action1"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["result2"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["action2"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["notice"].ToString() + "</td>";
                            if (dr["check" + seq + "_date"].ToString() != "")
                            {

                                data_body = data_body + "<td style='border: 1px solid;'>" + clsControlUI.getEmpName(dr["check" + seq + "_userid"].ToString()) + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + DateTime.Parse(dr["check" + seq + "_date"].ToString()).ToString("dd/MM/yy", new CultureInfo("en-US")) + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + dr["check" + seq + "_status"].ToString() + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + dr["check" + seq + "_notice"].ToString() + "</td></tr>";

                            }
                            else
                            {
                                data_body = data_body + "<td style='border: 1px solid;'>" + clsControlUI.getEmpName(dr["confirm1_userid"].ToString()) + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + DateTime.Parse(dr["confirm1_date"].ToString()).ToString("dd/MM/yy", new CultureInfo("en-US")) + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + dr["confirm1_status"].ToString() + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + dr["confirm1_notice"].ToString() + "</td></tr>";

                            }


                        }

                        data_body = "<table style='border: 1px solid;width:100%;border-collapse: collapse;'>" + data_header + data_body + "</table>";

                        fc.closeconnection();

                    }

                }


            }
            else
            {

                if (inspectiontype == "1" || inspectiontype == "2")
                {
                    data_header = "<tr><th style='border: 1px solid;'>Machine<br/>ID</th><th style='border: 1px solid;'>Machine</th><th style='border: 1px solid;'>No.</th><th style='border: 1px solid;'>Inspection<br/>Item</th><th style='border: 1px solid;'>Inspection<br/>Date</th><th style='border: 1px solid;'>Result</th><th style='border: 1px solid;'>Notice</th><th style='border: 1px solid;'>Approve<br/>By</th><th style='border: 1px solid;'>Approve<br/>Date</th><th style='border: 1px solid;'>Approve<br/>Result</th><th style='border: 1px solid;'>Approve<br/>Notice</th></tr>";
                    str_body = string.Format("select b.machineid,c.machinename,a.itemno,a.itemname,a.inspectiondate,case when resultvalue is NULL then resultstatus else  convert(varchar(10),resultvalue) end as result,notice,approve{1}_status,approve{1}_date,approve{1}_notice,approve{1}_userid,confirm2_status,confirm2_date,confirm2_notice,confirm2_userid from InspectionInput as a inner join EquipmentList as b on a.equid=b.equid  inner  join MachineMaster as c on b.machineid=c.machineid Where inspectiontype='{0}'	and insp_status='R' and (approve{1}_status='N' or confirm2_status='N') ", inspectiontype,seq);
                    using (FcSql.Function fc = new FcSql.Function())
                    {
                        DataTable dtbody = fc.SQL_DataTable(str_body);
                        foreach (DataRow dr in dtbody.Rows)
                        {
                            data_body = data_body + "<tr><td style='border: 1px solid;'>" + dr["machineid"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["machinename"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["itemno"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["itemname"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + DateTime.Parse(dr["inspectiondate"].ToString()).ToString("dd/MM/yy", new CultureInfo("en-US")) + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["result"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["notice"].ToString() + "</td>";
                            if (dr["approve" + seq + "_date"].ToString() != "")
                            {

                                data_body = data_body + "<td style='border: 1px solid;'>" + clsControlUI.getEmpName(dr["approve" + seq + "_userid"].ToString()) + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + DateTime.Parse(dr["approve" + seq + "_date"].ToString()).ToString("dd/MM/yy", new CultureInfo("en-US")) + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + dr["approve" + seq + "_status"].ToString() + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + dr["approve" + seq + "_notice"].ToString() + "</td></tr>";

                            }
                            else
                            {
                                data_body = data_body + "<td style='border: 1px solid;'>" + clsControlUI.getEmpName(dr["confirm2_userid"].ToString()) + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + DateTime.Parse(dr["confirm2_date"].ToString()).ToString("dd/MM/yy", new CultureInfo("en-US")) + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + dr["confirm2_status"].ToString() + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + dr["confirm2_notice"].ToString() + "</td></tr>";

                            }


                        }

                        data_body = "<table style='border: 1px solid;width:100%;border-collapse: collapse;'>" + data_header + data_body + "</table>";

                        fc.closeconnection();

                    }

                }
                else if (inspectiontype == "3")
                {
                    data_header = "<tr><th style='border: 1px solid;'>Machine<br/>ID</th><th style='border: 1px solid;'>Machine</th><th style='border: 1px solid;'>Part<br/>number</th><th style='border: 1px solid;'>Serial<br/>number</th><th style='border: 1px solid;'>Tool name</th><th style='border: 1px solid;'>Inspection<br/>Date</th><th style='border: 1px solid;'>Result</th><th style='border: 1px solid;'>Notice</th><th style='border: 1px solid;'>Approve<br/>By</th><th style='border: 1px solid;'>Approve<br/>Date</th><th style='border: 1px solid;'>Approve<br/>Result</th><th style='border: 1px solid;'>Approve<br/>Notice</th></tr>";
                    str_body = string.Format("select b.machineid,c.machinename,a.partnumber,a.serialnumber as itemno,a.toolname as itemname,a.inspectiondate,case when resultvalue is NULL then resultstatus else  convert(varchar(10),resultvalue) end as result,notice,approve{1}_status,approve{1}_date,approve{1}_notice,approve{1}_userid,confirm2_status,confirm2_date,confirm2_notice,confirm2_userid from InspectionInput as a inner join EquipmentList as b on a.jigid=b.jigid  inner  join MachineMaster as c on b.machineid=c.machineid Where inspectiontype='{0}'	and insp_status='R'  and (approve{1}_status='N' or confirm2_status='N')  ", inspectiontype, seq);
                    using (FcSql.Function fc = new FcSql.Function())
                    {
                        DataTable dtbody = fc.SQL_DataTable(str_body);
                        foreach (DataRow dr in dtbody.Rows)
                        {
                            data_body = data_body + "<tr><td style='border: 1px solid;'>" + dr["machineid"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["machinename"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["partnumber"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["itemno"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["itemname"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + DateTime.Parse(dr["inspectiondate"].ToString()).ToString("dd/MM/yy", new CultureInfo("en-US")) + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["result"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["notice"].ToString() + "</td>";
                            if (dr["approve" + seq + "_date"].ToString() != "")
                            {

                                data_body = data_body + "<td style='border: 1px solid;'>" + clsControlUI.getEmpName(dr["approve" + seq + "_userid"].ToString()) + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + DateTime.Parse(dr["approve" + seq + "_date"].ToString()).ToString("dd/MM/yy", new CultureInfo("en-US")) + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + dr["approve" + seq + "_status"].ToString() + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + dr["approve" + seq + "_notice"].ToString() + "</td></tr>";

                            }
                            else
                            {
                                data_body = data_body + "<td style='border: 1px solid;'>" + clsControlUI.getEmpName(dr["confirm2_userid"].ToString()) + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + DateTime.Parse(dr["confirm2_date"].ToString()).ToString("dd/MM/yy", new CultureInfo("en-US")) + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + dr["confirm2_status"].ToString() + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + dr["confirm2_notice"].ToString() + "</td></tr>";

                            }


                        }

                        data_body = "<table style='border: 1px solid;width:100%;border-collapse: collapse;'>" + data_header + data_body + "</table>";
                        fc.closeconnection();


                    }

                }
                else
                {
                    data_header = "<tr><th style='border: 1px solid;'>Machine<br/>ID</th><th style='border: 1px solid;'>Machine</th><th style='border: 1px solid;'>No.</th><th style='border: 1px solid;'>Inspection<br/>Item</th><th style='border: 1px solid;'>Inspection<br/>Date</th><th style='border: 1px solid;'>Detail</th><th style='border: 1px solid;'>Result 1</th><th style='border: 1px solid;'>Action 1</th><th style='border: 1px solid;'>Result 2</th><th style='border: 1px solid;'>Action 2</th><th style='border: 1px solid;'>Notice</th><th style='border: 1px solid;'>Approve<br/>By</th><th style='border: 1px solid;'>Approve<br/>Date</th><th style='border: 1px solid;'>Approve<br/>Result</th><th style='border: 1px solid;'>Approve<br/>Notice</th></tr>";

                    str_body = string.Format("select b.machineid,c.machinename,a.itemno,a.itemname,a.inspectiondate,detailchangepoint,result1,action1,result2,action2,notice,approve{1}_status,approve{1}_date,approve{1}_notice,approve{1}_userid,confirm2_status,confirm2_date,confirm2_notice,confirm2_userid from InspectionInput as a inner join EquipmentList as b on a.equid=b.equid  inner  join MachineMaster as c on b.machineid=c.machineid Where inspectiontype='{0}'	and insp_status='R' and (approve{1}_status='N' or confirm2_status='N')  ", inspectiontype, seq);
                    using (FcSql.Function fc = new FcSql.Function())
                    {
                        DataTable dtbody = fc.SQL_DataTable(str_body);
                        foreach (DataRow dr in dtbody.Rows)
                        {
                            data_body = data_body + "<tr><td style='border: 1px solid;'>" + dr["machineid"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["machinename"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["itemno"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["itemname"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + DateTime.Parse(dr["inspectiondate"].ToString()).ToString("dd/MM/yy", new CultureInfo("en-US")) + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["detailchangepoint"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["result1"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["action1"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["result2"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["action2"].ToString() + "</td>";
                            data_body = data_body + "<td style='border: 1px solid;'>" + dr["notice"].ToString() + "</td>";
                            if (dr["approve"+seq+"_date"].ToString() != "")
                            {

                                data_body = data_body + "<td style='border: 1px solid;'>" + clsControlUI.getEmpName(dr["approve" + seq + "_userid"].ToString()) + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + DateTime.Parse(dr["approve" + seq + "_date"].ToString()).ToString("dd/MM/yy", new CultureInfo("en-US")) + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + dr["approve" + seq + "_status"].ToString() + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + dr["approve" + seq + "_notice"].ToString() + "</td></tr>";

                            }
                            else
                            {
                                data_body = data_body + "<td style='border: 1px solid;'>" + clsControlUI.getEmpName(dr["confirm2_userid"].ToString()) + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + DateTime.Parse(dr["confirm2_date"].ToString()).ToString("dd/MM/yy", new CultureInfo("en-US")) + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + dr["confirm2_status"].ToString() + "</td>";
                                data_body = data_body + "<td style='border: 1px solid;'>" + dr["confirm2_notice"].ToString() + "</td></tr>";

                            }


                        }

                        data_body = "<table style='border: 1px solid;width:100%;border-collapse: collapse;'>" + data_header + data_body + "</table>";

                        fc.closeconnection();

                    }

                }

            }


            byte[] encrypt = Encoding.UTF8.GetBytes(userapproveid.Replace("#", ""));
            string ecypt_userapprove = Convert.ToBase64String(encrypt);

            string body = string.Format("<br/><br/>{2}", hostip, ecypt_userapprove, data_body);
            string cc = string.Empty;

            using (var message = new MailMessage())
            {
                string emailTo = string.Empty;
                string emailNameTo = string.Empty;

                using (FcSql.Function fc = new FcSql.Function())
                {
                    string str_approve = string.Format("select distinct emailaddress,usercode as approve_userid,firstname+' '+lastname as approve_username from Users Where usercode='{0}' ", userapproveid);
                    DataTable dt_apprve = fc.SQL_DataTable(str_approve);
                    foreach (DataRow dr in dt_apprve.Rows)
                    {
                        emailTo = dr["emailaddress"].ToString();
                        emailNameTo = dr["approve_username"].ToString();
                        message.To.Add(new MailAddress(emailTo, emailNameTo));

                    }

                    fc.closeconnection();

                }


                message.From = new MailAddress(emailFrom, "Check Sheet System");
                message.Subject = subject;
                message.Body = body;
                message.IsBodyHtml = true; // change to true if body msg is in html

                using (var client = new SmtpClient(smtpAddress))
                {
                    client.UseDefaultCredentials = false;
                    client.Port = int.Parse(clsControlUI.GetXML("port"));
                    client.Credentials = new NetworkCredential(emailFrom, password);
                    client.EnableSsl = true;

                    try
                    {
                        client.Send(message);

                    }
                    catch (Exception e)
                    {
                        using (FcSql.Function fc = new FcSql.Function())
                        {
                            string err = string.Format("insert into EmailSend_log (error_msg, log_datetime) values ('{0}','{1}')", e.ToString(), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", new CultureInfo("en-US")));
                            string errcmd = fc.ExecSQLStatement(err.ToString());
                            fc.closeconnection();
                        }



                        cmd = "";
                    }
                }
            }

            //return cmd;
        }


        public static string sendemail_delete_linegroup(string lineid,string partnumber,string machineid,string detail, string subject, string userapproveid)
        {
            Thread myNewThread = new Thread(() => thredsendemail_delete_linegroup(lineid,partnumber,machineid,detail,subject, userapproveid));
            myNewThread.Start();


            return "";

        }

        private static void thredsendemail_delete_linegroup(string lineid,string partnumber,string machineid,string detail, string subject, string userapproveid)
        {
            string cmd = string.Empty;


            string docno = clsControlUI.GetXML("docno");
            string hostip = clsControlUI.GetXML("hostip");
            string smtp = clsControlUI.GetXML("smtp");
            string email = clsControlUI.GetXML("email");
            string passwordconfig = clsControlUI.GetXML("password");


            string strDecriptPassword = clsControlUI.decriptpassword(email, passwordconfig);
            string smtpAddress = smtp;
            string emailFrom = email;
            string password = strDecriptPassword;

            string str_body = string.Empty;
            string data_body = detail;
            string data_header = string.Empty;
   
            string cc = string.Empty;
            string body = string.Empty;

            string strdata = userapproveid + "|" + lineid + "|" + partnumber + "|" + machineid + "|";



            byte[] encrypt = Encoding.UTF8.GetBytes(strdata.Replace("#", ""));
            string ecypt_userapprove = Convert.ToBase64String(encrypt);
            body = string.Format("<a href='{0}/approve/Confirm_delete_equ?user={1}' target='_blank'>click to approval.</a><br/><br/>{2}", hostip, ecypt_userapprove, data_body);



            using (var message = new MailMessage())
            {
                string emailTo = string.Empty;
                string emailNameTo = string.Empty;

                using (FcSql.Function fc = new FcSql.Function())
                {
                    string str_approve = string.Format("select distinct approve_email,approve_userid,approve_username,approve_position from mst_Approve Where approve_level=2 and approve_userid='{0}'", userapproveid);
                    DataTable dt_apprve = fc.SQL_DataTable(str_approve);
                    if (dt_apprve.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt_apprve.Rows)
                        {
                            emailTo = dr["approve_email"].ToString();
                            emailNameTo = dr["approve_username"].ToString();
                            message.To.Add(new MailAddress(emailTo, emailNameTo));

                        }
                    }

                    fc.closeconnection();

                }


                message.From = new MailAddress(emailFrom, "Approve delete equipment.");
                message.Subject = subject;
                message.Body = body;
                message.IsBodyHtml = true; // change to true if body msg is in html

                using (var client = new SmtpClient(smtpAddress))
                {
                    client.UseDefaultCredentials = false;
                    client.Port = int.Parse(clsControlUI.GetXML("port"));
                    client.Credentials = new NetworkCredential(emailFrom, password);
                    client.EnableSsl = true;

                    try
                    {
                        client.Send(message);

                    }
                    catch (Exception e)
                    {
                        using (FcSql.Function fc = new FcSql.Function())
                        {
                            string err = string.Format("insert into EmailSend_log (error_msg, log_datetime) values ('{0}','{1}')", e.ToString(), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", new CultureInfo("en-US")));
                            string errcmd = fc.ExecSQLStatement(err.ToString());
                            fc.closeconnection();
                        }



                        cmd = "";
                    }
                }
            }

            //return cmd;
        }



        public static string encriptpassword(string userid,string password)
        {
           

            string strEncriptPassword = string.Empty;
            #region ถอดรหัส Password
            try
            {
                classEncriptDecript EncryptDecrypt = new classEncriptDecript("Piriy@P@ssw0rd1234567890" + userid.Trim());
                strEncriptPassword = EncryptDecrypt.Encrypt(password.Trim());
            }
            catch { };
            #endregion

            return strEncriptPassword;
        }

        public static string decriptpassword(string userid, string password)
        {


            string strEncriptPassword = string.Empty;
            #region ถอดรหัส Password
            try
            {
                classEncriptDecript EncryptDecrypt = new classEncriptDecript("Piriy@P@ssw0rd1234567890" + userid.Trim());
                strEncriptPassword = EncryptDecrypt.Decrypt(password.Trim());
            }
            catch { };
            #endregion

            return strEncriptPassword;
        }



        public static string encriptpara(string value)
        {


            string strEncriptPassword = string.Empty;
           
            try
            {
                classEncriptDecript EncryptDecrypt = new classEncriptDecript("Piriy@P@ssw0rd1234567890");
                strEncriptPassword = EncryptDecrypt.Encrypt(value.Trim());
            }
            catch { };


            return strEncriptPassword;
        }

        public static string decriptpara(string value)
        {


            string strEncriptPassword = string.Empty;
           
            try
            {
                classEncriptDecript EncryptDecrypt = new classEncriptDecript("Piriy@P@ssw0rd1234567890");
                strEncriptPassword = EncryptDecrypt.Decrypt(value.Trim()+"==");
            }
            catch { };
 

            return strEncriptPassword;
        }
        public static string createtoken(string idname, string idemail)
        {
            string strtoken = string.Empty;
            try
            {
                classEncriptDecript EncryptDecrypt = new classEncriptDecript(idname + "_Piriy@P@ssw0rd1234567890");
                strtoken = EncryptDecrypt.Encrypt(idemail);
            }
            catch { };

            return strtoken;

        }

  


        public static string getformatdate(string para, string type)
        {
            string ddate = string.Empty;

            if (type == "yyMMdd")
            {
                if (para != "")
                {

                    try
                    {
                        int yinv = DateTime.Parse(para).Year;
                        if (yinv < 2500)
                        {

                            ddate = DateTime.Parse(para).AddYears(543).ToString("yyMMdd", new CultureInfo("th-TH"));
                        }
                        else
                        {

                            ddate = DateTime.Parse(para).ToString("yyMMdd", new CultureInfo("th-TH"));
                        }
                    }
                    catch
                    {
                        int yinv = DateTime.Now.Year;
                        if (yinv < 2500)
                        {

                            ddate = DateTime.Now.AddYears(543).ToString("yyMMdd", new CultureInfo("th-TH"));
                        }
                        else
                        {

                            ddate = DateTime.Now.ToString("yyMMdd", new CultureInfo("th-TH"));
                        }


                    }

                }
                else
                {

                    int yinv = DateTime.Now.Year;
                    if (yinv < 2500)
                    {

                        ddate = ((DateTime.Now.Year) + 543).ToString().Substring(2, 2) + DateTime.Now.ToString("MMdd", new CultureInfo("th-TH"));
                    }
                    else
                    {

                        ddate = DateTime.Now.ToString("yyMMdd", new CultureInfo("th-TH"));
                    }

                }

            }
            else
            {
                if (para != "")
                {
                    try
                    {
                        int yinv = DateTime.Parse(para).Year;
                        if (yinv < 2500)
                        {

                            ddate = DateTime.Parse(para).AddYears(543).ToString("yyMM", new CultureInfo("th-TH"));
                        }
                        else
                        {

                            ddate = DateTime.Parse(para).ToString("yyMM", new CultureInfo("th-TH"));
                        }
                    }
                    catch
                    {

                        int yinv = DateTime.Now.Year;
                        if (yinv < 2500)
                        {

                            ddate = DateTime.Now.AddYears(543).ToString("yyMM", new CultureInfo("th-TH"));
                        }
                        else
                        {

                            ddate = DateTime.Now.ToString("yyMM", new CultureInfo("th-TH"));
                        }

                    }

                }
                else
                {

                    int yinv = DateTime.Now.Year;
                    if (yinv < 2500)
                    {

                        ddate = ((DateTime.Now.Year) + 543).ToString().Substring(2, 2) + DateTime.Now.ToString("MM", new CultureInfo("th-TH"));
                    }
                    else
                    {

                        ddate = DateTime.Now.ToString("yyMM", new CultureInfo("th-TH"));
                    }

                }
            }

            return ddate;
        }



        public static string ThaiBahtText(string strNumber, bool IsTrillion = false)
        {
            string BahtText = "";
            string strTrillion = "";
            string[] strThaiNumber = { "ศูนย์", "หนึ่ง", "สอง", "สาม", "สี่", "ห้า", "หก", "เจ็ด", "แปด", "เก้า", "สิบ" };
            string[] strThaiPos = { "", "สิบ", "ร้อย", "พัน", "หมื่น", "แสน", "ล้าน" };

            decimal decNumber = 0;
            decimal.TryParse(strNumber, out decNumber);

            if (decNumber == 0)
            {
                return "ศูนย์บาทถ้วน";
            }

            strNumber = decNumber.ToString("0.00");
            string strInteger = strNumber.Split('.')[0];
            string strSatang = strNumber.Split('.')[1];

            if (strInteger.Length > 13)
                throw new Exception("รองรับตัวเลขได้เพียง ล้านล้าน เท่านั้น!");

            bool _IsTrillion = strInteger.Length > 7;
            if (_IsTrillion)
            {
                strTrillion = strInteger.Substring(0, strInteger.Length - 6);
                BahtText = ThaiBahtText(strTrillion, _IsTrillion);
                strInteger = strInteger.Substring(strTrillion.Length);
            }

            int strLength = strInteger.Length;
            for (int i = 0; i < strInteger.Length; i++)
            {
                string number = strInteger.Substring(i, 1);
                if (number != "0")
                {
                    if (i == strLength - 1 && number == "1" && strLength != 1)
                    {
                        BahtText += "เอ็ด";
                    }
                    else if (i == strLength - 2 && number == "2" && strLength != 1)
                    {
                        BahtText += "ยี่";
                    }
                    else if (i != strLength - 2 || number != "1")
                    {
                        BahtText += strThaiNumber[int.Parse(number)];
                    }

                    BahtText += strThaiPos[(strLength - i) - 1];
                }
            }

            if (IsTrillion)
            {
                return BahtText + "ล้าน";
            }

            if (strInteger != "0")
            {
                BahtText += "บาท";
            }

            if (strSatang == "00")
            {
                BahtText += "ถ้วน";
            }
            else
            {
                strLength = strSatang.Length;
                for (int i = 0; i < strSatang.Length; i++)
                {
                    string number = strSatang.Substring(i, 1);
                    if (number != "0")
                    {
                        if (i == strLength - 1 && number == "1" && strSatang[0].ToString() != "0")
                        {
                            BahtText += "เอ็ด";
                        }
                        else if (i == strLength - 2 && number == "2" && strSatang[0].ToString() != "0")
                        {
                            BahtText += "ยี่";
                        }
                        else if (i != strLength - 2 || number != "1")
                        {
                            BahtText += strThaiNumber[int.Parse(number)];
                        }

                        BahtText += strThaiPos[(strLength - i) - 1];
                    }
                }

                BahtText += "สตางค์";
            }

            return BahtText;
        }


        public static string url = System.Web.HttpContext.Current.Server.MapPath("../config/config.txt");
        public static void WriteSetting(string key, string value)
        {
            // load config document for current assembly

            XmlDocument doc = null;
            try
            {
                doc = new XmlDocument();
                doc.Load(url);
               
            }
            catch (System.IO.FileNotFoundException e)
            {
                throw new Exception("No configuration file found.", e);
            }

          

            // retrieve appSettings node
            XmlNode node = doc.SelectSingleNode("//configapp");

            if (node == null)
                throw new InvalidOperationException("appSettings section not found in config file.");

            try
            {
                // select the 'add' element that contains the kzzzxcey
                XmlElement elem = (XmlElement)node.SelectSingleNode(string.Format("//add[@key='{0}']", key));

                if (elem != null)
                {
                    // add value for key
                    elem.SetAttribute("value", value);
                }
                else
                {
                    // key was not found so create the 'add' element 
                    // and set it's key/value attributes 
                    elem = doc.CreateElement("add");
                    elem.SetAttribute("key", key);
                    elem.SetAttribute("value", value);
                    node.AppendChild(elem);
                }
                doc.Save(url);
            }
            catch
            {
                throw;
            }
        }
       
        public static string GetXML(string key)
        {
            //fDecript();
            XmlDocument doc = new XmlDocument();
            doc.Load(url);
            string returnValue = string.Empty;
            //get all the elements for the specified tag
            XmlNodeList nodeList = doc.GetElementsByTagName("configapp");
            //loop through the document
            //for (int i = 0; i < nodeList.Count; i++)
            //{
            for (int i = 0; i < nodeList[0].ChildNodes.Count; i++)
            {
                //check to see if we have a match
                try
                {
                    if (nodeList[0].ChildNodes[i].Attributes[0].Value == key)
                    {
                        returnValue = nodeList[0].ChildNodes[i].Attributes[1].Value;
                        //break;
                    }
                }
                catch { };

            }

            //}
            return returnValue;
        }


    

    }
}
    