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_dx
{
    public class InputDXTelController : BaseController
    {
        int vfileid = 0;
        // 导入号码读取填入数据库
        public ActionResult TelInput(string fileid,int type)
        {
                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 = uploadexcel(fileid, type);
                #region 将文件中的数据导入数据库

                try
                {

                    //************************将文件中的数据导入数据库*************************//
                    DataSet dt = ReadEcxel(Excelsource, 0,type);
                    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];//要导入的电话号码


                            #region MyRegion
                            using (SqlConnection coon = new SqlConnection(DbHelperSQL.connectionString))
                            {
                                try
                                {
                                    coon.Open();
                                    int colscount = dtInputData.Columns.Count;//列数
                                    int rowscount = dtInputData.Rows.Count;//行数
                                    
                                    if (rowscount > 0)
                                    {
                                        DateTime dn = DateTime.Now;
                                        foreach (DataRow dr in dtInputData.Rows)
                                        {
                                                int rescount = 0;

                                                if (type == 0)
                                                {
                                                    rescount = intoDBO(dr, dn);
                                                }
                                                if (type == 1)
                                                {
                                                    rescount = intoDBN(dr, dn);
                                                }
                                                if (rescount > 0)
                                                    count += 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 int intoDBO(DataRow dr, DateTime dn)
        {
            Model.T_Vis_DXOTelphone modelPhoneImport = new Model.T_Vis_DXOTelphone();
            modelPhoneImport.F_insertDate = dn;
            modelPhoneImport.F_insertUserID = CurrentUser.UserData.F_UserId.ToString();
            modelPhoneImport.F_insertUser = CurrentUser.UserData.F_UserName;
            if (dr[15].ToString() != "" || dr[16].ToString() != "")
            {
                modelPhoneImport.F_CardDate = dr[0].ToString();//办保养卡时间
                modelPhoneImport.F_CardType = dr[1].ToString();//保养卡类别
                modelPhoneImport.F_CardAmount = dr[2].ToString();//保养卡金额
                modelPhoneImport.F_MaintainUser = dr[3].ToString();//电销维护
                modelPhoneImport.F_ComLocations = dr[4].ToString();//车辆常用地
                modelPhoneImport.F_Grade = dr[5].ToString();//等级
                modelPhoneImport.F_Reciver = dr[6].ToString();//接车员
                modelPhoneImport.F_RepairTimes = dr[7].ToString();//历史维修次
                modelPhoneImport.F_FirstInDate = dr[8].ToString();//首次入厂日期
                modelPhoneImport.F_LastMileage = dr[9].ToString();//上次入厂里程
                modelPhoneImport.F_LastOutDate = dr[10].ToString();//上次出厂日期
                modelPhoneImport.F_Years = dr[11].ToString();//年份
                modelPhoneImport.F_InsuranceC = dr[12].ToString();//承保公司
                modelPhoneImport.F_InsuranceDate = dr[13].ToString();//保险到期日
                modelPhoneImport.F_Storefront = dr[14].ToString();//店面
                modelPhoneImport.F_License = dr[15].ToString();//系统车牌号
                modelPhoneImport.F_Numbers = dr[16].ToString();//识别号
                modelPhoneImport.F_brand = dr[17].ToString();//品牌
                modelPhoneImport.F_CarType = dr[18].ToString();//车型
                modelPhoneImport.F_Contacts = dr[19].ToString();//联系人
                modelPhoneImport.F_khMobile = dr[20].ToString();//客户手机
                modelPhoneImport.F_khPhone = dr[21].ToString();//客户电话
                modelPhoneImport.F_PreLoss = dr[22].ToString();//预流失
                modelPhoneImport.F_WoOrder = dr[23].ToString();//工单
                modelPhoneImport.F_usePlace = dr[24].ToString();//使用地
                modelPhoneImport.F_khInfor = dr[25].ToString();//客户提供信息
                modelPhoneImport.F_lossReason = dr[26].ToString();//流失原因
                modelPhoneImport.F_hanleMode = dr[27].ToString();//处理方式
                modelPhoneImport.F_liableP = dr[28].ToString();//责任人
            }
            modelPhoneImport.F_FileID = vfileid;
            //办保养卡时间0 保养卡类别1   保养卡金额2 电销维护 3   车辆常用地4 等级5  接车员6 历史维修次7   
            //首次入厂日期8 上次入厂里程9  上次出厂日期10 年份11  承保公司12 保险到期日13   7月店面14 
            //系统车牌号15   识别号16 品牌17  车型18 联系人19 客户手机20 客户电话 21   预流失22 工单23  使用地24 客户提供信息25  
            //流失原因26    处理方式27

            return new BLL.T_Vis_DXOTelphone().Add(modelPhoneImport);
        }
        //新客户
        private int intoDBN(DataRow dr, DateTime dn)
        {
            Model.T_Vis_DXNTelphone modelPhoneImport = new Model.T_Vis_DXNTelphone();
            modelPhoneImport.F_insertDate = dn;
            modelPhoneImport.F_insertUserID = CurrentUser.UserData.F_UserId.ToString();
            modelPhoneImport.F_insertUser = CurrentUser.UserData.F_UserName;
            if (dr[1].ToString() != "" || dr[2].ToString() != "")
            {
                modelPhoneImport.F_SerialNo = dr[0].ToString();//序号
                modelPhoneImport.F_InfoDode = dr[1].ToString();//信息编号
                modelPhoneImport.F_License = dr[2].ToString();//车牌号
                modelPhoneImport.F_brand = dr[3].ToString();//品牌
                modelPhoneImport.F_series = dr[4].ToString();//车系
                modelPhoneImport.F_CarType = dr[5].ToString();//车型
                modelPhoneImport.F_ownerName = dr[6].ToString();//车主姓名
                modelPhoneImport.F_Telphone = dr[7].ToString();//固定电话
                modelPhoneImport.F_MobilePhone = dr[8].ToString();//移动电话
                modelPhoneImport.F_ownerships = dr[9].ToString();//归属人
                modelPhoneImport.F_usePlace = dr[10].ToString();//使用地
                modelPhoneImport.F_ReportRemark = dr[11].ToString();//报备备注
                modelPhoneImport.F_khInfor = dr[12].ToString();//客户提供信息
                modelPhoneImport.F_GroupName = dr[13].ToString();//集团名称
                modelPhoneImport.F_khType = dr[14].ToString();//客户类别
                modelPhoneImport.F_isInto = dr[15].ToString();//是否进店
                modelPhoneImport.F_intointent = dr[16].ToString();//进店意向程度
                modelPhoneImport.F_ReportUser = dr[17].ToString();//报备人
                modelPhoneImport.F_ownerships2 = dr[18].ToString();//归属人
                modelPhoneImport.F_ReportTime = dr[19].ToString();//报备时间
                modelPhoneImport.F_PerfectRate = dr[20].ToString();//信息完善率
                modelPhoneImport.F_infoState = dr[21].ToString();//信息状态
                modelPhoneImport.F_aging = dr[22].ToString();//跟进时效

                modelPhoneImport.F_liableP = dr[23].ToString();//责任人
            }
            modelPhoneImport.F_FileID = vfileid;
            //序号0	信息编号1	 车牌号2	品牌3	车系4  车型5	车主姓名6	固定电话7	移动电话8	归属人9	
            //使用地10	报备备注11	客户提供信息12	
            //2017年下半年回访内容	分类	时间	
            //2017年上半年回访内容	分类	时间	
            //2016回访内容	分类	时间	
            //集团名称13	客户类别14	是否进店15	进店意向程度16	报备人17	归属人18	
            //报备时间19	信息完善率20	信息状态21	跟进时效22


            return new BLL.T_Vis_DXNTelphone().Add(modelPhoneImport);
        }
        #endregion

        #region 上传文件
        private string uploadexcel(string fileid,int type)
        {
            string Excelsource = "";
            try
            {
                //HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
                HttpPostedFile _upfile = RequestString.GetFile(fileid);
                if (_upfile != null)
                {
                    string imgPath = "";

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

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

                    Excelsource = Server.MapPath(this.Request.ApplicationPath + "\\ExcelData\\DX\\") + 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 = type;
                    filesmodel.F_TypeGroup = 1;
                    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,int type)
        {
            return ToDataTable(FileName,type);
        }

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

            try
            {
                int cell1 = 15, cell2 = 16;
                if (type == 1)
                {
                    cell1 = 1;
                    cell2 = 2;
                }
                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;

                dt = new DataTable(sheet.SheetName);
                for (int i = firstCellNum; i < lastCellNum; 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(cell1) != null && sheet.GetRow(i).GetCell(cell1).ToString() != "")|| (sheet.GetRow(i).GetCell(cell2) != null && sheet.GetRow(i).GetCell(cell2).ToString() != ""))
                    {
                        DataRow newRow = dt.Rows.Add();
                        for (int j = firstCellNum; j < lastCellNum; 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
    }
}