using CallCenter.Utility;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers.visit
{
    public class VisitInputController : BaseController
    {
        int vfileid = 0;
        // 导入号码读取填入数据库
        public ActionResult TelInput()
        {
            DataTable dtres = new DataTable();
            string errres = "";
            int i = 0;
            int count = 0;//导入成功的条数
            string Excelsource = "";
            int rcount = 0;
            int ccount = 0;
            System.Text.StringBuilder strBuilder = null;
            //Excelsource = Server.MapPath(this.Request.ApplicationPath + "\\ExcelData\\") + filename.ToString();
            Excelsource = uploadexcel();
            #region 将文件中的数据导入数据库

            try
            {

                //************************将文件中的数据导入数据库*************************//
                DataSet dt = ReadEcxel(Excelsource, 0);
                try
                {
                    if (dt != null && dt.Tables[0].Rows.Count != 0)
                    {
                        rcount = dt.Tables[0].Rows.Count;
                        ccount = dt.Tables[0].Columns.Count;
                        strBuilder = new System.Text.StringBuilder();//用于如果导入失败，删除已经导入过的

                        DataTable dtInputData = dt.Tables[0];//要导入的电话号码
                        List<string> sqlList = new List<string>();
                        List<string> lstsql = new List<string>();
                        int ilns = dt.Tables[0].Columns.Count;
                        DataSet dsnew = new DataSet();


                        #region MyRegion
                        using (SqlConnection coon = new SqlConnection(DbHelperSQL.connectionString))
                        {
                            try
                            {
                                coon.Open();
                                int colscount = dtInputData.Columns.Count;//列数
                                int rowscount = dtInputData.Rows.Count;//行数

                                Model.T_Vis_Telphone modelPhoneImport = new Model.T_Vis_Telphone();

                                Model.T_Vis_TelAllot modelTelAllot = new Model.T_Vis_TelAllot();
                                modelTelAllot.F_CreateDate = DateTime.Now;
                                modelTelAllot.F_CreateUserID = CurrentUser.UserData.F_UserId;
                                modelTelAllot.F_CreateUserName = CurrentUser.UserData.F_UserName;
                                modelTelAllot.F_state = 0;

                                modelPhoneImport.F_InputDate = System.DateTime.Now;
                                modelPhoneImport.F_ISAllot = false;
                                modelPhoneImport.F_ISVis = false;

                                modelPhoneImport.F_InputUserID = CurrentUser.UserData.F_UserId;
                                modelPhoneImport.F_InputUserName = CurrentUser.UserData.F_UserName;

                                modelPhoneImport.F_FileID = vfileid;
                                if (rowscount > 0)
                                {
                                    foreach (DataRow dr in dtInputData.Rows)
                                    {
                                        sqlList.Clear();
                                        lstsql.Clear();
                                        if (dr[2].ToString() != "")
                                        {
                                            string dddddd = dr[2].ToString();
                                            #region 导入表内容
                                            //大区    店面	出厂日期	接车员	车牌号码	品牌	车型	客户名称	手机	固定电话
                                            //维修类别	调查日期	班组得分	接车员得分	环检	整体	合计	备注	
                                            //回访结果	详细内容	是否成功	维修项目	班组	机电	钣金	喷漆	
                                            //维修工	工单号	新客户
                                            #region 保存字段
                                            modelPhoneImport.F_Sheng = dr[0].ToString();//大区
                                            modelPhoneImport.F_Store = dr[1].ToString();//店面
                                            modelPhoneImport.F_Prodate = Convert.ToDateTime(dr[2].ToString()).ToString("yyyy-MM-dd");//出厂日期
                                            modelPhoneImport.F_Reciver = dr[3].ToString();//接车员
                                            modelPhoneImport.F_License = dr[4].ToString();//车牌号码
                                            modelPhoneImport.F_Brand = dr[5].ToString();//品牌
                                            modelPhoneImport.F_Models = dr[6].ToString();//车型
                                            modelPhoneImport.F_CusName = dr[7].ToString();//客户名称
                                            modelPhoneImport.F_CusTelphone = dr[8].ToString();//手机
                                            modelPhoneImport.F_CusPhone = dr[9].ToString();//固定电话
                                            modelPhoneImport.F_RepType = dr[10].ToString();//维修类别
                                            modelPhoneImport.F_SurveyDate = dr[11].ToString();//调查日期
                                            modelPhoneImport.F_TScore = dr[12].ToString();//班组得分
                                            modelPhoneImport.F_RScore = dr[13].ToString();//接车员得分
                                            modelPhoneImport.F_RingS = dr[14].ToString();//环检
                                            modelPhoneImport.F_WholeS = dr[15].ToString();//整体
                                            modelPhoneImport.F_TotalS = dr[16].ToString();//合计
                                            modelPhoneImport.F_Remark = dr[17].ToString();//备注
                                            modelPhoneImport.F_VisResult = dr[18].ToString();//回访结果
                                            modelPhoneImport.F_VisInfo = dr[19].ToString();//详细内容
                                            modelPhoneImport.F_VisIS = dr[20].ToString();//是否成功
                                            modelPhoneImport.F_RepItem = dr[21].ToString();//维修项目
                                            modelPhoneImport.F_TheTeam = dr[22].ToString();//班组
                                            modelPhoneImport.F_Elect = dr[23].ToString();//班机电组
                                            modelPhoneImport.F_Sheetmetal = dr[24].ToString();//钣金
                                            modelPhoneImport.F_Paint = dr[25].ToString();//喷漆
                                            modelPhoneImport.F_RepUser = dr[26].ToString();//维修工
                                            modelPhoneImport.F_WoNumber = dr[27].ToString();//工单号
                                            modelPhoneImport.F_NewCus = dr[28].ToString();//新客户
                                            #endregion
                                            #region 扩展字段
                                            modelPhoneImport.F_Extend1 = dr[29].ToString();
                                            modelPhoneImport.F_Extend2 = dr[30].ToString();
                                            modelPhoneImport.F_Extend3 = dr[32].ToString();
                                            modelPhoneImport.F_Extend4 = dr[33].ToString();
                                            modelPhoneImport.F_Extend5 = dr[34].ToString();
                                            modelPhoneImport.F_Extend6 = dr[35].ToString();
                                            modelPhoneImport.F_Extend7 = dr[36].ToString();
                                            modelPhoneImport.F_Extend8 = dr[37].ToString();
                                            modelPhoneImport.F_Extend9 = dr[38].ToString();
                                            modelPhoneImport.F_Extend10 = dr[39].ToString();
                                            modelPhoneImport.F_Extend11 = dr[40].ToString();
                                            modelPhoneImport.F_Extend12 = dr[41].ToString();
                                            modelPhoneImport.F_Extend13 = dr[42].ToString();
                                            modelPhoneImport.F_Extend14 = dr[43].ToString();
                                            modelPhoneImport.F_Extend15 = dr[44].ToString();
                                            modelPhoneImport.F_Extend16 = dr[45].ToString();
                                            modelPhoneImport.F_Extend17 = dr[46].ToString();
                                            modelPhoneImport.F_Extend18 = dr[47].ToString();
                                            modelPhoneImport.F_Extend19 = dr[48].ToString();
                                            modelPhoneImport.F_Extend20 = dr[49].ToString();
                                            #endregion

                                            #endregion

                                            int rmw = new BLL.T_Vis_Telphone().Add(modelPhoneImport);
                                            if (rmw > 0)
                                            {
                                                Model.T_Vis_TelBZ bzmodel = new Model.T_Vis_TelBZ();
                                                bzmodel.F_Score = dr[12].ToString();
                                                bzmodel.F_Sheng = dr[0].ToString();
                                                bzmodel.F_Store = dr[1].ToString();
                                                bzmodel.F_Telid = rmw;
                                                string bz = "";
                                                #region
                                                if (dr[22].ToString() != "")
                                                {
                                                    bz += dr[22].ToString() + "/";
                                                }
                                                if (dr[23].ToString() != "")
                                                {
                                                    bz += dr[23].ToString() + "/";
                                                }
                                                if (dr[24].ToString() != "")
                                                {
                                                    bz += dr[24].ToString() + "/";
                                                }
                                                if (dr[25].ToString() != "")
                                                {
                                                    bz += dr[25].ToString() + "/";
                                                }
                                                #endregion

                                                string[] arrbz = bz.Trim('/').Split('/');
                                                string[] arrn = arrbz.Distinct().ToArray();
                                                for (int v = 0; v < arrn.Length; v++)
                                                {
                                                    bzmodel.F_Leader = arrn[v];
                                                    new BLL.T_Vis_TelBZ().Add(bzmodel);
                                                }

                                                modelTelAllot.F_HFTelID = rmw;
                                                new BLL.T_Vis_TelAllot().Add(modelTelAllot);
                                                count += 1;//导入成功，+1
                                            }
                                        }

                                    }
                                    dtres = dtInputData;

                                }
                                else
                                {
                                    errres += "该文档的内容为空";
                                }
                            }
                            catch (Exception ex)
                            {
                                if (coon.State == ConnectionState.Open)
                                {
                                    coon.Close();
                                }
                                i++;
                                errres += i.ToString() + ".导入出现异常，共导入" + count + "条数据，请从第" + (count + 2).ToString() + "行开始导入;\n";
                                if (strBuilder.Length > 0)
                                {
                                    errres += "重复的号码为：" + strBuilder.ToString() + "\n";
                                }
                            }
                            finally
                            {
                                if (coon.State == ConnectionState.Open)
                                {
                                    coon.Close();
                                }
                            }


                        }//****************using*********

                        #endregion

                    }
                    else
                    {
                        i++;
                        errres += i.ToString() + ".Excel中无数据;\n";
                    }

                }
                catch
                {
                    i++;
                    errres += i.ToString() + ".导入出现异常，导入失败;\n";
                }
                finally
                {
                    dt.Clear();
                    dt.Dispose();
                }

            }
            catch
            {
                errres += i.ToString() + ".Excel格式不正确，系统错误，导入失败;\n";
            }

            #endregion
            if (errres != "")
            {
                return Error("导入失败！错误信息：" + errres);
            }
            else
            {
                string info = "本文件有" + rcount.ToString() + "行" + ccount.ToString() + "列数据";
                return Success("导入成功！" + info, vfileid);
            }
        }
        #region 上传文件
        private string uploadexcel()
        {
            string Excelsource = "";
            try {
                //HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
                HttpPostedFile _upfile = RequestString.GetFile("upFile");
                if (_upfile != null)
                {
                    string imgPath = "";

                    string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss");
                    newFileName = newFileName + "_" + _upfile.FileName;
                    if (!Directory.Exists(Server.MapPath(this.Request.ApplicationPath + "\\ExcelData")))
                    {
                        Directory.CreateDirectory(Server.MapPath(this.Request.ApplicationPath + "\\ExcelData"));
                    }

                    imgPath = this.Request.ApplicationPath + "/ExcelData/" + newFileName.ToString();
                    string PhysicalPath = Server.MapPath(imgPath);
                    _upfile.SaveAs(PhysicalPath);

                    Excelsource = Server.MapPath(this.Request.ApplicationPath + "\\ExcelData\\") + newFileName.ToString();

                    Model.T_Vis_Files filesmodel = new Model.T_Vis_Files();
                    filesmodel.F_FileNewName = newFileName;
                    filesmodel.F_FileOldName = _upfile.FileName;
                    filesmodel.F_FilePath = Excelsource;
                    filesmodel.F_FileType = 0;
                    filesmodel.F_TypeGroup = 0;
                    filesmodel.F_FileFix = _upfile.FileName.Substring(_upfile.FileName.LastIndexOf('.') + 1);
                    filesmodel.F_InputDate = DateTime.Now;
                    filesmodel.F_InputUserCode = CurrentUser.UserData.F_UserCode;
                    filesmodel.F_InputUserID = CurrentUser.UserData.F_UserId;

                    vfileid = new BLL.T_Vis_Files().Add(filesmodel);
                }
            }
            catch(Exception ex) { }
            return Excelsource;
        }
        #endregion

        #region 读取Excel文件,返一个DataTable
        private DataSet ReadEcxel(string FileName, int Rows)
        {
            return ToDataTable(FileName);
        }

        /// <summary>
        /// 读取Excel文件到DataSet中
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        private DataSet ToDataTable(string filePath)
        {
            DataSet ds = new DataSet();
            DataTable dt = null;

            try
            {
                FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);

                NPOI.SS.UserModel.IWorkbook book = null;
                if (filePath.IndexOf(".xlsx") > 0) // 2007版本
                    book = new NPOI.XSSF.UserModel.XSSFWorkbook(fs);
                else if (filePath.IndexOf(".xls") > 0) // 2003版本
                    book = new NPOI.HSSF.UserModel.HSSFWorkbook(fs);
                //NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook(fs);

                NPOI.SS.UserModel.ISheet sheet = book.GetSheetAt(0);


                NPOI.SS.UserModel.IRow row = sheet.GetRow(0);


                int firstCellNum = row.FirstCellNum;
                int lastCellNum = row.LastCellNum;
                //if (firstCellNum == lastCellNum) continue;

                dt = new DataTable(sheet.SheetName);
                //for (int i = firstCellNum; i < lastCellNum; i++)
                for (int i = firstCellNum; i < 50; i++)
                {
                    if (row.GetCell(i) != null)
                    {
                        dt.Columns.Add(row.GetCell(i).ToString() + i.ToString(), typeof(string));
                    }
                    else
                    {
                        dt.Columns.Add(i.ToString(), typeof(string));
                    }
                }

                for (int i = 1; i <= sheet.LastRowNum; i++)
                {
                    if (sheet.GetRow(i).GetCell(2) != null && sheet.GetRow(i).GetCell(2).ToString() != "")
                    {
                        DataRow newRow = dt.Rows.Add();
                        for (int j = firstCellNum; j < 50; j++)
                        {
                            if (sheet.GetRow(i).GetCell(j) != null)
                            {
                                newRow[j] = sheet.GetRow(i).GetCell(j).ToString();
                            }
                            else
                            {
                                newRow[j] = "";
                            }
                        }
                    }
                }

                ds.Tables.Add(dt);
            }
            catch (Exception ex)
            {
                //SysLog.WriteLog(ex);
            }
            return ds;
        }
        #endregion
    }
}