using CallCenter.Utility;
using CallCenterApi.Interface.Controllers.Base;
using CallCenterApi.Interface.Models.Input;
using CallCenterApi.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers
{
    //[Authority]
    public class SysConfigController : BaseController
    {
        private BLL.T_Sys_SystemConfig sysConfigBLL = new BLL.T_Sys_SystemConfig();

        #region 基础数据管理

        /// <summary>
        /// 获取基础数据列表
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult GetList()
        {
            string Value = RequestString.GetQueryString("Value");
            string Code = RequestString.GetQueryString("Code");
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            var sql = "";
            if (!string.IsNullOrWhiteSpace(Value))
            {
                sql += " and F_ParamValue like '%" + Value + "%' ";
            }
            if (!string.IsNullOrWhiteSpace(Code))
            {
                sql += " and F_ParamCode like '%" + Code + "%' ";
            }
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }

            int recordCount = 0;
            Model.PageData<Model.T_Sys_SystemConfig> pageModel = new Model.PageData<Model.T_Sys_SystemConfig>();

            var dt = BLL.PagerBLL.GetListPager(
                "T_Sys_SystemConfig",
                "F_ParamId",
                "*",
                sql,
                "ORDER BY F_ParamId desc",
                pagesize,
                pageindex,
                true,
                out recordCount);
            var obj = new
            {
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());

        }

        /// <summary>
        /// 获取实体
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult GetModel(int id = 0)
        {
            var model = sysConfigBLL.GetModel(id);
            if (model == null)
                return Error("获取失败，该条数据不存在");

            return Success("获取成功", model);
        }

        /// <summary>
        /// 添加基础数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// [Authority]
        public ActionResult Add(SysConfigInput input)
        {
            var sysConfig = new Model.T_Sys_SystemConfig();
            sysConfig.F_ParamCode = input.Code;
            sysConfig.F_ParamValue = input.Value;
            sysConfig.F_ParamDes = input.Des;
            sysConfig.F_State = 0;
            if (sysConfigBLL.Add(sysConfig) > 0)
                return Success("添加成功");
            else
                return Error("添加失败");

        }

        /// <summary>
        /// 修改基础数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult Edit(SysConfigInput input)
        {
            if (input.Id <= 0) return Error("不存在此条数据");
            var sysConfig = sysConfigBLL.GetModel(input.Id);
            if (sysConfig == null) return Error("不存在此条数据");
            sysConfig.F_ParamCode = input.Code;
            sysConfig.F_ParamValue = input.Value;
            sysConfig.F_ParamDes = input.Des;
            sysConfig.F_State = 0;
            if (sysConfigBLL.Update(sysConfig))
                return Success("修改成功");
            else
                return Error("修改失败");

        }

        /// <summary>
        /// 删除基础数据
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult Delete(string[] ids)
        {

            if (ids != null)
            {
                var str = string.Join(",", ids);
                if (sysConfigBLL.DeleteList(str))
                    return Success("删除成功");
                else
                    return Error("删除失败");
            }
            else
                return Error("删除失败");

        }

        #endregion

        #region 邮箱设置管理
        /// <summary>
        /// 获取邮箱设置值
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetEmailValue()
        {
            string MailName = Configs.GetValue("MailName");
            string MailServer = Configs.GetValue("MailServer");
            string MailUserName = Configs.GetValue("MailUserName");
            string MailPassword = Configs.GetValue("MailPassword");
            var obj = new
            {
                mailName = MailName,
                mailServer = MailServer,
                mailUserName = MailUserName,
                mailPassword = MailPassword
            };
            return Success("获取成功", obj);
        }
        /// <summary>
        /// 保存邮箱设置
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult SaveEmailValue()
        {
            string mailName = RequestString.GetFormString("mailName");
            string mailServer = RequestString.GetFormString("mailServer");
            string mailUserName = RequestString.GetFormString("mailUserName");
            string mailPassword = RequestString.GetFormString("mailPassword");
            //if (string.IsNullOrEmpty(mailName)) {
            //    return Error("邮箱名称不能为空");
            //}
            if (string.IsNullOrEmpty(mailServer))
            {
                return Error("邮箱主机不能为空");
            }
            if (string.IsNullOrEmpty(mailUserName))
            {
                return Error("邮箱地址不能为空");
            }
            if (string.IsNullOrEmpty(mailPassword))
            {
                return Error("邮箱密码不能为空");
            }
            Configs.SetValue("MailName", mailName);
            Configs.SetValue("MailServer", mailServer);
            Configs.SetValue("MailUserName", mailUserName);
            Configs.SetValue("MailPassword", mailPassword);
            return Success("保存成功");
        }
        #endregion

        #region 坐席数量限制授权设置

        /// <summary>
        /// 获取一条详细信息 Id
        /// </summary>
        /// <param name="infoid"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult GetSeatPermissionInfo()
        {
            Model.T_Sys_SeatPermissionConfig model = new Model.T_Sys_SeatPermissionConfig();
            BLL.T_Sys_SeatPermissionConfig bll = new BLL.T_Sys_SeatPermissionConfig();
            model = bll.GetModel();
            if (model != null)
            {
                model.F_PassHash = null;
                model.F_SaltValue = null;
                model.F_SecurityKey = SysInformationHelper.GetPCUniqueIdentificationCode(); //16字节的计算机的唯一标识代码
                return Success("获取成功", model);
            }
            else
            {
                return Error("获取失败,没有初始化信息");
            }
        }
        /// <summary>
        /// 保存坐席限制数据
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult SaveSeatPermission(T_Sys_SeatPermissionConfig input)
        {
            string saltValue = string.Empty;
            int maxSeat = int.Parse(input.F_MaxSeat.ToString());
            string securityKey = string.IsNullOrEmpty(input.F_SecurityKey) ? SysInformationHelper.GetPCUniqueIdentificationCode() : input.F_SecurityKey;
            string passHash = SaltAndHashHelper.GetHashSha256AndSalt(maxSeat + securityKey, out saltValue); //对密码进行加密

            Model.T_Sys_SeatPermissionConfig model = new Model.T_Sys_SeatPermissionConfig();
            BLL.T_Sys_SeatPermissionConfig bll = new BLL.T_Sys_SeatPermissionConfig();
            if (maxSeat <= 0)
            {
                return Error("参数不能为空");
            }
            if (!bll.Exists())
            {
                model.F_MaxSeat = maxSeat;
                model.F_PassHash = passHash;
                model.F_SaltValue = saltValue;
                model.F_SecurityKey = securityKey;
                int n = bll.Add(model);
                if (n > 0)
                {
                    return Success("添加成功");
                }
                else
                {
                    return Error("添加失败");
                }
            }
            else
            {
                model = bll.GetModel();
                if (model != null)
                {
                    model.F_MaxSeat = maxSeat;
                    model.F_PassHash = passHash;
                    model.F_SaltValue = saltValue;
                    model.F_SecurityKey = securityKey;
                    if (bll.Update(model))
                    {
                        return Success("修改成功");
                    }
                    else
                    {
                        return Error("修改失败");
                    }
                }
                return Error("信息不存在");
            }
        }

        /// <summary>
        /// 判断坐席限制权限
        /// </summary>
        /// <param name="currentSeat">当前坐席数</param>
        /// <returns></returns>
        public bool IsValidSeatPermission()
        {
            Model.T_Sys_SeatPermissionConfig model = new Model.T_Sys_SeatPermissionConfig();
            BLL.T_Sys_SeatPermissionConfig bll = new BLL.T_Sys_SeatPermissionConfig();
            BLL.T_Sys_UserAccount bllU = new BLL.T_Sys_UserAccount();
            int currentSeat = bllU.GetRecordCount(" F_SeatFlag = 1 ");  // and F_DeleteFlag = 0坐席角色用户数量 标志(0：非话务；1话务标志);F_DeleteFlag为0时是开启
            model = bll.GetModel();
            int maxSeat = int.Parse(model.F_MaxSeat.ToString());
            string securityKey = model.F_SecurityKey;
            string passHash = model.F_PassHash; //对密码进行加密
            string saltValue = model.F_SaltValue;
            string passHashNew = SaltAndHashHelper.GetHashSha256(maxSeat + securityKey, saltValue); //将用户数据的密码采用已知的盐值进行加密
            //校验密码hash值是否一致
            if (maxSeat > currentSeat)
            {
                return passHashNew.Equals(passHash);
            }
            else
            {
                return false;
            }
        }

        #endregion

        #region 坐席组参数
        /// <summary>
        /// 获取坐席组参数
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetZXZValue()
        {
            string zipcode = Configs.GetValue("CallOutZipCode");
            string bfix = Configs.GetValue("CallOutBPre");
            string wfix = Configs.GetValue("CallOutWPre");
            var obj = new
            {
                zipcode = zipcode,
                bfix = bfix,
                wfix = wfix
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 更新坐席组参数
        /// </summary>
        /// <param name="zipcode"></param>
        /// <param name="bfix"></param>
        /// <param name="wfix"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult UpdateZXZValue(string zipcode, string bfix, string wfix)
        {
            Configs.SetValue("CallOutZipCode", zipcode);
            Configs.SetValue("CallOutBPre", bfix);
            Configs.SetValue("CallOutWPre", wfix);

            return Success("更新成功");
        } 
        #endregion

    }
}