/// <summary>
 /// Delete a product on correct product.
 /// </summary>
 /// <param name="delstt"></param>
 /// <returns></returns>
 public ActionResult deleteproduct(String sttproduct)
 {
     if (!sttproduct.Equals("nothing"))
     {
         // get list product in session.
         List<ProductMap> listpro = (List<ProductMap>)Session["listproduct"];
         List<ProductMap> listerror = (List<ProductMap>)Session["listerror"];
         List<List<ProductMap>> listduplicate = (List<List<ProductMap>>)Session["listduplicate"];
         ProductMap delpro = new ProductMap();
         foreach (ProductMap p in listpro)
         {
             if (p.stt.Equals(sttproduct))
             {
                 delpro = p;
                 break;
             }
         }
         listpro.Remove(delpro);
         Session["listproduct"] = listpro;
     }
     ViewBag.listproduct = (List<ProductMap>)Session["listproduct"];
     ViewBag.listerror = (List<ProductMap>)Session["listerror"];
     ViewBag.listduplicate = (List<List<ProductMap>>)Session["listduplicate"];
     return View();
 }
        /// <summary>
        /// Tách sản phẩm khi so trùng trong database
        /// </summary>
        /// <returns></returns>
        public ActionResult tachdatabase(String valuestach)
        {
            List<List<ProductMap>> listduplicatenew = (List<List<ProductMap>>)Session["listduplicatenew"];
            String[] tachdup = valuestach.ToString().Split('@');
            ProductMap proTach = new ProductMap();
            proTach.stt = tachdup[0];
            proTach.ten = tachdup[1];
            proTach.trongso = tachdup[2];
            proTach.loai = tachdup[3];

            int count11 = 0;
            // duyệt hết list duplicate lớn
            for (int i = 0; i < listduplicatenew.Count; i++)
            {
                // duyệt từng listduplicate nhỏ
                for (int j = 0; j < listduplicatenew[i].Count; j++)
                {
                    // nếu phát hiện list nào có chứa giá trị tách trả về
                    if (proTach.stt.Equals(listduplicatenew[i][j].stt))
                    {

                        // nếu tên thành phần bị thanh đổi thì
                        if (!proTach.ten.Equals(listduplicatenew[i][j].ten))
                        {
                            //----------------------------------------------------------------------------------------
                            // lấy database ra so trùng tên mới nếu trùng cho vào list trùng mới
                            List<Hardware> listproindatabase = new List<Hardware>();
                            var resource = (from x in db.Hardwares select x);
                            listproindatabase = resource.ToList();

                          // tìm sản phẩm trùng cho vào list trùng hoặc xóa đi :|
                            for (int h = 0; h < listproindatabase.Count; h++)
                            {
                                List<ProductMap> duplicateProduct = new List<ProductMap>();
                                    String Name = "";
                                    String[] mangten = proTach.ten.ToString().Split(';');
                                    if (mangten.Length >= 2)
                                    {
                                        Name = mangten[0];
                                    }
                                    else
                                    {
                                        Name = proTach.ten;
                                    }
                                    // nếu đã có trong database rồi thì xóa đi.
                                    if (listproindatabase[h].Name.ToString().Equals(Name))
                                    {
                                        listproindatabase.RemoveAt(h);
                                        listduplicatenew.RemoveAt(i);
                                        i--;
                                        break;
                                    }

                                    // lấy sản phầm trùng cho vào list trùng mới
                                    if (CompareStringHelper.CompareString(Name, listproindatabase[h].Name.ToString()) >= 80)
                                    {
                                        count11++;
                                        ProductMap pro = new ProductMap();
                                        pro.stt = listproindatabase[h].ID.ToString();
                                        pro.ten = listproindatabase[h].Name;
                                        pro.loai = listproindatabase[h].Codetype.Name;
                                        pro.trongso = listproindatabase[h].WeightCriteraPoint.ToString();

                                        //add list dup.
                                        duplicateProduct.Add(pro);
                                        duplicateProduct.Add(proTach);
                                        listduplicatenew.RemoveAt(i);
                                        i--;
                                    }

                                if (duplicateProduct.Count >= 2)
                                {
                                    listduplicatenew.Add(duplicateProduct);
                                    Session["listduplicatenew"] = listduplicatenew;
                                    break;
                                }
                            }
                            if(count11==0){
                                Hardware p = new Hardware();
                                p.IsActive = true;
                                String[] mangten = proTach.ten.ToString().Split(';');
                                if (mangten.Length >= 2)
                                {
                                    p.Name = mangten[0];
                                }
                                else
                                {
                                    p.Name = proTach.ten;
                                }
                                p.CodetypeID = proTach.loai;
                                p.WeightCriteraPoint = Convert.ToInt32(proTach.trongso);
                                db.Hardwares.Add(p);
                                db.SaveChanges();
                                // lấy max ID và thêm vào bảng alias
                                if (mangten.Length >= 1)
                                {
                                    var pronew = db.Hardwares.OrderByDescending(pro => pro.ID).FirstOrDefault();
                                    int idinsert = Convert.ToInt32(pronew.ID);

                                    for (int h = 0; h < mangten.Length; h++)
                                    {
                                        Dictionary a = new Dictionary();
                                        a.Name = mangten[h];
                                        a.AttributeDicID = idinsert;
                                        db.Dictionaries.Add(a);
                                        db.SaveChanges();
                                    }

                                }
                                // xóa phần tử được add vào database ra khỏi list
                                listduplicatenew.RemoveAt(i);
                                i--;
                            }
                        }
                        // nếu vẫn là tên cũ thì lưu vào database
                        else
                        {
                            Hardware p = new Hardware();
                            p.IsActive = true;
                            String[] mangten = listduplicatenew[i][1].ten.ToString().Split(';');
                            if (mangten.Length >= 2)
                            {
                                p.Name = mangten[0];
                            }
                            else
                            {
                                p.Name = listduplicatenew[i][1].ten;
                            }

                            //lấy product trong database ra chỉ lấy Codetype bằng loai kiểm tra xem có trong database chưa @@.
                            List<Hardware> listproindatabase = new List<Hardware>();
                            String loai = listduplicatenew[i][1].loai;
                          var resource = (from x in db.Hardwares select x);
                         listproindatabase = resource.ToList();
                            int count = 0;
                            for (int t = 0; t < listproindatabase.Count; t++)
                            {
                                if (listproindatabase[t].Name.Equals(p.Name))
                                {
                                    count++;
                                }
                            }

                            if (count > 0)
                            {
                                listduplicatenew.RemoveAt(i);
                                Session["listduplicatenew"] = listduplicatenew;
                                break;
                            }
                            p.CodetypeID = listduplicatenew[i][1].loai;
                            p.WeightCriteraPoint = Convert.ToInt32(listduplicatenew[i][1].trongso);
                            db.Hardwares.Add(p);
                            db.SaveChanges();
                            // lấy max ID và thêm vào bảng alias
                            if (mangten.Length >= 2)
                            {
                                var pronew = db.Hardwares.OrderByDescending(pro => pro.ID).FirstOrDefault();
                                int idinsert = Convert.ToInt32(pronew.ID);

                                for (int h = 1; h < mangten.Length; h++)
                                {

                                    //lấy product trong database ra chỉ lấy Codetype bằng loai kiểm tra xem có trong database chưa @@.
                                     List<Dictionary> listmap = new List<Dictionary>();
                                    var resource1 = (from x in db.Dictionaries  select x);
                                    listmap = resource1.ToList();
                                    int count1 = 0;
                                    for (int r = 0; r < listmap.Count; r++)
                                    {
                                        if (listmap[r].Name.Equals(mangten[h]))
                                        {
                                            count1++;
                                        }
                                    }
                                    if (count1 > 0)
                                    {
                                        break;
                                    }

                                    for (int t = 0; t < listproindatabase.Count; t++)
                                    {
                                        if (listproindatabase[t].Name.Equals(p.Name))
                                        {
                                            count++;
                                        }
                                    }
                                    Dictionary a = new Dictionary();
                                    a.Name = mangten[h];
                                    a.AttributeDicID = idinsert;
                                    a.IsActive = true;
                                    db.Dictionaries.Add(a);
                                    db.SaveChanges();
                                }

                            }
                            listduplicatenew.RemoveAt(i);
                            Session["listduplicatenew"] = listduplicatenew;
                            break;
                        }
                    }
                    if (count11 > 0)
                    {
                        break;
                    }
                }
                if (count11 > 0)
                {
                    break;
                }
            }
            ViewBag.listduplicatenew = (List<List<ProductMap>>)Session["listduplicatenew"];
            return View();
        }
        public ActionResult saveAllProduct(String checkval)
        {
            // get list product in session.
            List<ProductMap> listpro = (List<ProductMap>)Session["listproduct"];
            List<ProductMap> listerror = (List<ProductMap>)Session["listerror"];
            List<List<ProductMap>> listduplicate = (List<List<ProductMap>>)Session["listduplicate"];

            //ghi logfile---------------------------------------------------------------------------------
            String[] ghilog = checkval.ToString().Split('@');

            // nếu có check  ghilog Duplicate
            #region ghilog Duplicate
            if (!ghilog[0].Equals("no")&&listduplicate!=null)
            {
                // lấy dữ liệu trong file text traning ra LapDataTraning;
                string path = Server.MapPath("~/UploadedExcelFiles/ProductName.txt");
                if (System.IO.File.Exists(path))
                {   // lấy hết dòng trong file txt ra.
                    string[] lines = System.IO.File.ReadAllLines(path);
                    // tảo mảng mới chứa dữ dữ liệu trùng.
                    string[] newlines = new string[listduplicate.Count];
                    for (int i = 0; i < listduplicate.Count; i++)
                    {
                        string newline = "";
                        for (int j = 0; j < listduplicate[i].Count; j++)
                        {
                            newline += listduplicate[i][j].ten + "|" + listduplicate[i][j].loai + "|" +
                                       listduplicate[i][j].trongso + "#";
                        }
                        newline = newline.Substring(0, newline.Length - 1);
                        newlines[i] = newline;
                    }
                    //Gộp hai bảng thành mảng mới và lưu vào txt lại
                    string[] save = new string[lines.Length + newlines.Length];
                    for (int i = 0; i < lines.Length; i++)
                    {
                        save[i] = lines[i];
                    }
                    for (int i = 0; i < newlines.Length; i++)
                    {
                        save[i + lines.Length] = newlines[i];
                    }
                    // ghi lại vào txt
                    System.IO.File.WriteAllLines(path, save);
                }

            }
            #endregion
            Session["listduplicate"] = null;
            // nếu có check ghilog Error
            if (!ghilog[1].Equals("no"))
            {
                // LogFileHelper.LogfileThanhPhanloi(listerror);
                // xóa session error

            }
            Session["listerror"] = null;

            // Tạo listduplicate mới chứa trùng giữa listpro và trong database
            List<List<ProductMap>> listduplicatenew = new List<List<ProductMap>>();

            //lấy product trong database ra chỉ lấy Codetype bằng loai.
            List<Hardware> listproindatabase = new List<Hardware>();
            var resource = (from x in db.Hardwares select x);
            listproindatabase = resource.ToList();

            // tìm sản phẩm trùng với database cho vào list trùng hoặc xóa đi :|
            for (int j = 0; j < listproindatabase.Count; j++)
            {

                List<ProductMap> duplicateProduct = new List<ProductMap>();
                for (int i = 0; i < listpro.Count; i++)
                {
                    String Name = "";
                    String[] mangten = listpro[i].ten.ToString().Split(';');
                    if (mangten.Length >= 2)
                    {
                        Name = mangten[0];
                    }
                    else
                    {
                        Name = listpro[i].ten;
                    }
                    // nếu đã có trong database rồi thì xóa đi.
                    if (listproindatabase[j].Name.Trim().ToString().Equals(Name.Trim()))
                    {
                        listproindatabase.RemoveAt(j);
                        listpro.RemoveAt(i);
                        i--;
                        j--;
                        break;
                    }

                    // lấy sản phầm trùng cho vào list trùng mới
                    if (CompareStringHelper.CompareString(Name, listproindatabase[j].Name.ToString()) >= 80)
                    {
                        ProductMap pro = new ProductMap();
                        pro.stt = listproindatabase[j].ID.ToString();
                        pro.ten = listproindatabase[j].Name;
                        pro.loai = listproindatabase[j].CodetypeID;
                        pro.trongso = listproindatabase[j].WeightCriteraPoint.ToString();

                        //add list dup.
                        duplicateProduct.Add(pro);
                        listpro[i].stt = "z" + listpro[i].stt;
                        duplicateProduct.Add(listpro[i]);
                        listpro.RemoveAt(i);
                        i--;
                    }

                }
                if (duplicateProduct.Count >= 2)
                {
                    listduplicatenew.Add(duplicateProduct);
                    Session["listduplicatenew"] = listduplicatenew;
                }
            }

            // lưu vào database
            for (int i = 0; i < listpro.Count; i++)
            {
                Hardware p = new Hardware();

                String[] mangten = listpro[i].ten.ToString().Split(';');
                if (mangten.Length >= 2)
                {
                    p.Name = mangten[0];
                }
                else
                {
                    p.Name = listpro[i].ten;
                }
                p.CodetypeID = listpro[i].loai;
                p.WeightCriteraPoint = Convert.ToInt32(listpro[i].trongso);
                p.IsActive = true;
                db.Hardwares.Add(p);
                db.SaveChanges();
                // lấy max ID và thêm vào bảng alias
                if (mangten.Length >= 1)
                {
                    var pronew = db.Hardwares.OrderByDescending(pro => pro.ID).FirstOrDefault();
                    int idinsert = Convert.ToInt32(pronew.ID);

                    for (int h = 0; h < mangten.Length; h++)
                    {
                        Dictionary a = new Dictionary();
                        a.Name = mangten[h];
                        a.AttributeDicID = idinsert;
                        a.IsActive = true;
                        db.Dictionaries.Add(a);
                        db.SaveChanges();
                    }

                }
                // xóa phần tử được add vào database ra khỏi list
                listpro.Remove(listpro[i]);
                i = i - 1;
            }
            Session["listduplicatenew"] = listduplicatenew;
            ViewBag.listduplicatenew = (List<List<ProductMap>>)Session["listduplicatenew"];
            return RedirectToAction("index");
        }
        /// <summary>
        /// Sản phẩm lỗi đã được sửa.
        /// </summary>
        /// <param name="delstt"></param>
        /// <returns></returns>
        public ActionResult fixedErrorProduct(String stringpro)
        {
            if (!stringpro.Equals("nothing"))
            {
                // get list product in session.
                List<ProductMap> listpro = (List<ProductMap>)Session["listproduct"];
                List<ProductMap> listerror = (List<ProductMap>)Session["listerror"];
                List<List<ProductMap>> listduplicate = (List<List<ProductMap>>)Session["listduplicate"];

                int count1 = listerror.Count;
                String[] info = stringpro.ToString().Split('@');
                string stt = info[0];
                string ten = info[1];
                string tronngso = info[3];
                string loai = info[2];
                // gán vào list để kiểm tra
                List<ProductMap> newlisterror = listerror;
                foreach (ProductMap p in newlisterror)
                {
                    if (p.stt.Equals(stt))
                    {
                        p.ten = ten;
                        p.trongso = tronngso;
                        p.loai = loai;
                        break;
                    }
                }
                List<ProductMap> newlisterror1 = ListErrorProduct(newlisterror);
                // gọi hàm kiểm tra lỗi và đếm xem có bao nhiêu sản phẩm lỗi
                int count2 = newlisterror1.Count;
                // nếu phát hiện số sản phẩm lỗi giảm đi 1 thì kiểm tra trùng với list pro và list dup, xóa trong list error
                if ((count1 - count2) == 1)
                {
                    // xóa sản phẩm trong list error và cập nhập vào session
                    ProductMap delpro = new ProductMap();
                    foreach (ProductMap p in listerror)
                    {
                        if (p.stt.Equals(stt))
                        {
                            delpro = p;
                            break;
                        }
                    }
                    listerror.Remove(delpro);
                    Session["listerror"] = newlisterror1;
                    // xử lý sản phẩm lỗi đã được update.
                    ProductMap update = new ProductMap();
                    update.stt = stt;
                    update.ten = ten;
                    update.trongso = tronngso;
                    update.loai = loai;

                    // so trùng với correct list và duplicate list
                    List<ProductMap> listtam = new List<ProductMap>();
                    listtam.Add(update);

                    //Duyệt hết list correct
                    for (int i = 0; i < listpro.Count; i++)
                    {
                        // nếu phát hiện trùng
                        if (CompareStringHelper.CompareString(listpro[i].ten.ToString(), update.ten) >= 80)
                        {
                            listtam.Add(listpro[i]);
                            listpro.Remove(listpro[i]);
                        }
                    }

                    //Kiểm tra xem list tạm lớn hơn 1 tức là trong correct product có trùng.
                    if (listtam.Count > 1)
                    {
                        listduplicate.Add(listtam);
                    }
                    // trong correct ko trùng thì bay qua list duplicate tìm trùng.
                    else
                    {
                        int count = 0;
                        for (int i = 0; i < listduplicate.Count; i++)
                        {
                            if (CompareStringHelper.CompareString(listduplicate[i][0].ten.ToString(), update.ten) >= 80)
                            {
                                listduplicate[i].Add(update);
                                count++;
                                break;
                            }
                        }
                        if (count == 0)
                        {
                            listpro.Add(update);
                        }

                    }
                }
                if ((count1 - count2) == 0)
                {
                    Session["listerror"] = newlisterror1;
                }
                //update listError and listDuplicate
                Session["listpro"] = listpro;
                Session["listduplicate"] = listduplicate;
            }
            // cho vào 3 list
            ViewBag.listproduct = (List<ProductMap>)Session["listproduct"];
            ViewBag.listerror = (List<ProductMap>)Session["listerror"];
            ViewBag.listduplicate = (List<List<ProductMap>>)Session["listduplicate"];

            // quá nhiều lỗi hiện thị ra dòng và sản phẩm bị lỗi.
            ViewBag.danhsachloi = (List<ProductMap>)Session["danhsachloi"];
            // dòng chứa lỗi
            ViewBag.errorLine = Session["errorLine"];
            return View();
        }
        /// <summary>
        /// Tách 1 table trùng
        /// </summary>
        /// <param name="values"></param>
        /// <returns></returns>
        public ActionResult getTach(String valuest)
        {
            if (!valuest.Equals("nothing"))
            {
                String[] tachdup = valuest.ToString().Split('*');
                if (tachdup.Length >= 3)
                {
                    tachdup = valuest.ToString().Split('@');
                    String[] tach1 = tachdup[0].Split('*');
                    List<String> valuesTach = new List<String>();
                    for (int j = 1; j < tach1.Length; j++)
                    {
                        valuesTach.Add(tach1[j]);
                    }

                    // get list product in session.
                    List<ProductMap> listpro = (List<ProductMap>)Session["listproduct"];
                    List<ProductMap> listerror = (List<ProductMap>)Session["listerror"];
                    List<List<ProductMap>> listduplicate = (List<List<ProductMap>>)Session["listduplicate"];
                    ProductMap duplicate = new ProductMap();
                    int count = 0;
                    for (int i = 0; i < listduplicate.Count; i++)
                    {
                        if (count > 0)
                        {
                            break;
                        }
                        for (int j = 0; j < listduplicate[i].Count; j++)
                        {
                            // duyệt để tim thấy list có chưa id tách được gửi về.
                            if (count > 0)
                            {
                                break;
                            }
                            List<ProductMap> duplicateProduct = new List<ProductMap>();
                            for (int t = 0; t < valuesTach.Count; t++)
                            {
                                if (listduplicate[i][j].stt.ToString().Equals(valuesTach[t].ToString()))
                                {
                                    duplicateProduct.Add(listduplicate[i][j]);
                                    listduplicate[i].Remove(listduplicate[i][j]);
                                    count++;
                                }
                            }
                            if (duplicateProduct.Count > 0)
                            {
                                listduplicate.Add(duplicateProduct);
                            }
                            // kiểm tra trong list nhỏ còn có 1 phần tử thì tách nó luôn cho vào list correct
                            if (listduplicate[i].Count == 1)
                            {
                                listpro.Add(listduplicate[i].First());
                                listduplicate[i].Remove(listduplicate[i].First());
                                //Xóa list rỗng trong list bự duplicate
                                listduplicate.Remove(listduplicate[i]);
                                count++;
                                break;

                            }
                            else if (listduplicate[i].Count == 0)
                            {
                                //Xóa list rỗng trong list bự duplicate
                                listduplicate.Remove(listduplicate[i]);
                                count++;
                                break;
                            }

                        }

                    }

                    Session["listerror"] = listerror;
                    Session["listduplicate"] = listduplicate;

                    Session["listproduct"] = listpro;
                }
                else
                {

                    List<String> valuesTach = new List<String>();
                    String[] value = tachdup[0].ToString().Split('@');
                    for (int j = 1; j < value.Length; j++)
                    {
                        valuesTach.Add(value[j]);
                    }

                    // get list product in session.
                    List<ProductMap> listpro = (List<ProductMap>)Session["listproduct"];
                    List<ProductMap> listerror = (List<ProductMap>)Session["listerror"];
                    List<List<ProductMap>> listduplicate = (List<List<ProductMap>>)Session["listduplicate"];
                    ProductMap duplicate = new ProductMap();
                    int count = 0;
                    for (int i = 0; i < listduplicate.Count; i++)
                    {
                        for (int j = 0; j < listduplicate[i].Count; j++)
                        {
                            // duyệt để tim thấy list có chưa id tách được gửi về.
                            for (int t = 0; t < valuesTach.Count; t++)
                            {
                                if (listduplicate[i][j].stt.ToString().Equals(valuesTach[t].ToString()))
                                {
                                    listpro.Add(listduplicate[i][j]);
                                    listduplicate[i].Remove(listduplicate[i][j]);

                                }
                            }

                            // kiểm tra trong list nhỏ còn có 1 phần tử thì tách nó luôn cho vào list correct
                            if (listduplicate[i].Count == 1)
                            {
                                listpro.Add(listduplicate[i].First());
                                listduplicate[i].Remove(listduplicate[i].First());
                                //Xóa list rỗng trong list bự duplicate
                                listduplicate.Remove(listduplicate[i]);
                                count++;
                                break;

                            }
                            else if (listduplicate[i].Count == 0)
                            {
                                //Xóa list rỗng trong list bự duplicate
                                listduplicate.Remove(listduplicate[i]);
                                count++;
                                break;
                            }
                        }
                        if (count > 0)
                        {
                            break;
                        }
                    }

                    Session["listerror"] = listerror;
                    Session["listduplicate"] = listduplicate;

                    Session["listproduct"] = listpro;
                }
            }
            //cho vào viewbag
            ViewBag.listproduct = (List<ProductMap>)Session["listproduct"];
            ViewBag.listerror = (List<ProductMap>)Session["listerror"];
            ViewBag.listduplicate = (List<List<ProductMap>>)Session["listduplicate"];

            return View();
        }
        /// <summary>
        /// Gộp 1 table trùng
        /// </summary>
        /// <param name="values"></param>
        /// <returns></returns>
        public ActionResult getGop(String valuest)
        {
            List<String> values = new List<String>();
            String[] value = valuest.ToString().Split('@');
            for (int j = 1; j < value.Length; j++)
            {
                values.Add(value[j]);
            }
            List<ProductMap> listpro = (List<ProductMap>)Session["listproduct"];
            List<ProductMap> listerror = (List<ProductMap>)Session["listerror"];
            List<List<ProductMap>> listduplicate = (List<List<ProductMap>>)Session["listduplicate"];

            // lấy tên chính ở cuối list ra và remove
            string sttTenchinh = values.Last();
            values.Remove(values.Last());

            // value chỉ chứa các giá trị khác ngoài tên chính
            for (int t = 0; t < values.Count; t++)
            {
                if (values[t].Trim().Equals(sttTenchinh.Trim()))
                {
                    values.RemoveAt(t);
                    break;
                }
            }

            // tên sản phẩm gộp
            string tenmoi = "";
            ProductMap sanphamgop = new ProductMap();

            int count = 0;
            for (int i = 0; i < listduplicate.Count; i++)
            {
                // duyệt list nhỏ
                for (int j = 0; j < listduplicate[i].Count; j++)
                {
                    // nếu stt của listdup = stt của tên chính thì cho nó thành sản phẩm gộp.
                    if (listduplicate[i][j].stt.ToString().Equals(sttTenchinh))
                    {
                        count++;
                        tenmoi = listduplicate[i][j].ten;
                        sanphamgop = listduplicate[i][j];
                        listduplicate[i].Remove(listduplicate[i][j]);
                    }
                    if (count > 0)
                    {

                        break;
                    }
                }
                if (count > 0)
                {

                    break;
                }
            }
            // duyệt để tim thấy list có chưa id tách được gửi về.
            for (int t = 0; t < values.Count; t++)
            {
                // duyệt list bự lấy tên phụ
                for (int i = 0; i < listduplicate.Count; i++)
                {
                    // duyệt list nhỏ
                    for (int j = 0; j < listduplicate[i].Count; j++)
                    {

                        // nếu stt của listdup = stt của tên chính thì cho nó thành sản phẩm gộp.
                        if (listduplicate[i][j].stt.ToString().Equals(values[t]))
                        {

                            tenmoi += ";" + listduplicate[i][j].ten;
                            listduplicate[i].Remove(listduplicate[i][j]);
                            break;
                        }
                    }
                }
            }
            // duyệt list bự xóa list rỗng hoặc list có 1 phần tử cho vào phần tử đúng
            for (int i = 0; i < listduplicate.Count; i++)
            {
                // kiểm tra trong list nhỏ còn có 1 phần tử thì tách nó luôn cho vào list correct
                if (listduplicate[i].Count == 1)
                {
                    listpro.Add(listduplicate[i].First());
                    listduplicate[i].Remove(listduplicate[i].First());
                    //Xóa list rỗng trong list bự duplicate
                    listduplicate.Remove(listduplicate[i]);
                }
                else if (listduplicate[i].Count == 0)
                {
                    //Xóa list rỗng trong list bự duplicate
                    listduplicate.Remove(listduplicate[i]);
                }
            }

            sanphamgop.ten = tenmoi;
            listpro.Add(sanphamgop);
            Session["listproduct"] = listpro;
            Session["listerror"] = listerror;
            Session["listduplicate"] = listduplicate;
            ViewBag.listproduct = (List<ProductMap>)Session["listproduct"];
            ViewBag.listerror = (List<ProductMap>)Session["listerror"];
            ViewBag.listduplicate = (List<List<ProductMap>>)Session["listduplicate"];

            //    Json(new { Result = String.Format("Fist item in list: '{0}'", values[0]) });
            return View();
        }
        //Load thành phần trùng với database từ txt
        public List<List<ProductMap>> LoadThanhPhanTrungDB()
        {
            // Thành phần trùng với thành phần trong database
             #region load sản phẩm trùng từ txt LapDataTraning
             string path = Server.MapPath("~/UploadedExcelFiles/ProductNameTraining.txt");
             List<List<ProductMap>> Listduptraning = new List<List<ProductMap>>();
             List<String> listID = new List<String>();
             if (System.IO.File.Exists(path))
             {
                 int h = 999;
                 string[] lines = System.IO.File.ReadAllLines(path);

                 int sttp = 0;
                 for (int i = 0; i < lines.Length; i++)
                 {
                     if (!String.IsNullOrWhiteSpace(lines[i].Trim()))
                     {
                         h++;
                         List<ProductMap> duppro = new List<ProductMap>();
                         string[] seperators = { "~", "#" };
                         // tách ra làm 3 phần tử.
                         String[] line = lines[i].Split(seperators, StringSplitOptions.RemoveEmptyEntries);
                         // cho id vào list ID
                         string productId = line[0];
                         // tên sản phẩm đã có trong database
                         string[] produc1 = line[1].Split('|');
                         ProductMap p1 = new ProductMap();
                         p1.stt = produc1[3];
                         p1.ten = produc1[0];
                         p1.loai = produc1[1];
                         p1.trongso = produc1[2];
                         p1.productid = line[0];
                         duppro.Add(p1);
                         // tên product bị trùng với product đã có trong database
                         string[] produc2 = line[2].Split('|');
                         ProductMap p2 = new ProductMap();
                         p2.stt = sttp.ToString() + 'z';
                         sttp++;
                         p2.ten = produc2[0];
                         p2.loai = produc1[1];

                         if (produc2[2].Equals(""))
                         {
                             p2.trongso = "0";
                         }
                         else
                         {
                             p2.trongso = produc2[2];
                         }
                         p2.productid = line[0];
                         duppro.Add(p2);

                         Listduptraning.Add(duppro);

                     }
                 }
             }
             #endregion
             return Listduptraning;
        }
        //LoadThanhPhanTrung từ txt
        public List<List<ProductMap>> LoadThanhPhanTrung()
        {
            #region load sản phẩm trùng từ txt LapDataTraning
            string path1 = Server.MapPath("~/UploadedExcelFiles/ProductName.txt");
            List<List<ProductMap>> ListdupProductTraning = new List<List<ProductMap>>();
            if (System.IO.File.Exists(path1))
            {
                int h = 0;
                string[] lines = System.IO.File.ReadAllLines(path1);
                for (int i = 0; i < lines.Length; i++)
                {
                    if (!String.IsNullOrWhiteSpace(lines[i].Trim()))
                    {
                        List<ProductMap> duppro = new List<ProductMap>();
                        String[] line = lines[i].Split('#');
                        for (int j = 0; j < line.Length; j++)
                        {
                            h++;
                            String[] Atrr = line[j].Split('|');
                            ProductMap pro = new ProductMap();
                            pro.stt = h.ToString();
                            pro.ten = Atrr[0];
                            pro.loai = Atrr[1];
                            pro.trongso = Atrr[2];
                            duppro.Add(pro);

                        }
                        ListdupProductTraning.Add(duppro);
                    }
                }
            }
            #endregion
            return ListdupProductTraning;
        }
        /// <summary>
        /// Gộp 1 table trùng
        /// </summary>
        /// <param name="values"></param>
        /// <returns></returns>
        public ActionResult getGop(String valuest)
        {
            List<String> values = new List<String>();
            String[] value = valuest.ToString().Split('@');
            for (int j = 1; j < value.Length; j++)
            {
                values.Add(value[j]);
            }
            List<List<ProductMap>> listduplicate = (List<List<ProductMap>>)Session["ListdupProduct"];
            // tạo list chứa sản phẩm để lưu hoặc so trùng với db
            List<ProductMap> listpro = new List<ProductMap>();
            // lấy tên chính ở cuối list ra và remove
            string sttTenchinh = values.Last();
            values.Remove(values.Last());

            // value chỉ chứa các giá trị khác ngoài tên chính
            for (int t = 0; t < values.Count; t++)
            {
                if (values[t].Trim().Equals(sttTenchinh.Trim()))
                {
                    values.RemoveAt(t);
                    break;
                }
            }

            // tên sản phẩm gộp
            string tenmoi = "";
            string tenchinh = "";
            ProductMap sanphamgop = new ProductMap();
            int check = 0;
            int count = 0;
            for (int i = 0; i < listduplicate.Count; i++)
            {
                // duyệt list nhỏ
                for (int j = 0; j < listduplicate[i].Count; j++)
                {
                    // nếu stt của listdup = stt của tên chính thì cho nó thành sản phẩm gộp.
                    if (listduplicate[i][j].stt.ToString().Equals(sttTenchinh))
                    {
                        count++;
                        tenmoi = listduplicate[i][j].ten;
                        tenchinh = listduplicate[i][j].ten;
                        sanphamgop = listduplicate[i][j];
                        listduplicate[i].Remove(listduplicate[i][j]);
                    }
                    if (count > 0)
                    {

                        break;
                    }
                }
                if (count > 0)
                {

                    break;
                }
            }
            // duyệt để tim thấy list có chưa id tách được gửi về.
            for (int t = 0; t < values.Count; t++)
            {
                // duyệt list bự lấy tên phụ
                for (int i = 0; i < listduplicate.Count; i++)
                {
                    // duyệt list nhỏ
                    for (int j = 0; j < listduplicate[i].Count; j++)
                    {

                        // nếu stt của listdup = stt của tên chính thì cho nó thành sản phẩm gộp.
                        if (listduplicate[i][j].stt.ToString().Equals(values[t]))
                        {

                            tenmoi += ";" + listduplicate[i][j].ten;
                            listduplicate[i].Remove(listduplicate[i][j]);
                            break;
                        }
                    }
                }
            }
            // duyệt list bự xóa list rỗng hoặc list có 1 phần tử cho vào phần tử đúng
            for (int i = 0; i < listduplicate.Count; i++)
            {
                // kiểm tra trong list nhỏ còn có 1 phần tử thì tách nó luôn cho vào list correct
                if (listduplicate[i].Count == 1)
                {
                    listpro.Add(listduplicate[i].First());
                    listduplicate[i].Remove(listduplicate[i].First());
                    //Xóa list rỗng trong list bự duplicate
                    listduplicate.Remove(listduplicate[i]);
                }
                else if (listduplicate[i].Count == 0)
                {
                    //Xóa list rỗng trong list bự duplicate
                    listduplicate.Remove(listduplicate[i]);
                }
            }

            sanphamgop.ten = tenmoi;
            // cho vào listpro
            listpro.Add(sanphamgop);
            // Tạo listduplicate mới chứa trùng giữa listpro và trong database
            List<List<ProductMap>> listduplicatenew = new List<List<ProductMap>>();

            //lấy product trong database ra chỉ lấy Codetype bằng loai.
            List<Hardware> listproindatabase = new List<Hardware>();
            String loai = sanphamgop.loai;
            var resource = (from x in db.Hardwares select x);
            listproindatabase = resource.ToList();

            // tìm sản phẩm trùng cho vào list trùng hoặc xóa đi :|
            for (int j = 0; j < listproindatabase.Count; j++)
            {
                for (int i = 0; i < listpro.Count; i++)
                {
                    List<ProductMap> duplicateProduct = new List<ProductMap>();

                    String Name = "";
                    String[] mangten = listpro[i].ten.ToString().Split(';');
                    if (mangten.Length >= 2)
                    {
                        Name = mangten[0];
                    }
                    else
                    {
                        Name = listpro[i].ten;
                    }

                    if (listproindatabase[j].Name.ToString().Equals(Name))
                    {
                        listproindatabase.RemoveAt(j);

                        j--;
                    }

                    // lấy sản phầm trùng cho vào list trùng mới
                    if (CompareStringHelper.CompareString(tenchinh, listproindatabase[j].Name.ToString()) >= 80)
                    {
                        ProductMap pro = new ProductMap();
                        pro.stt = listproindatabase[j].ID.ToString();
                        pro.ten = listproindatabase[j].Name;
                        pro.loai = listproindatabase[j].CodetypeID;
                        pro.trongso = listproindatabase[j].WeightCriteraPoint.ToString();
                        duplicateProduct.Add(pro);
                        listpro[i].stt = "z" + listpro[i].stt;
                        duplicateProduct.Add(listpro[i]);
                        listpro.RemoveAt(i);
                        i = i--;
                        //lấy dữ liệu trong file text traning ra ProductNameTraining;
                        string path1 = Server.MapPath("~/UploadedExcelFiles/ProductNameTraining.txt");
                        if (System.IO.File.Exists(path1))
                        {   // lấy hết dòng trong file txt ra.
                            string[] lines1 = System.IO.File.ReadAllLines(path1);
                            // tảo mảng mới chứa dữ dữ liệu trùng.
                            string[] newlines = new string[1];
                            string newline = "0" + '~';
                            for (int h = 0; h < duplicateProduct.Count; h++)
                            {
                                newline += duplicateProduct[h].ten + "|" + duplicateProduct[h].loai + "|" +
                                           duplicateProduct[h].trongso + "|" + duplicateProduct[h].stt + "#";
                            }
                            newline = newline.Substring(0, newline.Length - 1);
                            newlines[0] = newline;
                            //Gộp hai bảng thành mảng mới và lưu vào txt lại
                            string[] save = new string[lines1.Length + newlines.Length];
                            for (int h = 0; h < lines1.Length; h++)
                            {
                                save[h] = lines1[h];
                            }
                            for (int h = 0; h < newlines.Length; h++)
                            {
                                save[h + lines1.Length] = newlines[h];
                            }
                            // ghi lại vào txt
                            System.IO.File.WriteAllLines(path1, save);
                        }
                    }

                    if (duplicateProduct.Count >= 2)
                    {

                        listduplicatenew.Add(duplicateProduct);
                        check++;
                    }
                }
            }

            // lưu vào database
            if (check == 0)
            {
                Hardware p = new Hardware();

                String[] mangten = sanphamgop.ten.ToString().Split(';');
                if (mangten.Length >= 2)
                {
                    p.Name = mangten[0];
                }
                else
                {
                    p.Name = sanphamgop.ten;
                }
                p.CodetypeID = sanphamgop.loai;
                p.WeightCriteraPoint = Convert.ToInt32(sanphamgop.trongso);
                db.Hardwares.Add(p);
                db.SaveChanges();
                // lấy max ID và thêm vào bảng alias
                if (mangten.Length >= 1)
                {
                    var pronew = db.Hardwares.OrderByDescending(pro => pro.ID).FirstOrDefault();
                    int idinsert = Convert.ToInt32(pronew.ID);

                    for (int h = 0; h < mangten.Length; h++)
                    {
                        Dictionary a = new Dictionary();
                        a.Name = mangten[h];
                        a.AttributeDicID = idinsert;
                        a.IsActive = true;
                        db.Dictionaries.Add(a);
                        db.SaveChanges();
                    }

                }
            }

            // ghi lại vào txt
            string path = Server.MapPath("~/UploadedExcelFiles/ProductName.txt");
            string[] lines = new string[listduplicate.Count];
            for (int i = 0; i < listduplicate.Count; i++)
            {
                string line = "";
                for (int j = 0; j < listduplicate[i].Count; j++)
                {
                    line += listduplicate[i][j].ten + "|" + listduplicate[i][j].loai + "|" + listduplicate[i][j].trongso + "#";
                }
                line = line.Substring(0, line.Length - 1);
                lines[i] = line;

            }
            System.IO.File.WriteAllLines(path, lines);
            Session["ListdupProduct"] = listduplicate;
            ViewBag.ListdupProduct = (List<List<ProductMap>>)Session["ListdupProduct"];

            //    Json(new { Result = String.Format("Fist item in list: '{0}'", values[0]) });
            return View();
        }
        /// <summary>
        /// Tách 1 table trùng
        /// </summary>
        /// <param name="values"></param>
        /// <returns></returns>
        public ActionResult getTach(String valuest)
        {
            if (!valuest.Equals("nothing"))
            {
                String[] tachdup = valuest.ToString().Split('*');
                if (tachdup.Length >= 3)
                {
                    tachdup = valuest.ToString().Split('@');
                    String[] tach1 = tachdup[0].Split('*');
                    List<String> valuesTach = new List<String>();
                    for (int j = 1; j < tach1.Length; j++)
                    {
                        valuesTach.Add(tach1[j]);
                    }

                    // get list product in session.
                    List<ProductMap> listpro = new List<ProductMap>(); ;
                    List<List<ProductMap>> listduplicate = (List<List<ProductMap>>)Session["ListdupProduct"];
                    ProductMap duplicate = new ProductMap();
                    int count = 0;
                    for (int i = 0; i < listduplicate.Count; i++)
                    {
                        if (count > 0)
                        {
                            break;
                        }
                        for (int j = 0; j < listduplicate[i].Count; j++)
                        {
                            // duyệt để tim thấy list có chưa id tách được gửi về.
                            if (count > 0)
                            {
                                break;
                            }
                            List<ProductMap> duplicateProduct = new List<ProductMap>();
                            for (int t = 0; t < valuesTach.Count; t++)
                            {
                                if (listduplicate[i][j].stt.ToString().Equals(valuesTach[t].ToString()))
                                {
                                    duplicateProduct.Add(listduplicate[i][j]);
                                    listduplicate[i].Remove(listduplicate[i][j]);
                                    count++;
                                }
                            }
                            if (duplicateProduct.Count > 0)
                            {
                                listduplicate.Add(duplicateProduct);
                            }
                            // kiểm tra trong list nhỏ còn có 1 phần tử thì tách nó luôn cho vào list correct
                            if (listduplicate[i].Count == 1)
                            {
                                listpro.Add(listduplicate[i].First());
                                listduplicate[i].Remove(listduplicate[i].First());
                                //Xóa list rỗng trong list bự duplicate
                                listduplicate.Remove(listduplicate[i]);
                                count++;
                                break;

                            }
                            else if (listduplicate[i].Count == 0)
                            {
                                //Xóa list rỗng trong list bự duplicate
                                listduplicate.Remove(listduplicate[i]);
                                count++;
                                break;
                            }
                        }
                    }
                    Session["ListdupProduct"] = listduplicate;
                }
                else
                {

                    List<String> valuesTach = new List<String>();
                    String[] value = tachdup[0].ToString().Split('@');
                    for (int j = 1; j < value.Length; j++)
                    {
                        valuesTach.Add(value[j]);
                    }

                    // get list product in session.
                    List<ProductMap> listpro = new List<ProductMap>();
                    List<List<ProductMap>> listduplicate = (List<List<ProductMap>>)Session["ListdupProduct"];
                    ProductMap duplicate = new ProductMap();
                    int count = 0;
                    for (int i = 0; i < listduplicate.Count; i++)
                    {
                        for (int j = 0; j < listduplicate[i].Count; j++)
                        {
                            // duyệt để tim thấy list có chưa id tách được gửi về.
                            for (int t = 0; t < valuesTach.Count; t++)
                            {
                                if (listduplicate[i][j].stt.ToString().Equals(valuesTach[t].ToString()))
                                {
                                    listpro.Add(listduplicate[i][j]);
                                    listduplicate[i].Remove(listduplicate[i][j]);

                                }
                            }

                            // kiểm tra trong list nhỏ còn có 1 phần tử thì tách nó luôn cho vào list correct
                            if (listduplicate[i].Count == 1)
                            {
                                listpro.Add(listduplicate[i].First());
                                listduplicate[i].Remove(listduplicate[i].First());
                                //Xóa list rỗng trong list bự duplicate
                                listduplicate.Remove(listduplicate[i]);
                                count++;
                                break;

                            }
                            else if (listduplicate[i].Count == 0)
                            {
                                //Xóa list rỗng trong list bự duplicate
                                listduplicate.Remove(listduplicate[i]);
                                count++;
                                break;
                            }
                        }
                        if (count > 0)
                        {
                            break;
                        }
                    }

                    //kiểm tra listpro có bị trùng database ko nếu bị trùng thì lưu vào ProductNameTraining

                    List<List<ProductMap>> listduplicatenew = new List<List<ProductMap>>();
                    //lấy product trong database ra chỉ lấy Codetype bằng loai.
                    List<Hardware> listproindatabase = new List<Hardware>();

                    var resource = (from x in db.Hardwares select x);
                    listproindatabase = resource.ToList();

                    // tìm sản phẩm trùng cho vào list trùng hoặc xóa đi :|
                    for (int j = 0; j < listproindatabase.Count; j++)
                    {
                        for (int i = 0; i < listpro.Count; i++)
                        {
                            List<ProductMap> duplicateProduct = new List<ProductMap>();

                            String Name = "";
                            String[] mangten = listpro[i].ten.ToString().Split(';');
                            if (mangten.Length >= 2)
                            {
                                Name = mangten[0];
                            }
                            else
                            {
                                Name = listpro[i].ten;
                            }

                            if (listproindatabase[j].Name.ToString().Equals(Name))
                            {
                                listproindatabase.RemoveAt(j);

                                j--;
                            }

                            // lấy sản phầm trùng cho vào list trùng mới
                            if (CompareStringHelper.CompareString(Name, listproindatabase[j].Name.ToString()) >= 80)
                            {
                                ProductMap pro = new ProductMap();
                                pro.stt = listproindatabase[j].ID.ToString();
                                pro.ten = listproindatabase[j].Name;
                                pro.loai = listproindatabase[j].Codetype.Name;
                                pro.trongso = listproindatabase[j].WeightCriteraPoint.ToString();
                                duplicateProduct.Add(pro);
                                listpro[i].stt = "z" + listpro[i].stt;
                                duplicateProduct.Add(listpro[i]);
                                listpro.RemoveAt(i);
                                i = i--;

                                //lấy dữ liệu trong file text traning ra ProductNameTraining;
                                string path1 = Server.MapPath("~/UploadedExcelFiles/ProductNameTraining.txt");
                                if (System.IO.File.Exists(path1))
                                {   // lấy hết dòng trong file txt ra.
                                    string[] lines1 = System.IO.File.ReadAllLines(path1);
                                    // tảo mảng mới chứa dữ dữ liệu trùng.
                                    string[] newlines = new string[1];
                                    string newline = "0" + '~';
                                    for (int h = 0; h < duplicateProduct.Count; h++)
                                    {
                                        newline += duplicateProduct[h].ten + "|" + duplicateProduct[h].loai + "|" +
                                                   duplicateProduct[h].trongso + "|" + duplicateProduct[h].stt + "#";
                                    }
                                    newline = newline.Substring(0, newline.Length - 1);
                                    newlines[0] = newline;
                                    //Gộp hai bảng thành mảng mới và lưu vào txt lại
                                    string[] save = new string[lines1.Length + newlines.Length];
                                    for (int h = 0; h < lines1.Length; h++)
                                    {
                                        save[h] = lines1[h];
                                    }
                                    for (int h = 0; h < newlines.Length; h++)
                                    {
                                        save[h + lines1.Length] = newlines[h];
                                    }
                                    // ghi lại vào txt
                                    System.IO.File.WriteAllLines(path1, save);
                                }
                            }

                            if (duplicateProduct.Count >= 2)
                            {
                                listduplicatenew.Add(duplicateProduct);
                            }

                        }
                    }
                    Session["ListdupProduct"] = listduplicate;
                    // ghi lại vào txt
                    string path = Server.MapPath("~/UploadedExcelFiles/ProductName.txt");
                    string[] lines = new string[listduplicate.Count];
                    for (int a = 0; a < listduplicate.Count; a++)
                    {
                        string line = "";
                        for (int b = 0; b < listduplicate[a].Count; b++)
                        {
                            line += listduplicate[a][b].ten + "|" + listduplicate[a][b].loai + "|" + listduplicate[a][b].trongso + "#";
                        }
                        line = line.Substring(0, line.Length - 1);
                        lines[a] = line;
                    }
                    System.IO.File.WriteAllLines(path, lines);

                }
            }

            //cho vào viewbag
            ViewBag.listproduct = (List<ProductMap>)Session["listproduct"];
            ViewBag.ListdupProduct = (List<List<ProductMap>>)Session["ListdupProduct"];

            return View();
        }