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

namespace CallCenterApi.Interface.Controllers.customer
{
    [Authority]
    public class AddressBookController : BaseController
    {
        BLL.T_Cus_AddressBook bll = new BLL.T_Cus_AddressBook();
        BLL.T_Sys_UserAccount bllUser = new BLL.T_Sys_UserAccount();

        /// <summary>
        /// 获取通讯录列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetList()
        {
            string sql = " and F_IsDelete=0";
            DataTable dt = new DataTable();
            string keyWord = HttpUtility.UrlDecode(RequestString.GetQueryString("keyWord"));
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            if (keyWord.Trim() != "" && keyWord != "undefined")
            {
                sql += " and (F_Name like '%" + keyWord + "%' or F_Telephone like '%" + keyWord + "%' or F_Mobile like '%" + keyWord + "%' or F_ElseMobile like '%" + keyWord + "%' or F_Company like '%" + keyWord + "%' or F_Department like '%" + keyWord + "%' or F_Position like '%" + keyWord + "%') ";
            }
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }
            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            int recordCount = 0;
            string cols = "*";
            //,dbo.GetDictionaryName(F_CompanyId) as F_Company,"
            //+ "dbo.GetDictionaryName(F_DepartmentId) as F_Department,"
            //+ "dbo.GetDictionaryName(F_PositionId) as F_Position
            dt = BLL.PagerBLL.GetListPager(
                "T_Cus_AddressBook",
                "F_UserId",
                cols,
                sql,
                "ORDER BY F_UserId desc",
                pagesize,
                pageindex,
                true,
                out recordCount);

            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };

