using CallCenter.Utility;
using CallCenterApi.Interface.Controllers.Base;
using CallCenterApi.Interface.Models.Filter;
using CallCenterApi.Interface.Models.Input;
using CallCenterApi.Model;
using System;
using System.Collections.Generic;
using System.Linq;
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();

        /// <summary>
        /// 获取基础数据列表
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public ActionResult GetList(FilterSysConfig filter)
        {
            var res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                var sql = "";
                if (!string.IsNullOrWhiteSpace(filter.Value))
                {
                    sql += " and F_ParamValue like '%" + filter.Value + "%' ";
                }
                if (!string.IsNullOrWhiteSpace(filter.Code))
                {
                    sql += " and F_ParamCode like '%" + filter.Code + "%' ";
                }

                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",
                    filter.PageSize,
                    filter.PageIndex,
                    true,
                    out recordCount);
                var obj = new
                {
                    rows = dt,
                    total = recordCount
                };
                res = Content(obj.ToJson());
            }
            return res;
        }

        /// <summary>
        /// 获取实体
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ActionResult GetModel(int id = 0)
        {
            var res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                var model = sysConfigBLL.GetModel(id);
                if (model == null)
                    return Error("获取失败，该条数据不存在");

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

        /// <summary>
        /// 添加基础数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ActionResult Add(SysConfigInput input)
        {
            var res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                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)
                    res = Success("添加成功");
                else
                    res = Error("添加失败");
            }
            return res;
        }

        /// <summary>
        /// 修改基础数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ActionResult Edit(SysConfigInput input)
        {
            var res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                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))
                    res = Success("修改成功");
                else
                    res = Error("修改失败");
            }
            return res;
        }

        /// <summary>
        /// 删除基础数据
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult Delete(string[] ids)
        {
            var res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                if (ids != null)
                {
                    var str = string.Join(",", ids);
                    if (sysConfigBLL.DeleteList(str))
                        res = Success("删除成功");
                    else
                        res = Error("删除失败");
                }
                else
                    res = Error("删除失败");
            }
            return res;
        }

        #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(string usercode)
        {
            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();
            string sql = " F_SeatFlag = 1 ";
            if (!string.IsNullOrWhiteSpace(usercode))
                sql += " and F_UserCode<>'" + usercode + "' ";
            int currentSeat = bllU.GetRecordCount(sql);  //坐席角色用户数量 1中心话务员 2标志(0：非话务；1话务标志)
            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
    }
}