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

namespace CallCenterApi.Interface.Controllers
{
    /// <summary>
    /// 区域/城市/项目/楼号
    /// </summary>
    //[Authority]
    public class CusRegionCategoryController : BaseController
    {
        private BLL.T_Cus_RegionCategory bllCus_Region = new BLL.T_Cus_RegionCategory();
        private BLL.T_Cus_Region_UserAccount_Map bllRegion_UserAccount_Map = new BLL.T_Cus_Region_UserAccount_Map();

        #region 区域项目 楼号（楼盘）
        /// <summary>
        /// 获取区域/城市/项目/楼号 下拉
        /// </summary>
        /// <returns></returns>
        public ActionResult GetListDrop(int areaid = 1,int parentid = 0)
        {
            var list = bllCus_Region.GetModelList(" F_AreaId = " + areaid + " AND F_ParentId = " + parentid + " and F_DeleteFlag = 0 ORDER BY F_Sort,F_RegionId ");
            return Success("获取下拉成功", list);
        }

        /// <summary>
        /// 获取区域/城市/项目/楼号列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetList()
        {
            DataTable dt = new DataTable();
            var sql = " and F_DeleteFlag = 0 ";
            int areaid = Utils.StrToInt(RequestString.GetQueryString("areaid"), 1);
            int parentid = Utils.StrToInt(RequestString.GetQueryString("parentid"), 0);
            string regionname = RequestString.GetQueryString("regionname");
            string city = RequestString.GetQueryString("city");   //城市
            string property = RequestString.GetQueryString("property");   //物业 
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            sql += " and F_ParentId = " + parentid + " ";
            if (!string.IsNullOrEmpty(city))
            {
                sql += " and F_City like '%" + city.Trim() + "%' ";
            }
            if (!string.IsNullOrEmpty(property))
            {
                sql += " and F_Property like '%" + property.Trim() + "%' ";
            }
            if (!string.IsNullOrEmpty(regionname))
            {
                sql += " and F_RegionName like '%" + regionname.Trim() + "%' ";
            }
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }
            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "dbo.T_Cus_RegionCategory (NOLOCK)",
                "F_RegionId",
                "*",
                sql,
                "ORDER BY F_Sort,F_RegionId",
                pagesize,
                pageindex,
                true,
                out recordCount);

            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());
        }

        /// <summary>
        /// 获取区域/城市/项目/楼号详情
        /// </summary>
        /// <param name="dicFlag"></param>
        /// <returns></returns>
        public ActionResult GetInfo(int id)
        {
            var model = bllCus_Region.GetModel(id);
            if (model != null)
                return Success("加载字典成功", model);
            else
                return Error("加载字典失败");
        }

        /// <summary>
        /// 添加区域/城市/项目/楼号信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ActionResult Add(Cus_RegionCategoryInput input)
        {
            int userId = CurrentUser.UserData.F_UserId;
            if (input.F_AreaId<=0)
                return Error("分类信息不能为空");
            if (string.IsNullOrEmpty(input.F_RegionName))
                return Error("区域名称不能为空");
            var model = new Model.T_Cus_RegionCategory();
            model.F_RegionName = input.F_RegionName;
            model.F_City = input.F_City;
            model.F_Property = input.F_Property;
            model.F_ParentId = input.F_ParentId;
            model.F_AreaId = input.F_AreaId;
            model.F_Sort = input.F_Sort;
            model.F_CreateBy = userId;
            model.F_CreateOn = DateTime.Now;
            int b = bllCus_Region.Add(model);
            if (b > 0)
                return Success("添加成功");
            else
                return Error("添加失败");
        }

        /// <summary>
        /// 修改区域/城市/项目/楼号信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ActionResult Update(Cus_RegionCategoryInput input)
        {
            int userId = CurrentUser.UserData.F_UserId;
            if (input.F_RegionId <= 0)
                return Error("参数错误");
            if (input.F_AreaId <= 0)
                return Error("分类信息不能为空");
            if (string.IsNullOrEmpty(input.F_RegionName))
                return Error("区域名称不能为空");
            var model = bllCus_Region.GetModel(input.F_RegionId);
            if (model == null)
                return Error("字典标志不要修改");   //字典对象不存在
            model.F_RegionName = input.F_RegionName;
            model.F_City = input.F_City;
            model.F_Property = input.F_Property;
            model.F_ParentId = input.F_ParentId;
            model.F_AreaId = input.F_AreaId;
            model.F_Sort = input.F_Sort;
            model.F_ModifyBy = userId;
            model.F_ModifyOn = DateTime.Now;
            bool b = bllCus_Region.Update(model);
            if (b)
                return Success("修改成功");
            else
                return Error("修改失败");
        }

        /// <summary>
        /// 删除信息
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="parentid"></param>
        /// <returns></returns>
        public ActionResult Delete(string[] ids)
        {
            if (ids == null || ids.Length <= 0)
                return Error("获取参数失败");
            StringBuilder sb = new StringBuilder();
            foreach (var item in ids)
            {
                sb.Append("" + item + ",");
            }
            #region 判断子栏目是否存在
            var sql = "";
            sql += " F_DeleteFlag = 0 AND F_ParentId in (" + sb.ToString().Trim(',') + ") ";
            var list = bllCus_Region.DataTableToList(bllCus_Region.GetList(sql).Tables[0]);
            if (list.Count > 0)
                return Error("操作失败：子栏目存在，不能删除");
            #endregion
            string sqlwhereGoods = $" UPDATE dbo.T_Cus_RegionCategory SET F_DeleteFlag = 1 WHERE F_DeleteFlag = 0 AND F_RegionId IN ({sb.ToString().Trim(',')}) "; //删除
            int n = DbHelperSQL.ExecuteSql(sqlwhereGoods);
            if (n > 0)
                return Success("删除成功");
            else
                return Error("删除失败");
            //bool b = bllCus_Region.DeleteList(sb.ToString().Trim(','));
            //if (b)
            //    return Success("删除成功");
            //else
            //    return Error("删除失败");
        }
        #endregion

        #region 坐席会员与项目关联

        /// <summary>
        /// 保存坐席与项目关联
        /// </summary>
        /// <param name="regionIds"></param>
        /// <param name="userid"></param>
        /// <returns></returns>
        public ActionResult SaveRegionUserFunction(string[] regionIds, int useraccountid = 0)
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            try
            {
                string usercode = CurrentUser.UserData.F_UserCode;
                if (regionIds == null)
                    return Error("参数错误");
                var modelUser = new T_Cus_Region_UserAccount_Map();
                //查询选中页面中的权限
                var idStr = string.Join(",", regionIds);
                if (useraccountid == 0)
                    return Error("参数错误");
                //清除对应信息
                bool bdelete = bllRegion_UserAccount_Map.Delete(useraccountid);
                //var childRegionIdList = bllCus_Region.DataTableToList(bllCus_Region.GetList(" F_ParentId in (" + idStr + ") ").Tables[0]).Select(x => x.F_RegionId).ToList();   
                //childRegionIdList.AddRange(regionIds.ToList().Select(x => Convert.ToInt32(x)).ToList());
                var childRegionIdList = regionIds.ToList().Select(x => Convert.ToInt32(x)).ToList();
                var query = childRegionIdList.Distinct();
                foreach (var funcId in query)
                {
                    modelUser.RegionId = funcId;
                    modelUser.UserId = useraccountid;
                    modelUser.CreateBy = usercode;
                    modelUser.CreateDateTime = DateTime.Now;
                    bool b = bllRegion_UserAccount_Map.Add(modelUser);
                    if (b)
                        res = Success("权限设置成功");
                    else
                        res = Error("权限设置失败");
                }
                return res;
            }
            catch (Exception ex)
            {
                //throw;
                return Error("设置异常");
            }
        }

        /// <summary>
        /// 获取区域项目列表 - 选中
        /// </summary>
        /// <param name="parentid"></param>
        /// <returns></returns>
        public ActionResult GetRegionFunction(int parentid = 0, int areaid = 1,int userid = 0)
        {
            #region 权限限制   
            int userId = CurrentUser.UserData.F_UserId;
            int roleId = CurrentUser.UserData.F_RoleId;
            int userRegionId = CurrentUser.UserData.RegionId;  //项目id      
            string sql = $" F_AreaId = {areaid} ";
            if (roleId != 17)
            {
                //获取用户所在项目的区域，项目，楼号信息
                sql += $" AND (F_RegionId = {userRegionId} OR F_ParentId = {userRegionId} OR F_RegionId IN (SELECT F_ParentId FROM dbo.T_Cus_RegionCategory WHERE F_RegionId = {userRegionId})) ";
            }
            #endregion

            var cus_RegionList = bllCus_Region.DataTableToList(bllCus_Region.GetList($" {sql} AND F_DeleteFlag = 0 ORDER BY F_Sort,F_RegionId ").Tables[0]);
            //if (userid == 0) { userid = 1545; }
            var list = bllRegion_UserAccount_Map.GetModelList(" UserId=" + userid).Select(x => x.RegionId).ToList();
            return Success("加载成功", cus_RegionList.Select(x => new
            {
                id = x.F_RegionId,
                pid = x.F_ParentId,
                name = x.F_RegionName,
                city = x.F_City,
                property = x.F_Property,
                ischecked = list.Where(y => y == x.F_RegionId).Count() > 0 ? true : false
            }));
        }

        /// <summary>
        /// 获取区域项目列表 - 二级
        /// </summary>
        /// <param name="parentid"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult GetRegionListTree2(int parentid = 0, int areaid = 1)
        {
            #region 权限限制   
            int userId = CurrentUser.UserData.F_UserId;
            int roleId = CurrentUser.UserData.F_RoleId;
            int userRegionId = CurrentUser.UserData.RegionId;  //项目id      
            string sql = $" F_AreaId = {areaid} ";
            if (roleId != 17)
            {
                //获取用户所在项目的区域，项目，楼号信息
                sql += $" AND (F_RegionId = {userRegionId} OR F_ParentId = {userRegionId} OR F_RegionId IN (SELECT F_ParentId FROM dbo.T_Cus_RegionCategory WHERE F_RegionId = {userRegionId})) ";
            }
            #endregion

            var listCus_Region = bllCus_Region.DataTableToList(bllCus_Region.GetList($" {sql} AND F_DeleteFlag = 0 ORDER BY F_Sort,F_RegionId ").Tables[0]);
            var list1 = listCus_Region.Where(x => x.F_ParentId == parentid).ToList();    //一级区域id
            var regionids = list1.Select(x => x.F_RegionId).ToList();
            string idd = "";    //二级项目id
            foreach (var item in regionids)
            {
                idd += item + ",";
            }
            var list2 =  listCus_Region.Where(x => idd.TrimEnd(',').Contains((x.F_ParentId ?? 0).ToString()) && x.F_ParentId !=0).ToList();
            list1.AddRange(list2);  //合并list
            var modelList = new List<Cus_RegionTreeModel>();
            for (int i = 0; i < list1.Count; i++)
            {
                var model = new Cus_RegionTreeModel();
                model.id = list1[i].F_RegionId;//当前功能ID
                model.ParentId = list1[i].F_ParentId ?? 0;
                model.text = list1[i].F_RegionName;
                model.city = list1[i].F_City;
                model.property = list1[i].F_Property;
                modelList.Add(model);
            }
            return Success("获取成功", modelList);
        }

        /// <summary>
        /// 获取区域项目,楼盘 树形下拉 - 不用
        /// </summary>
        /// <param name="parentid"></param>
        /// <returns></returns>
        public ActionResult GetListTreeDrop(int parentid = 0,int areaid = 1)
        {
            var list = bllCus_Region.DataTableToList(bllCus_Region.GetList(" F_AreaId = " + areaid + " AND F_DeleteFlag = 0 ORDER BY F_Sort,F_RegionId ").Tables[0]);    //不在此处添加搜素条件，计划改为缓存
            List<Cus_RegionTreeModel> modelList = BindTree(list, parentid);
            if (modelList != null)
            {
                if (modelList.Count > 0)
                    return Success("获取成功", modelList);
            }
            return Success("获取成功", null);
        }

        /// <summary>
        /// tree  树形部门 - 不用
        /// </summary>
        /// <param name="tab"></param>
        /// <param name="parentid"></param>
        /// <returns></returns>
        private List<Cus_RegionTreeModel> BindTree(List<T_Cus_RegionCategory> list, int parentid)
        {
            if (list.Count > 0)
            {
                var plist = list.Where(x => x.F_ParentId == parentid).ToList();
                List<Cus_RegionTreeModel> modelList = new List<Cus_RegionTreeModel>();
                for (int i = 0; i < plist.Count; i++)
                {
                    Cus_RegionTreeModel model = new Cus_RegionTreeModel();
                    int currentID = plist[i].F_RegionId;//当前功能ID
                    model.id = currentID;
                    model.ParentId = plist[i].F_ParentId ?? 0;
                    model.text = plist[i].F_RegionName;
                    model.city = plist[i].F_City;
                    model.property = plist[i].F_Property;
                    var list2 = list.Where(x => x.F_ParentId == currentID).OrderByDescending(x => x.F_Sort).ToList();
                    if (list2 != null && list2.Count > 0)
                    {
                        model.children = BindTree(list, currentID);
                    }
                    modelList.Add(model);
                }
                return modelList;
            }
            return null;
        }

        #endregion

    }
}