            return Content(obj.ToJson());
        }

        /// <summary>
        /// 获取一条详细信息 Id
        /// </summary>
        /// <param name="infoid"></param>
        /// <returns></returns>
        public ActionResult GetInfo(string infoid)
        {
            if (infoid != null && infoid.Trim() != "")
            {
                Model.T_Cus_AddressBook model = bll.GetModel(int.Parse(infoid.Trim()));
                if (model != null)
                {
                    return Success("获取成功", model);
                }
                else
                {
                    return Error("获取失败");
                };
            }
            else
            {
                return Error("获取参数失败");
            }
        }

        /// <summary>
        /// 添加/修改通讯录
        /// </summary>
        /// <returns></returns>
        public ActionResult SaveInfo()
        {
            Model.T_Cus_AddressBook model = new Model.T_Cus_AddressBook();
            int id = RequestString.GetInt("id", 0);
            string F_Name = RequestString.GetFormString("F_Name");
            string F_Sex = RequestString.GetFormString("F_Sex");
            //string F_Birthday = RequestString.GetFormString("F_Birthday");
            //string F_IDCard = RequestString.GetFormString("F_IDCard");
            string F_Address = RequestString.GetFormString("F_Address");
            //string F_Education = RequestString.GetFormString("F_Education");
            string F_Email = RequestString.GetFormString("F_Email");
            string F_Telephone = RequestString.GetFormString("F_Telephone");
            string F_Mobile = RequestString.GetFormString("F_Mobile");
            string F_ElseMobile = RequestString.GetFormString("F_ElseMobile");
            //int F_CompanyId = RequestString.GetInt("F_CompanyId", 0);
            //int F_DepartmentId = RequestString.GetInt("F_DepartmentId", 0);
            //int F_PositionId = RequestString.GetInt("F_PositionId", 0);
            string F_Company = RequestString.GetFormString("F_Company");
            string F_Department = RequestString.GetFormString("F_Department");
            string F_Position = RequestString.GetFormString("F_Position");
            string F_Note = RequestString.GetFormString("F_Note");

            if (string.IsNullOrEmpty(F_Name))
            {
                return Error("姓名不能為空");
            }
            if (string.IsNullOrEmpty(F_Sex))
            {
                return Error("性別不能為空");
            }
            if (string.IsNullOrEmpty(F_Mobile))
            {
                return Error("手机号不能為空");
            }
            if (id == 0)
            {
                model.F_Name = F_Name;
                model.F_Sex = F_Sex;
                //model.F_Birthday = Convert.ToDateTime(F_Birthday);
                //model.F_IDCard = F_IDCard;
                model.F_Address = F_Address;
                //model.F_Education = F_Education;
                model.F_Email = F_Email;
                model.F_Telephone = F_Telephone;
                model.F_Mobile = F_Mobile;
                model.F_ElseMobile = F_ElseMobile;
                model.F_Company = F_Company;
                model.F_Department = F_Department;
                model.F_Position = F_Position;
                model.F_Note = F_Note;
                int n = bll.Add(model);
                if (n > 0)
                {
                    return Success("添加成功", n);
                }
                else
                {
                    return Error("添加失败");
                }
            }
            else
            {
                model = bll.GetModel(id);
                if (model != null)
                {
                    model.F_UserId = id;
                    model.F_Name = F_Name;
                    model.F_Sex = F_Sex;
                    //model.F_Birthday = Convert.ToDateTime(F_Birthday);
                    // model.F_IDCard = F_IDCard;
                    model.F_Address = F_Address;
                    //model.F_Education = F_Education;
                    model.F_Email = F_Email;
                    model.F_Telephone = F_Telephone;
                    model.F_Mobile = F_Mobile;
                    model.F_ElseMobile = F_ElseMobile;
                    model.F_Company = F_Company;
                    model.F_Department = F_Department;
                    model.F_Position = F_Position;
                    model.F_Note = F_Note;
                    if (bll.Update(model))
                    {
                        return Success("修改成功");
                    }
                    else
                    {
                        return Error("修改失败");
                    }
                }
                return Error("信息不存在");
            }
        }

        /// <summary>
        /// 删除通讯录信息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DelAddressBook(string[] ids)
        {
            if (ids != null && ids.Length > 0)
            {
                string idd = " ";
                foreach (string str in ids)
                {
                    idd += str + ",";
                }
                string sql = "UPDATE dbo.T_Cus_AddressBook SET F_IsDelete = 1 WHERE F_UserId in(" + idd.TrimEnd(',') + ")";
                if (!string.IsNullOrEmpty(idd.Trim()))
                {
                    if (DbHelperSQL.ExecuteSql(sql) > 0)
                    {
                        return Success("设置成功");
                    }
                    else
                    {
                        return Error("设置失败");
                    }
                }
                else
                {
                    return Error("请选择用户");
                }
            }
            else
            {
                return Error("获取参数失败");
            }
        }

        /// <summary>
        /// 导入通讯录
        /// </summary>
        /// <returns></returns>
        public ActionResult ImportAddressBook()
        {
            NPOIHelper npoi = new NPOIHelper();
            //HttpPostedFile _upfile = RequestString.GetFile("upFile");

            if (Request.Files.Count <= 0)
                return Error("请选中导入的Excel文件");
            int headrow = 0;
            DataTable dt = npoi.ExcelToTable(Request.Files[0], headrow);
            foreach (DataRow dr in dt.Rows)
            {
                string ddd = dr[0].ToString();
            }
            foreach (DataRow dr in dt.Rows)
            {
                headrow = headrow + 1;
                if (dr[0].ToString() != "")
                {
                    Model.T_Cus_AddressBook model = new Model.T_Cus_AddressBook();
                    model.F_Name = dr[0].ToString();                //姓名
                    model.F_Sex = dr[1].ToString();                 //性别
                    //if (!string.IsNullOrEmpty(dr[2].ToString())) {
                    //    model.F_Birthday = DateTime.FromOADate(double.Parse(dr[2].ToString()));    //生日
                    //}                    
                    //model.F_IDCard = dr[3].ToString();                  //身份证
                    //model.F_Education = dr[5].ToString();               //学历
                    if (!string.IsNullOrEmpty(dr[2].ToString()))
                    {
                        model.F_Address = dr[2].ToString();                 //地址
                    }
                    if (!string.IsNullOrEmpty(dr[3].ToString()))
                    {
                        model.F_Email = dr[3].ToString();                   //邮件
                    }
                    if (!string.IsNullOrEmpty(dr[4].ToString()))
                    {
                        model.F_Telephone = dr[4].ToString();               //单位电话
                    }
                    model.F_Mobile = dr[5].ToString();                  //手机号
                    if (!string.IsNullOrEmpty(dr[6].ToString()))
                    {
                        model.F_ElseMobile = dr[6].ToString();              //其他电话
                    }
                    //导入名称，获取ID
                    //model.F_CompanyId = GetDictionaryValueIdByName(dr[10].ToString());    //单位Id
                    //model.F_DepartmentId = GetDictionaryValueIdByName(dr[11].ToString()); //部门Id
                    //model.F_PositionId = GetDictionaryValueIdByName(dr[12].ToString());   //职务Id
                    if (!string.IsNullOrEmpty(dr[7].ToString()))
                    {
                        model.F_Company = dr[7].ToString();    //单位Id
                    }
                    if (!string.IsNullOrEmpty(dr[8].ToString()))
                    {
                        model.F_Department = dr[8].ToString(); //部门Id
                    }
                    if (!string.IsNullOrEmpty(dr[9].ToString()))
                    {
                        model.F_Position = dr[9].ToString();   //职务Id
                    }
                    if (!string.IsNullOrEmpty(dr[10].ToString()))
                    {
                        model.F_Note = dr[10].ToString();                    //备注
                    }
                    if (new BLL.T_Cus_AddressBook().Add(model) <= 0)
                    {
                        return Error("第" + headrow + "行，导入失败!");
                    }
                }
                else
                {
                    return Error("第" + headrow + "行，第1，2列信息不能为空，未导入");
                }
            }
            return Success("导入成功");
        }
        /// <summary>
        /// 数据字典 获取ID通过名称
        /// </summary>
        /// <param name="Value"></param>
        /// <returns></returns>
        public int GetDictionaryValueIdByName(string Value)
        {
            int n = 0;
            BLL.T_Sys_DictionaryValue bll = new BLL.T_Sys_DictionaryValue();
            var listmodel = bll.GetModelList(" F_Value = '" + Value + "' ").FirstOrDefault();
            if (listmodel != null)
            {
                n = listmodel.F_ValueId;
            }
            return n;
        }

        /// <summary>
        /// 导出通讯录信息
        /// </summary>
        /// <returns></returns>
        public ActionResult ExportAddressBook()
        {
            string sqlwhere = string.Empty;
            BLL.T_Cus_AddressBook bll = new BLL.T_Cus_AddressBook();
            NPOIHelper npoi = new NPOIHelper();
            string keyWord = HttpUtility.UrlDecode(RequestString.GetQueryString("keyWord"));
            if (keyWord.Trim() != "" && keyWord != "undefined")
            {
                sqlwhere += " and (F_Name like '%" + keyWord + "%' or F_Telephone like '%" + keyWord + "%' or F_Mobile like '%" + keyWord + "%' or F_ElseMobile like '%" + keyWord + "%' or F_Company like '%" + keyWord + "%' or F_Department like '%" + keyWord + "%' or F_Position like '%" + keyWord + "%') ";
            }
            string sql = "SELECT F_Name,F_Sex,F_Address,F_Email,F_Telephone,F_Mobile,F_ElseMobile,F_Company,F_Department,F_Position,F_Note "
                    + "FROM T_Cus_AddressBook "
                    + "WHERE  F_IsDelete=0 " + sqlwhere;
            var dt = DbHelperSQL.Query(sql).Tables[0];
            //DataTable dt = bll.GetList(" F_IsDelete=0 " + sqlwhere).Tables[0];
            string result = npoi.ExportToExcel("通讯录信息", dt, new string[] { "姓名", "性别", "地址", "邮件", "单位电话", "手机号", "其他电话", "单位", "部门", "职务", "备注" });

            return string.IsNullOrWhiteSpace(result) ? Success("导出成功") : Error("导出失败");
        }

        #region App手机端 通讯录接口
        /// <summary>
        /// 获取手机端 通讯录（通讯录和坐席合并）
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAppList(string keyWord = "")
        {
            DataTable dt = new DataTable();
            string sqlA = " and F_IsDelete = 0 AND ISNULL(F_Mobile,'')<>'' ";
            string sqlB = " and b.F_DeleteFlag = 0 AND ISNULL(F_Mobile,'')<>''";
            string sqlkey = "SELECT F_ValueId FROM T_Sys_DictionaryValue WHERE F_Value LIKE '%" + keyWord + "%'";
            if (!string.IsNullOrWhiteSpace(keyWord))
            {
                //sqlA += " and (F_Name like '%" + keyWord + "%' or F_Telephone like '%" + keyWord + "%' or F_Mobile like '%" + keyWord + "%' or F_ElseMobile like '%" + keyWord + "%' or F_CompanyId IN (" + sqlkey + ") or F_DepartmentId IN (" + sqlkey + ") or F_PositionId IN (" + sqlkey + ") ) ";
                //sqlB += " and (F_UserName like '%" + keyWord + "%' or F_Telephone like '%" + keyWord + "%' or F_Mobile like '%" + keyWord + "%' or F_HomePhone like '%" + keyWord + "%' ) ";
                sqlA += " and (F_Name like '%" + keyWord + "%' or F_Mobile like '%" + keyWord + "%' or F_CompanyId IN (" + sqlkey + ") or F_DepartmentId IN (" + sqlkey + ") or F_PositionId IN (" + sqlkey + ") ) ";
                sqlB += " and (F_UserName like '%" + keyWord + "%' or F_Mobile like '%" + keyWord + "%') ";
            }
            //List<Model.T_Cus_AddressBook> modelList = bll.GetModelList(sql);
            //过滤 - 管理员，中心领导管理员
            sqlB += " and b.F_RoleId NOT IN (SELECT F_RoleId FROM dbo.T_Sys_RoleInfo WHERE F_RoleCode IN ('GLY','ZXLDGLY'))";
            dt = DbHelperSQL.Query($"SELECT 1 AS TypeId,a.F_UserId,a.F_Name,a.F_Sex,a.F_Address,a.F_Email,a.F_Telephone,a.F_Mobile,a.F_ElseMobile,a.F_Company,a.F_Department,a.F_Position,a.F_Note FROM dbo.T_Cus_AddressBook a WHERE 1=1 {sqlA} UNION ALL SELECT 2 AS TypeId, b.F_UserId, b.F_UserName, b.F_SexFlag, '', '', b.F_Telephone, b.F_Mobile, b.F_HomePhone, '', '', '', b.F_Remark from dbo.T_Sys_UserAccount b WHERE 1=1 {sqlB}").Tables[0];
            var modelList = CallCenter.Utility.DataTableExtensions.ToList<AddressBookDto>(dt);

            List<AddressBookDto> modellists = modelList.Select(x => new AddressBookDto()
            {
                F_UserId = x.F_UserId,
                NameOneCode = ChineseToPinYin.Convert(x.F_Name).ToUpper(),            //姓名第一个字母
                F_Name = x.F_Name,            //姓名
                F_Sex = x.F_Sex,              //性别
                F_Address = x.F_Address,      //地址
                F_Email = x.F_Email,          //邮件
                F_Telephone = x.F_Telephone,  //单位电话
                F_Mobile = x.F_Mobile,        //手机号
                F_ElseMobile = x.F_ElseMobile,//其他电话
                F_Company = x.F_Company,            //单位
                F_Department = x.F_Department,      //部门
                F_Position = x.F_Position,          //职务
                F_Note = x.F_Note                   //备注
            }).ToList();
            //去掉其他元素
            List<AddressBookCodeDto> resultList = modellists.Select(x => new AddressBookCodeDto()
            {
                NameOneCode = ChineseToPinYin.GetSpellOneCode(x.F_Name).ToUpper()            //姓名第一个字母
            }).ToList();
            //去重
            for (int i = 0; i < resultList.Count; i++)  //外循环是循环的次数
            {
                for (int j = resultList.Count - 1; j > i; j--)  //内循环是 外循环一次比较的次数
                {
                    if (resultList[i].NameOneCode == resultList[j].NameOneCode)
                    {
                        resultList.RemoveAt(j);
                    }
                }
            }
            //排序
            var modelListOrder = resultList.OrderBy(x => x.NameOneCode);

            //获取数组
            var list = new List<AddressBookCodeDto>();
            foreach (var item in modelListOrder)
            {
                var modellist_olds = modellists.Where(y => (y.NameOneCode).Substring(0, 1) == item.NameOneCode).ToList();

                list.Add(new AddressBookCodeDto
                {
                    NameOneCode = item.NameOneCode,
                    AddressBooklist = modellist_olds
                });
            }

            var obj = new
            {
                state = "success",
                message = "获取成功",
                rows = list
            };
            return Content(obj.ToJson());

            #region 不用

            //string keyWord = string.Empty;
            //DataTable dt = new DataTable();
            //string sql = " 1=1 and F_IsDelete=0 ";

            //keyWord = RequestString.GetQueryString("keyWord");
            //string sqlkey = "SELECT F_ValueId FROM T_Sys_DictionaryValue WHERE F_Value LIKE '%" + keyWord + "%'";
            //if (!string.IsNullOrWhiteSpace(keyWord))
            //{
            //    sql += " and (F_Name like '%" + keyWord + "%' or F_Telephone like '%" + keyWord + "%' or F_Mobile like '%" + keyWord + "%' or F_ElseMobile like '%" + keyWord + "%' or F_CompanyId IN (" + sqlkey + ") or F_DepartmentId IN (" + sqlkey + ") or F_PositionId IN (" + sqlkey + ") ) ";
            //}
            //List<Model.T_Cus_AddressBook> modelList = bll.GetModelList(sql);
            //return Success("获取成功",
            //    modelList.Select(x => new
            //    {
            //        F_UserId = x.F_UserId,
            //        F_Name = x.F_Name,            //姓名
            //        F_Sex = x.F_Sex,              //性别
            //                                      //F_Birthday = x.F_Birthday,    //生日
            //                                      //F_IDCard = x.F_IDCard,        //身份证
            //                                      //F_Education = x.F_Education,  //学历
            //        F_Address = x.F_Address,      //地址
            //        F_Email = x.F_Email,          //邮件
            //        F_Telephone = x.F_Telephone,  //单位电话
            //        F_Mobile = x.F_Mobile,        //手机号
            //        F_ElseMobile = x.F_ElseMobile,//其他电话
            //                                      //F_CompanyId = x.F_CompanyId,        //单位Id
            //        F_Company = x.F_Company,            //单位
            //                                            //F_DepartmentId = x.F_DepartmentId,  //部门Id
            //        F_Department = x.F_Department,      //部门
            //                                            //F_PositionId = x.F_PositionId,      //职务Id
            //        F_Position = x.F_Position,          //职务
            //        F_Note = x.F_Note                   //备注
            //    })
            //    );

            #endregion
        }

        /// <summary>
        /// 获取手机端 通讯录（坐席）
        /// </summary>
        /// <param name="rolecodeid">rolecodeid:
        /// --1热线领导组 （中心领导ZXLD） - 中心领导管理员ZXLDGLY
        /// --2话务组	（中心话务员ZXHWY 话务主管ZXBZ 坐席班长ZXBZ ）导播话务员
        /// --3承办单位 （网络单位WLDW）
        /// --4调度组（调度专员ZXLD）
        /// <returns></returns>
        public ActionResult GetAppUserAccountList(int roleid = 0)
        {
            DataTable dt = new DataTable();
            string sql = " 1=1 and F_DeleteFlag=0 AND ISNULL(F_Mobile,'')<>'' ";
            if (roleid>0)
            {
                sql += $" and F_RoleId = {roleid} ";
            }
            List<Model.T_Sys_UserAccount> modelList = bllUser.GetModelList(sql);

            List<AddressBookDto> modellists = modelList.Select(x => new AddressBookDto()
            {
                TypeId = 1,
                F_UserId = x.F_UserId,
                NameOneCode = ChineseToPinYin.Convert(x.F_UserName).ToUpper(),            //姓名第一个字母
                F_Name = x.F_UserName,          //姓名
                F_Sex = x.F_SexFlag,            //性别
                F_Address = "",                 //地址
                F_Email = "",                   //邮件
                F_Telephone = x.F_Telephone,    //单位电话
                F_Mobile = x.F_Mobile,          //手机号
                F_ElseMobile = x.F_HomePhone,   //其他电话
                F_Company = "",                 //单位
                F_Department = "",              //部门
                F_Position = "",                //职务
                F_Note = x.F_Remark             //备注
            }).ToList();
            //去掉其他元素
            List<AddressBookCodeDto> resultList = modellists.Select(x => new AddressBookCodeDto()
            {
                NameOneCode = ChineseToPinYin.GetSpellOneCode(x.F_Name).ToUpper()            //姓名第一个字母
            }).ToList();
            //去重
            for (int i = 0; i < resultList.Count; i++)  //外循环是循环的次数
            {
                for (int j = resultList.Count - 1; j > i; j--)  //内循环是 外循环一次比较的次数
                {
                    if (resultList[i].NameOneCode == resultList[j].NameOneCode)
                    {
                        resultList.RemoveAt(j);
                    }
                }
            }
            //排序
            var modelListOrder = resultList.OrderBy(x => x.NameOneCode);

            //获取数组
            var list = new List<AddressBookCodeDto>();
            foreach (var item in modelListOrder)
            {
                var modellist_olds = modellists.Where(y => (y.NameOneCode).Substring(0, 1) == item.NameOneCode).ToList();

                list.Add(new AddressBookCodeDto
                {
                    NameOneCode = item.NameOneCode,
                    AddressBooklist = modellist_olds
                });
            }

            var obj = new
            {
                state = "success",
                message = "获取成功",
                rows = list
            };
            return Content(obj.ToJson());
        }

        #endregion
    }
}