using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.Interface.Controllers.Base;
using CallCenterApi.Interface.Models.Input;
using CallCenterApi.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers.customer
{
    public class RegionCategoryController : BaseController
    {
        private BLL.T_RegionCategory regionBLL = new BLL.T_RegionCategory();
        public ActionResult GetProvinces()
        {
          //  if (Request.IsAuthenticated)
          //  {
                list = new BLL.T_RegionCategory().GetModelList(" F_DeleteFlag=0 ");
                var list_p = list.Where(x => x.F_ParentId == 0).ToList();
                List<Model.TreeModel> modelList = BindTreeRegion (list_p, "0");

                if (modelList != null)
                {
                    if (modelList.Count > 0)
                        return Success("加载成功", modelList);
                }
                return Error("加载失败");
          //  }
          //  return NoToken("未知错误，请重新登录");
        }
        /// <summary>
        /// 获取省市县乡镇
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAllList(int F_Layer=0, string F_RegionName = "")
        {
            int F_RegionId = 0;
            if (!string .IsNullOrEmpty (F_RegionName))
            {
                Model.T_RegionCategory userModel = regionBLL.GetModelList("F_RegionName='"+ F_RegionName + "'"+ "and F_Layer="+(F_Layer -1)).FirstOrDefault ();
                if (userModel !=null )
                {
                    F_RegionId = userModel.F_RegionId;
                }
            }
            var entityJson = new BLL.T_RegionCategory().GetModelList("F_Layer = " + F_Layer + "AND F_ParentId=" + F_RegionId + "order by F_Sort");
                return Success("加载成功", entityJson);


        }
        /// <summary>
        /// 获取省市县乡镇
        /// </summary>
        /// <returns></returns>
        public ActionResult GetKeywordsList(int F_Layer = 0, string F_RegionName = "", string keywords = "")
        {
            int F_RegionId = 0;
            int F_ParentId = 0;
            if (!string.IsNullOrEmpty(F_RegionName.Trim()))
            {
                Model.T_RegionCategory userModel = regionBLL.GetModel(F_RegionName);
                if (userModel != null)
                {
                    F_RegionId = userModel.F_RegionId;
                    F_ParentId = int.Parse(userModel.F_ParentId.ToString());
                }
            }
            if (!string.IsNullOrEmpty(keywords.Trim()))
            {
                List<Model.T_RegionCategory> userModel = regionBLL.GetModelList(" F_RegionName like '%" + keywords.Trim() + "%'"+ "and F_Layer = " + F_Layer);
                if (userModel != null)
                {
                    return Success("加载成功", userModel);
                }

            }
            Model.T_RegionCategory entityJson1 = new Model.T_RegionCategory();
            Model.T_RegionCategory entityJson2 = new Model.T_RegionCategory();
            Model.T_RegionCategory entityJson3 = new Model.T_RegionCategory();
            var entityJson = new BLL.T_RegionCategory().GetModelList("F_Layer = " + F_Layer + "AND F_ParentId=" + F_RegionId + "order by F_Sort");
            F_Layer = F_Layer - 1;
            if (!string.IsNullOrEmpty(F_RegionName.Trim()))
            {
                if (F_ParentId>0)
                {
                    if (F_Layer == 2)
                    {
                        entityJson1 = regionBLL.GetModel(F_ParentId);
                    }
                    else if (F_Layer == 3)
                    {
                        entityJson2 = regionBLL.GetModel(F_ParentId);
                        entityJson1 = regionBLL.GetModel(int.Parse(entityJson2.F_ParentId.ToString()));
                    }
                    else if (F_Layer == 4)
                    {
                        entityJson3 = regionBLL.GetModel(F_ParentId);
                        entityJson2 = regionBLL.GetModel(int.Parse(entityJson3.F_ParentId.ToString()));
                        entityJson1 = regionBLL.GetModel(int.Parse(entityJson2.F_ParentId.ToString()));
                    }
                }
            }
            var obj = new
            {
                entityJson1,
                entityJson2,
                entityJson3,
                entityJson
            };

            return Success("加载成功", obj);
        }
        /// <summary>
        /// 导入excel
        /// </summary>
        /// <returns></returns>
        public ActionResult ImportExcel(int F_Layer, string F_RegionName="")
        {
            string userscode = CurrentUser.UserData.F_UserCode;
            HttpPostedFile _upFile = RequestString.GetFile("upFile");
            if (_upFile != null)
            {
                int headrow = 0;
                #region 上传文件
                string filepath = "";
                string datepath = DateTime.Now.ToString("yyyyMMddHHMMss");
                string aLastName = Path.GetExtension(_upFile.FileName);
                string oriname = Path.GetFileNameWithoutExtension(_upFile.FileName);
                if (aLastName != ".xls" && aLastName != ".xlsx")
                {
                    return Error("文件类型错误，请选择Excel文件");
                }
                string newpath = datepath + "_" + _upFile.FileName;
                if (!Directory.Exists(Server.MapPath(this.Request.ApplicationPath + "\\ExcelData")))
                {
                    Directory.CreateDirectory(Server.MapPath(this.Request.ApplicationPath + "\\ExcelData"));
                }
                filepath = this.Request.ApplicationPath + "/ExcelData/" + newpath;
                string PhysicalPath = Server.MapPath(filepath);
                _upFile.SaveAs(PhysicalPath);
                #endregion
                #region 添加附件日志
                Model.T_Sys_Accessories model_T_Sys_Accessories = new Model.T_Sys_Accessories();
                model_T_Sys_Accessories.F_AddTime = DateTime.Now;//上传时间
                model_T_Sys_Accessories.F_FileName = newpath;//附件名称
                model_T_Sys_Accessories.F_FileType = aLastName;//附件类型
                model_T_Sys_Accessories.F_FileUrl = filepath;//附件地址
                model_T_Sys_Accessories.F_UserCode = userscode;//上传人  
                model_T_Sys_Accessories.F_OriName = oriname;
                int fid = new BLL.T_Sys_Accessories().Add(model_T_Sys_Accessories);
                #endregion
                NPOIHelper np = new NPOIHelper();
                DataTable dt = np.ExcelToTable(_upFile, headrow);
                string msg = string.Empty;
                if (dt == null || dt.Rows.Count == 0)
                    return Error("文件没有数据");
                else
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        #region 数据入库
                        headrow = headrow + 1;

                        if (dr["地区名称"].ToString() != "" )
                        {
                           
                            Model.T_RegionCategory dModel = new Model.T_RegionCategory();
                            dModel.F_RegionName = dr["地区名称"].ToString();//地区名称
                            dModel.F_Layer = F_Layer;
                            if (F_RegionName != "")
                            {
                                Model.T_RegionCategory userModel = regionBLL.GetModel(F_RegionName);
                                if (userModel != null)
                                {
                                    dModel.F_ParentId = userModel.F_RegionId;
                                }
                                else
                                {
                                    dModel.F_ParentId = 0;
                                }
                            }
                            dModel.F_CreateBy = int .Parse (userscode);
                            dModel.F_CreateOn = DateTime.Now;
                            dModel.F_DeleteFlag = 0;
                            dModel.F_Sort = 0;
                            var res = regionBLL.Add(dModel);
                            if (res > 0)
                            {
                                addoptlog(userscode, DTRequest.GetIP(), EnumOpt.import.ToString(), res.ToString(), "导入成功,导入的文件为：" + newpath + ",当前为第" + headrow + "行");
                            }
                            else
                            {

                                msg = msg + "第" + headrow + "行，导入失败<br>";
                            }
                        }
                        else
                            msg = msg + "第" + headrow + "行，地区名称为空或格式不正确，未导入<br>";
                        #endregion
                    }
                    if (string.IsNullOrEmpty(msg))
                        return Success("导入成功 ");
                    else
                        return Error(msg);
                }

            }
            return Error("文件不能为空");
        }
        /// <summary>
        /// 操作日志
        /// </summary>
        /// <param name="usercode">操作人工号</param>
        /// <param name="ip">操作人IP</param>
        /// <param name="optcode">操作编号</param>
        /// <param name="optid">操作id</param>
        /// <param name="des">操作描述</param>
        private void addoptlog(string usercode, string ip, string optcode, string optid, string des)
        {
            new BLL.T_Sys_OperateLogs().AddOptLog("地区管理", usercode, ip, des, optcode, "T_RegionCategory", optid);
        }

        /// <summary>
        /// 获取地市
        /// </summary>
        /// <param name="deptId"></param>
        /// <returns></returns>
        public ActionResult GetRegion(int deptId = 0)
        {
            if (Request.IsAuthenticated)
            {
                BLL.T_RegionCategory dBLL = new BLL.T_RegionCategory();
                Model.T_RegionCategory dModel = dBLL.GetModel(deptId);
                if (dModel != null)
                    return Success("获取地市信息成功", dModel);
                return Error("获取地市信息失败");
            }
            return NoToken("未知错误，请重新登录");
        }

        /// <summary>
        /// 添加地市
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddRegion(RegionCategoryInput input)
        {
          
                Model.T_RegionCategory dModel = new Model.T_RegionCategory();
                dModel.F_ParentId = input.F_ParentId;
                dModel.F_Sort = input.F_Sort;
                dModel.F_RegionName = input.F_RegionName;
                dModel.F_DeleteFlag = 0;
                dModel.F_Layer = input.F_Layer;
                dModel.F_CreateBy = CurrentUser.UserData.F_UserId;
                dModel.F_CreateOn = DateTime.Now;
                if (regionBLL.Add(dModel) > 0)
                    return Success("添加成功");
                else
                    return Success("添加失败");
           
        }

        /// <summary>
        /// 编辑地市
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditRegion(RegionCategoryInput input)
        {
          
                if (input.F_RegionId <= 0)
                    return Error("请选择要编辑的地市");
                BLL.T_RegionCategory dBLL = new BLL.T_RegionCategory();
                Model.T_RegionCategory dModel = dBLL.GetModel(input.F_RegionId);
                if (dModel == null)
                    return Error("获取信息失败");
                dModel.F_ParentId = input.F_ParentId;
                dModel.F_Sort = input.F_Sort;
                dModel.F_RegionName = input.F_RegionName;
                dModel.F_Layer = input.F_Layer;
                dModel.F_ModifyBy = CurrentUser.UserData.F_UserId;
                dModel.F_ModifyOn = DateTime.Now;
                if (dBLL.Update(dModel))
                    return Success("编辑成功");
                return Error("编辑失败");
         
        }

        /// <summary>
        /// 删除地市
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DelRegion(string[] ids)
        {
          
                if (ids == null || ids.Length <= 0)
                    return Error("请选择要删除的地市");

                var idStr = string.Join(",", ids);
                if (string.IsNullOrEmpty(idStr.Trim()))
                    return Error("请选择要删除的地市");

                if (regionBLL.DeleteList(idStr))
                    return Success("删除成功");
                return Error("删除失败");
        
        }

        #region 获取地市列表 - 优化前的
        ///// <summary>
        ///// 获取地市列表
        ///// </summary>
        ///// <returns></returns>
        //public ActionResult GetRegionList(int pId = 0)
        //{
        //    if (Request.IsAuthenticated)
        //    {
        //        DataTable dt = new DataTable();
        //        dt = new BLL.T_RegionCategory().GetList(" F_DeleteFlag=0 and F_ParentId=" + pId).Tables[0];
        //        List<Model.TreeModel> modelList = BindTree(dt, "0");

        //        if (modelList != null)
        //        {
        //            if (modelList.Count > 0)
        //                return Success("加载成功", modelList);
        //        }
        //        return Error("加载失败");
        //    }
        //    return NoToken("未知错误，请重新登录");
        //}
        ///// <summary>
        ///// tree  树形地市
        ///// </summary>
        ///// <param name="tab"></param>
        ///// <param name="parentid"></param>
        ///// <returns></returns>
        //private List<Model.TreeModel> BindTree(DataTable tab, string parentid)
        //{
        //    DataTable tab2 = new DataTable();

        //    if (tab != null && tab.Rows.Count > 0)
        //    {
        //        List<Model.T_RegionCategory> categorylist = new BLL.T_RegionCategory().DataTableToList(tab);
        //        List<Model.TreeModel> modelList = new List<Model.TreeModel>(categorylist.Count);
        //        for (int i = 0; i < categorylist.Count; i++)
        //        {
        //            Model.TreeModel model = new Model.TreeModel();
        //            string currentID = categorylist[i].F_RegionId.ToString();//当前功能ID
        //            model.id = currentID;
        //            model.IconCls = "";//图标
        //            model.headerid =int .Parse ( categorylist[i].F_Layer.ToString ());
        //            model.text = categorylist[i].F_RegionName;
        //            tab2 = new BLL.T_RegionCategory().GetList("F_ParentId=" + currentID + " and F_DeleteFlag=0 order by f_sort").Tables[0];
        //            if (tab2 != null && tab2.Rows.Count > 0)
        //            {
        //                model.children = BindTree(tab2, currentID);
        //            }
        //            modelList.Add(model);
        //        }
        //        return modelList;

        //    }
        //    else
        //    {
        //        return null;
        //    }

        //}

        #endregion


        public List<T_RegionCategory> list = null;
        #region 获取地市列表 - 优化后的
        /// <summary>
        /// 获取地市列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetRegionList(int pId = 0)
        {
            if (Request.IsAuthenticated)
            {
                list = new BLL.T_RegionCategory().GetModelList(" F_DeleteFlag=0 ");
                var list_p = list.Where(x => x.F_ParentId == pId).ToList();
                List<Model.TreeModel> modelList = BindTree(list_p, "0");

                if (modelList != null)
                {
                    if (modelList.Count > 0)
                        return Success("加载成功", modelList);
                }
                return Error("加载失败");
            }
            return NoToken("未知错误，请重新登录");
        }
        /// <summary>
        /// tree  树形地市
        /// </summary>
        /// <param name="tab"></param>
        /// <param name="parentid"></param>
        /// <returns></returns>
        private List<Model.TreeModel> BindTreeRegion(List<T_RegionCategory> tab, string parentid)
        {
            if (tab.Count > 0)
            {
                List<Model.TreeModel> modelList = new List<Model.TreeModel>(tab.Count);
                for (int i = 0; i < tab.Count; i++)
                {
                    Model.TreeModel model = new Model.TreeModel();
                    int F_RegionId = tab[i].F_RegionId;
                    string currentID = tab[i].F_RegionId.ToString();//当前功能ID
                    model.id = currentID;
                    model.IconCls = "";//图标
                    if (tab[i].F_Layer != null)
                    {
                        model.headerid = int.Parse(tab[i].F_Layer.ToString());
                    }
                    model.text = tab[i].F_RegionName;
                    var tab2 = list.Where(x => x.F_ParentId == F_RegionId).OrderByDescending(x => x.F_Sort).ToList();
                    if (tab2.Count >0)
                    {
                        model.children = BindRegion(tab2, currentID);
                    }
                    modelList.Add(model);
                }
                return modelList;
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// tree  树形地市
        /// </summary>
        /// <param name="tab"></param>
        /// <param name="parentid"></param>
        /// <returns></returns>
        private List<Model.TreeModel> BindRegion(List<T_RegionCategory> tab, string parentid)
        {
            if (tab.Count > 0)
            {
                List<Model.TreeModel> modelList = new List<Model.TreeModel>(tab.Count);
                for (int i = 0; i < tab.Count; i++)
                {
                    Model.TreeModel model = new Model.TreeModel();
                    int F_RegionId = tab[i].F_RegionId;
                    string currentID = tab[i].F_RegionId.ToString();//当前功能ID
                    model.id = currentID;
                    model.IconCls = "";//图标
                    if (tab[i].F_Layer != null)
                    {
                        model.headerid = int.Parse(tab[i].F_Layer.ToString());
                    }
                    model.text = tab[i].F_RegionName;
                    var tab2 = list.Where(x => x.F_ParentId == F_RegionId).OrderByDescending(x => x.F_Sort).ToList();
                    modelList.Add(model);
                }
                return modelList;
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// tree  树形地市
        /// </summary>
        /// <param name="tab"></param>
        /// <param name="parentid"></param>
        /// <returns></returns>
        private List<Model.TreeModel> BindTree(List<T_RegionCategory> tab, string parentid)
        {
            if (tab.Count > 0)
            {
                List<Model.TreeModel> modelList = new List<Model.TreeModel>(tab.Count);
                for (int i = 0; i < tab.Count; i++)
                {
                    Model.TreeModel model = new Model.TreeModel();
                    int F_RegionId = tab[i].F_RegionId;
                    string currentID = tab[i].F_RegionId.ToString();//当前功能ID
                    model.id = currentID;
                    model.IconCls = "";//图标
                    if (tab[i].F_Layer!=null )
                    {
                        model.headerid = int.Parse(tab[i].F_Layer.ToString());
                    }
                    model.text = tab[i].F_RegionName;
                    var tab2 = list.Where(x => x.F_ParentId == F_RegionId).OrderByDescending(x=>x.F_Sort).ToList();
                    if (tab2.Count > 0)
                    {
                        model.children = BindTree(tab2, currentID);
                    }
                    modelList.Add(model);
                }
                return modelList;

            }
            else
            {
                return null;
            }

        }
        #endregion
    }
}