TG.WXCRM.V4/WEB/Controllers/Res/ImportResController.cs

453 lines
19 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml.Serialization;
using WX.CRM.Common;
using WX.CRM.IBLL.Res;
using WX.CRM.Model.Entity;
using WX.CRM.Model.QueryMap;
using WX.CRM.WebHelper;
namespace WX.CRM.WEB.Controllers.Res
{
public class ImportResController : BaseController
{
IRES_IMPORTRES importResBiz;
IRES_IMPORTRES_Q importResBiz_Q;
IRES_RESOURCETYPE_Q resourceTypeBiz_Q;
IRES_ACTIVITY_Q activeBiz_Q;
IRES_CUSTOMERDETAIL _res_customerdetail;
IRES_CUSTOMERDETAIL_Q _res_customerdetail_q;
public ImportResController(IRES_IMPORTRES _importResBiz, IRES_RESOURCETYPE_Q _resourceTypeBiz_Q, IRES_ACTIVITY_Q _activeBiz_Q, IRES_IMPORTRES_Q _importResBiz_Q, IRES_CUSTOMERDETAIL res_customerdetail, IRES_CUSTOMERDETAIL_Q res_customerdetail_q)
{
importResBiz = _importResBiz;
resourceTypeBiz_Q = _resourceTypeBiz_Q;
activeBiz_Q = _activeBiz_Q;
importResBiz_Q = _importResBiz_Q;
_res_customerdetail = res_customerdetail;
_res_customerdetail_q = res_customerdetail_q;
}
[AuthorizeRedirect(Roles = InitRights.CONST_导入资源)]
public ActionResult Index()
{
ToolBar tool = new ToolBar();
tool.AllowButton("Certain");
ViewBag.ToolBar = tool;
List<SelectListItem> lis = new List<SelectListItem>();
var rlis = resourceTypeBiz_Q.GetList();
lis.Add(new SelectListItem() { Value = "0", Text = "-请选择-" });
foreach (var obj in rlis)
{
lis.Add(new SelectListItem() { Value = string.Format("{0}", obj.RESTYPEID), Text = obj.TYPENAME });
}
ViewData["ResourctType1"] = lis;
ViewData["ResourctType2"] = lis;
ViewData["ResourctType3"] = lis;
Pager pager = new Pager() { order = "IMPORTID", page = 1, rows = 10 };
string tableId = "tablist";
Table tab = new Table(tableId);
tab.AddHeadCol("map_IMPORTID", "20%", "导入ID");
tab.AddHeadCol("map_RESOURCENAME", "", "资源名称");
tab.AddHeadCol("map_ACTIVITYNAME", "", "活动名称");
tab.AddHeadCol("map_RESOURCETAG", "20%", "资源标签");
tab.AddHeadCol("map_ResourceCount", "", "资源总数");
tab.AddHeadCol("map_ResourceNewCount", "", "新资源数");
tab.AddHeadCol("map_OPTYPECHAR", "", "上传方式");
tab.AddHeadCol("map_CREATEUSERNAME", "", "创建人");
tab.AddHeadCol("map_CTIME", "", "创建时间");
tab.AddHeadRow();
ViewBag.gridTable = tab.GetTable() + Pagination.GetPage(pager, tableId, "15,30,50,100");
return View();
}
public string RecFile()
{
return UploadFile();
}
[AuthorizeRedirect(Roles = InitRights.CONST_导入资源)]
public JsonResult GetHtmlList(Pager pager, string columns)
{
int c = 0;
List<WX.CRM.Model.Entity.RES_IMPORTRES> lis = importResBiz_Q.GetList(pager.page, pager.rows, ref c);
pager.totalRows = c;
Table table = new Table(columns, true);
table.gridPager = pager;
foreach (WX.CRM.Model.Entity.RES_IMPORTRES model in lis)
{
table.AddCol(model.map_IMPORTID);
table.AddCol(model.map_RESOURCENAME);
table.AddCol(model.map_ACTIVITYNAME);
table.AddCol(model.map_RESOURCETAG);
table.AddCol(model.map_ResourceCount);
table.AddCol(model.map_ResourceNewCount);
table.AddCol(model.map_OPTYPECHAR);
table.AddCol(model.map_CREATEUSERNAME);
table.AddCol(model.map_CTIME);
table.AddRow();
}
var json = new
{
totalPages = pager.totalPages,
totalRows = pager.totalRows,
rowsList = table.GetRows()
};
return Json(json, JsonRequestBehavior.AllowGet);
}
#region
public ActionResult ActiveList(decimal? id)
{
var lis = activeBiz_Q.GetList(id.GetValueOrDefault(0));
if (Request.IsAjaxRequest())
{
return Json(lis, JsonRequestBehavior.AllowGet);
}
else
{
return View("");
}
}
#endregion
#region
string UploadFile()
{
string msg = "ok";
try
{
List<string> mbs = new List<string>();
List<RES_IMPORTRESEXT> extList = new List<RES_IMPORTRESEXT>();
string t = string.Format("{0}", Request.Form["FileType"]);
string rtag = string.Format("{0}", Request.Form["HidRESOURCETAG"]);
string rid = string.Format("{0}", Request.Form["HidResourceId"]);
string aid = string.Format("{0}", Request.Form["HidACTIVITYID"]);
int rtype = 0; //0手机号批量提交1文件上传导入
if (t == "手机号批量提交")
{
mbs = GetMiblesByStr();
rtype = 0;
}
else if (t == "文件上传导入")
{
mbs = GetMiblesByTxtFile();
rtype = 1;
}
else if (t == "Excel上传导入")
{
extList = GetMiblesByExcelFile();
rtype = 2;
}
else
{
throw new Exception("请先选中正确的tab标签");
}
if (rtype == 2)
{
if (extList == null || extList.Count == 0)
{
throw new Exception("请输入正确的手机号!");
}
}
else
{
if (mbs == null || mbs.Count == 0)
throw new Exception("请输入正确的手机号!");
}
WX.CRM.Model.Entity.RES_IMPORTRES info = new WX.CRM.Model.Entity.RES_IMPORTRES();
info.RESTYPEID = decimal.Parse(rid);
info.ACTIVITYID = decimal.Parse(aid);
info.OPTYPE = rtype;
info.RESOURCETAG = rtag;
info.CREATEUSER = UserId;
info.CTIME = System.DateTime.Now;
if (info.RESTYPEID.GetValueOrDefault(0) == 0 || info.ACTIVITYID.GetValueOrDefault(0) == 0)
throw new Exception("请选择正确的资源类型!");
List<string> pushmbs = new List<string>();
if (rtype == 2)
{
pushmbs = extList.Select(m => m.Mobile).ToList();
importResBiz.ImpotDt(info, extList, 300);
}
else
{
pushmbs = mbs;
importResBiz.ImpotDt(info, mbs, 300);
}
#region cms
//CMSApiHelper pushapi = new CMSApiHelper();
////分页推送
//int size=3, index=1,count= pushmbs.Count();
//var pushCode = "";
//while (true)
//{
// Dictionary<string, object> data = new Dictionary<string, object>();
// var pushData = pushmbs.Skip((index - 1) * size).Take(size);
// count -= pushData.Count();
// data.Add("pushCode", pushCode);
// data.Add("pushData", string.Join(",", pushData));//JsonHelper.ObjDivertToJson(pushData)
// var req = pushapi.PushImportData(data);
// if (req.code == 0) {
// pushCode = req.data.pushCode;//更新推送id
// }
// if (count <= 0) break;
//}
//var subReq = pushapi.SubmitImport(new Dictionary<string, object>() { { "pushCode", pushCode } });
#endregion
}
catch (Exception ex)
{
msg = ex.Message;
LogHelper.Error("ImportResController:【UploadFile】:" + ex.Message + ex.StackTrace);
}
return msg;
}
List<string> GetMiblesByTxtFile()
{
string vPath = System.Configuration.ConfigurationManager.AppSettings["UploadTemFileDic"];
List<string> lis = new List<string>();
HttpFileCollectionBase files = Request.Files;
HttpPostedFileBase file = files["FileMobile"];
if (file != null && file.ContentLength > 0)
{
string fileName = file.FileName;
//判断文件名字是否包含路径名,如果有则提取文件名
if (fileName.LastIndexOf("\\") > -1)
{
fileName = fileName.Substring(fileName.LastIndexOf("\\") + 1);
}
if (fileName.ToLower().IndexOf(".txt") > -1)
{
if (!System.IO.Directory.Exists(Server.MapPath(vPath)))
{
System.IO.Directory.CreateDirectory(Server.MapPath(vPath));
}
string path = Server.MapPath((vPath + "/") + fileName);
file.SaveAs(path);
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);
while (!sr.EndOfStream)
{
string number = sr.ReadLine();
if (WX.CRM.Common.Utility.ChekMobile(number) || WX.CRM.Common.Utility.ValidateTelCode(number))
lis.Add(number);
else
{
LogHelper.Info("错误的号码:" + number);
}
}
sr.Close();
fs.Close();
System.IO.File.Delete(path);
}
else
{
throw new Exception("文件格式不正确!");
}
}
else
{
throw new Exception("文件不存在!");
}
return lis;
}
List<RES_IMPORTRESEXT> GetMiblesByExcelFile()
{
string vPath = System.Configuration.ConfigurationManager.AppSettings["UploadTemFileDic"];
List<RES_IMPORTRESEXT> lis = new List<RES_IMPORTRESEXT>();
HttpFileCollectionBase files = Request.Files;
HttpPostedFileBase file = files["FileMobile2"];
if (file != null && file.ContentLength > 0)
{
string fileName = file.FileName;
//判断文件名字是否包含路径名,如果有则提取文件名
if (fileName.LastIndexOf("\\") > -1)
{
fileName = fileName.Substring(fileName.LastIndexOf("\\") + 1);
}
if (fileName.ToLower().IndexOf(".xls") > -1)
{
if (!System.IO.Directory.Exists(Server.MapPath(vPath)))
{
System.IO.Directory.CreateDirectory(Server.MapPath(vPath));
}
string path = Server.MapPath((vPath + "/") + fileName);
file.SaveAs(path);
DataTable dt = null;
try
{
NPOIHelper.InitializeWorkbook_xls(path);
dt = NPOIHelper.ConvertToDataTable();
}
catch (Exception ex)
{
LogHelper.Error(ex);
throw new Exception("解析excel文件错误");
}
if (dt.Rows.Count > 0 || dt.Columns.Count == 3)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow model = dt.Rows[i];
string number = model[0] != null ? model[0].ToString() : "";
if (WX.CRM.Common.Utility.ChekMobile(number) || WX.CRM.Common.Utility.ValidateTelCode(number))
{
RES_IMPORTRESEXT ext = new RES_IMPORTRESEXT();
ext.Mobile = number;
if (model[1] != null && !string.IsNullOrWhiteSpace(model[1].ToString()))
{
var customerDetail = new RES_CUSTOMERDETAIL();
customerDetail.CNAME = model[1].ToString();
var xmls = new XmlSerializer(typeof(RES_CUSTOMERDETAIL));
var sw = new StringWriter();
xmls.Serialize(sw, customerDetail);
ext.ExtXml = sw.ToString();
}
lis.Add(ext);
}
}
}
System.IO.File.Delete(path);
}
else
{
throw new Exception("文件格式不正确!");
}
}
else
{
throw new Exception("文件不存在!");
}
return lis;
}
List<string> GetMiblesByStr()
{
List<string> lis = new List<string>();
string mobileStr = string.Format("{0}", Request.Form["txtMobiles"]);
mobileStr = mobileStr.Replace("\r\n", "&");
mobileStr = mobileStr.Replace("\r", "&");
mobileStr = mobileStr.Replace("\n", "&");
string[] mbs = mobileStr.Trim().Split('&');
for (int i = 0; i < mbs.Length; i++)
{
if (WX.CRM.Common.Utility.ChekMobile(mbs[i]) || WX.CRM.Common.Utility.ValidateTelCode(mbs[i]))
lis.Add(mbs[i]);
}
//string patten = @"[1][34578]\d{9}";
//var mobiles = Regex.Matches(mobileStr, patten);
//string m = mobiles[0].Value;
//LogHelper.Error(mobileStr);
return lis;
}
#endregion
#region
[HttpGet]
[AuthorizeRedirect(Roles = InitRights.CONST_导入资源)]
public ActionResult UpdateName()
{
return View();
}
[HttpPost]
//[AuthorizeRedirect(Roles = InitRights.CONST_导入资源)]
public JsonResult UploadName(HttpPostedFileBase fileData)
{
if (fileData != null)
{
try
{
//文件上传后的保存路径
string filePath = Server.MapPath("~/UploadFile/UpdateName/");
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
string fileName = Path.GetFileName(fileData.FileName);//原始文件名称
string fileExtension = Path.GetExtension(fileName); //文件扩展名
string saveName = Guid.NewGuid() + fileExtension; //保存文件名称
fileData.SaveAs(filePath + saveName);
var ret = handleName(saveName, fileExtension);
return Json(ret ? new { Success = true, Message = "上传成功" } : new { Success = false, Message = "上传失败" });
}
catch (Exception ex)
{
return Json(new { Success = false, Message = ex.Message }, JsonRequestBehavior.AllowGet);
}
}
return Json(new { Success = false, Message = "请选择要上传的文件!" }, JsonRequestBehavior.AllowGet);
}
public bool handleName(string file, string fileExten)
{
try
{
DataTable dt = new DataTable();
if (fileExten == ".xls")
{
NPOIHelper.InitializeWorkbook_xls(AppDomain.CurrentDomain.BaseDirectory + "UploadFile\\UpdateName\\" + file);
dt = NPOIHelper.ConvertToDataTable();
}
else if (fileExten == ".xlsx")
{
NPOIHelper.InitializeWorkbook_xlsx(AppDomain.CurrentDomain.BaseDirectory + "UploadFile\\UpdateName\\" + file);
dt = NPOIHelper.ConvertToDataTable_xlsx();
}
//LogHelper.Error(fileExten);
if (dt.Rows.Count > 0)
{
int start = 0;
int end = dt.Rows.Count;
while (start < end)
{
DataRow model = dt.Rows[start++];
var resid = string.Empty;
if (!string.IsNullOrWhiteSpace(model[0].ToString()))
{
//LogHelper.Info("mobile:" + model[0].ToString());
//eid = Convert.ToDecimal(model[0]);
resid = ResUtil.CreateResId(model[0].ToString());
}
var name = string.Empty;
if (!string.IsNullOrWhiteSpace(model[1].ToString()))
{
name = model[1].ToString();
}
//LogHelper.Info("resid:" + resid);
var info = _res_customerdetail_q.GetModel_RES_CUSTOMERDETAIL(resid);
if (info != null)
{
info.CNAME = name;
var ret = _res_customerdetail.Update(info);
//LogHelper.Info("ret:" + ret.ToString());
}
}
}
return true;
}
catch (Exception ex)
{
LogHelper.Error(ex);
return false;
}
}
#endregion
}
}