using RMYY_CallCenter_Api.DB;
using RMYY_CallCenter_Api.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace RMYY_CallCenter_Api.Controllers.System
{
    public class AddressBookController : BaseController
    {

        Bll.T_Cus_AddressBook bookbll = new Bll.T_Cus_AddressBook();
        Bll.T_Sys_UserAccount userbll = new Bll.T_Sys_UserAccount();
        Bll.T_Sys_Department departbll = new Bll.T_Sys_Department();



        /// <summary>
        /// 获取通讯录列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetList(string keyWord,string department,string company, int pageindex= 1,int pagesize= 10)
        {
            string sql = " and F_IsDelete=0";


            DataTable dt = new DataTable();

            if (!string.IsNullOrEmpty(keyWord))
            {
                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 (!string.IsNullOrEmpty(department))
            {
                sql += " and F_Department='" + department+ "'";
            }
            if (!string.IsNullOrEmpty(company))
            {
                sql +=  " and F_Company='"+company+"'";
            }
            int recordCount = 0;
 
            dt = Bll.PagerBll.GetListPager(
                "T_Cus_AddressBook",
                "F_Id",
                "*",
                sql,
                "ORDER BY F_Id 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 = bookbll.GetModel(int.Parse(infoid.Trim()));
                if (model != null)
                {
                    return Success("获取成功", model);
                }
                else
                {
                    return Error("获取失败");
                };
            }
            else
            {
                return Error("获取参数失败");
            }
        }

        /// <summary>
        /// 添加/修改通讯录
        /// </summary>
        /// <returns></returns>
        public ActionResult SaveInfo(string name, string sex, string remark,string office, string mobile="",string positon="", string depart="", string company="", string elsemobile="", string phone="",  string address="", int id=0)
        //string email="",
        {
            Model.T_Cus_AddressBook model = new Model.T_Cus_AddressBook();        
         
            if (id == 0)
            {
                model.F_Name = name;
                model.F_Sex = sex;
                model.F_Address = address;
       
                model.F_Telephone = phone;
                model.F_Mobile = mobile;
                model.F_ElseMobile = elsemobile;

                var departmodel = departbll.GetModel(Convert.ToInt32(depart));
                if (departmodel != null)
                {
                    model.F_Department = depart;
                }
                else
                {
                    model.F_Department = "0";
                }

                model.F_Position = positon;
                model.F_Company = office;
                model.F_Note = remark;
                int n = bookbll.Add(model);
                if (n > 0)
                {
                    return Success("添加成功", n);
                }
                else
                {
                    return Error("添加失败");
                }
            }
            else
            {
                model = bookbll.GetModel(id);
                if (model != null)
                {
                  //  model.F_Id = id;
                   model.F_Name = name;
                    model.F_Sex = sex;
                    model.F_Address = address;
                    //model.F_Birthday = Convert.ToDateTime(F_Birthday);
                    // model.F_IDCard = F_IDCard;
                  
                    //model.F_Education = F_Education;
                  //  model.F_Email = email;
                    model.F_Telephone = phone;
                    model.F_Mobile = mobile;
                    model.F_ElseMobile = elsemobile;

                  var departmodel= departbll.GetModel( Convert.ToInt32( depart));
                    if (departmodel != null)
                    {
                        model.F_Department = depart;
                    }
                    else
                    {
                        model.F_Department = "0";
                    }
                    
                    model.F_Position = positon;
                    model.F_Company = office;
                    model.F_Note = remark;
                    
                    if (bookbll.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_Id 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();
            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)
            {
                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_Address = dr[2].ToString();                 //地址
                    }
                    //if (!string.IsNullOrEmpty(dr[3].ToString()))
                    //{
                    //    model.F_Email = dr[3].ToString();                   //邮件
                    //}
                    if (!string.IsNullOrEmpty(dr[3].ToString()))
                    {
                        model.F_Telephone = dr[3].ToString();               //单位电话
                    }
                    model.F_Mobile = dr[4].ToString();                  //手机号
                    if (!string.IsNullOrEmpty(dr[5].ToString()))
                    {
                        model.F_ElseMobile = dr[5].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[6].ToString()))
                    {
                        model.F_Company = dr[6].ToString();    //单位Id 所在科室
                    }
                    if (!string.IsNullOrEmpty(dr[7].ToString()))
                    {
                        model.F_Department = dr[7].ToString(); //部门Id
                    }
                    if (!string.IsNullOrEmpty(dr[8].ToString()))
                    {
                        model.F_Position = dr[8].ToString();   //职务Id
                    }
                    if (!string.IsNullOrEmpty(dr[9].ToString()))
                    {
                        model.F_Note = dr[9].ToString();                    //备注
                    }
                    if (bookbll.Add(model) <= 0)
                    {
                        return Error("第" + headrow + "行，导入失败!");
                    }
                }
                else
                {
                    return Error("第" + headrow + "行，第1，2列信息不能为空，未导入");
                }
            }
            return Success("导入成功");
        }


        /// <summary>
        /// 导出通讯录信息
        /// </summary>
        /// <returns></returns>
        public ActionResult ExportAddressBook(string keyWord)
        {
            string sqlwhere = string.Empty;
            NPOIHelper npoi = new NPOIHelper();
            if (!string.IsNullOrEmpty(keyWord))
            {
                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 = bookbll.GetList(sql).Tables[0];
            string result = npoi.ExportToExcel("通讯录信息", dt, new string[] { "姓名", "性别", "地址", "邮件", "单位电话", "手机号", "其他电话", "单位", "部门", "职务", "备注" });

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

    }
}