using System;
using System.Collections.Generic;
using System.Common;
using System.IRepositories;
using System.Linq;
using System.Linq.Expressions;
using System.Model;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using TVShoppingCallCenter_ZLJ.Models.Inputs;

namespace TVShoppingCallCenter_ZLJ.Controllers.System
{
    [Authorize]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class SeatGroupController : BaseController
    {
        private readonly ISys_SeatGroupRepository _sys_seatgroupRepository;
        public SeatGroupController(ISys_SeatGroupRepository sys_seatgroupRepository)
        {
            _sys_seatgroupRepository = sys_seatgroupRepository;
        }
        /// <summary>
        /// 获取坐席组列表
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [Authorize]
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListsByPage(string key, int pageindex = 1, int pagesize = 20)
        {
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            #region 条件筛选
            conModels.Add(new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.Equal, FieldValue = ((int)EnumDelState.Enabled).ToString() });

            if (!string.IsNullOrEmpty(key))
            {
                conModels.Add(new ConditionalCollections()
                {
                    ConditionalList = new List<KeyValuePair<WhereType, ConditionalModel>>()
                    {
                        new  KeyValuePair<WhereType, ConditionalModel>(WhereType.And, new ConditionalModel() { FieldName = "F_ZXZName", ConditionalType = ConditionalType.Like, FieldValue = key }),
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or , new ConditionalModel() { FieldName = "F_ZXZCode", ConditionalType = ConditionalType.Like, FieldValue = key }),
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or, new ConditionalModel() { FieldName = "F_ZXAtt", ConditionalType = ConditionalType.Like, FieldValue = key })
                    }
                });
            }
            #endregion
            int recordCount = 0;
            var list = await _sys_seatgroupRepository.GetListByPage(conModels, new MyPageModel() { PageIndex = pageindex, PageSize = pagesize, PageCount = recordCount }, "F_CreateOn desc");

            return Success("成功", list);
        }

        [Authorize]
        [HttpGet("getlistdrop")]
        public async Task<IActionResult> GetListDrop(string key)
        {
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            #region 条件筛选
            conModels.Add(new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.Equal, FieldValue = ((int)EnumDelState.Enabled).ToString() });

            if (!string.IsNullOrEmpty(key))
            {
                conModels.Add(new ConditionalCollections()
                {
                    ConditionalList = new List<KeyValuePair<WhereType, ConditionalModel>>()
                    {
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or , new ConditionalModel() { FieldName = "F_ZXZCode", ConditionalType = ConditionalType.Like, FieldValue = key }),
                        new  KeyValuePair<WhereType, ConditionalModel>(WhereType.Or, new ConditionalModel() { FieldName = "F_ZXZName", ConditionalType = ConditionalType.Like, FieldValue = key }),
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or, new ConditionalModel() { FieldName = "F_ZXAtt", ConditionalType = ConditionalType.Like, FieldValue = key })
                    }
                });

            }
            #endregion
            var list = await _sys_seatgroupRepository.GetListALL(conModels, "F_CreateOn desc");
            var result = list.Select(x => new {
                x.F_ZXZID,
                x.F_ZXZCode,
                x.F_ZXZName,
                x.F_ZXAtt
            });
            return Success("获取全部数据成功", result);
        }

        /// <summary>
        /// 获取实体
        /// </summary>
        [Authorize]
        [HttpGet("getdetails")]
        public async Task<IActionResult> GetDetails(int id)
        {
            if (id > 0)
            {
                var dModel = await _sys_seatgroupRepository.GetSingle(x => x.F_ZXZID == id && x.F_State == (int)EnumDelState.Enabled);

                if (dModel != null)
                {
                    return Success("获取坐席组成功", dModel);
                }
                else
                {
                    return Error("获取坐席组失败");
                }
            }
            else
            {
                return Error("获取参数失败");
            }
        }

        /// <summary>
        /// 添加坐席组
        /// </summary>
        [Authorize]
        [HttpPost("add")]
        public async Task<IActionResult> Add(SeatGroupInput input)
        {
            #region 验证
            if (string.IsNullOrWhiteSpace(input.zxzcode))
            {
                return Error("编号不能为空");
            }
            if (string.IsNullOrWhiteSpace(input.zxzname))
            {
                return Error("名称不能为空");
            }
            if (string.IsNullOrWhiteSpace(input.zxatt))
            {
                return Error("坐席地区号不能为空");
            }
            if (string.IsNullOrWhiteSpace(input.whwdkey))
            {
                return Error("外呼外地前缀不能为空");
            }
            if (string.IsNullOrWhiteSpace(input.whbdkey))
            {
                return Error("外呼本地前缀不能为空");
            }
            if (!ValidateString.IsNumberStr(input.whwdkey.Trim().ToString()))
            {
                return Error("外呼外地前缀必须为数字");
            }
            if (!ValidateString.IsNumberStr(input.whbdkey.Trim().ToString()))
            {
                return Error("外呼本地前缀必须为数字");
            }
            if (await GetExistByCodeAsync(input.zxzcode, 0) || await GetExistByNameAsync(input.zxzname, 0))
            {
                return Error("坐席组编号和名称必须唯一，请重新输入！");
            }
            #endregion
            T_Sys_SeatGroup clmodel = new T_Sys_SeatGroup();
            clmodel.F_ZXZCode = input.zxzcode.Trim();

            clmodel.F_IVRKey = input.ivrkey;
            clmodel.F_ZXZName = input.zxzname.Trim();
            clmodel.F_ZXAtt = input.zxatt.Trim();
            clmodel.F_WHWDKey = input.whwdkey.Trim();
            clmodel.F_WHBDKey = input.whbdkey.Trim();

            clmodel.F_Des = input.des;
            clmodel.F_CreateBy = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value; //"8000";
            clmodel.F_CreateOn = DateTime.Now;
            clmodel.F_State = (int)EnumDelState.Enabled;

            var res = await _sys_seatgroupRepository.Add(clmodel);
            if (res > 0)
                return Success("坐席组保存成功");
            else
            {
                return Error("坐席组保存失败");
            }
        }

        /// <summary>
        /// 修改坐席组
        /// </summary>
        [Authorize]
        [HttpPost("update")]
        public async Task<IActionResult> Edit(SeatGroupInput input)
        {
            #region
            if (input.id <= 0)
                return Error("请选择要编辑的坐席组");
            if (string.IsNullOrWhiteSpace(input.whwdkey))
                return Error("外呼外地前缀不能为空");
            if (string.IsNullOrWhiteSpace(input.whbdkey))
                return Error("外呼本地前缀不能为空");
            if (!ValidateString.IsNumberStr(input.whwdkey.Trim().ToString()))
            {
                return Error("外呼外地前缀必须为数字");
            }
            if (!ValidateString.IsNumberStr(input.whbdkey.Trim().ToString()))
            {
                return Error("外呼本地前缀必须为数字");
            }
            if (await GetExistByCodeAsync(input.zxzcode, input.id) || await GetExistByNameAsync(input.zxzname, input.id))
                return Error("坐席组编号和名称必须唯一，请重新输入！");
            #endregion

            var clmodel = await _sys_seatgroupRepository.GetSingle(x => x.F_ZXZID == input.id && x.F_State == (int)EnumDelState.Enabled);
            if (clmodel == null)
                return Error("信息获取失败");
            clmodel.F_ZXZCode = input.zxzcode.Trim();
            clmodel.F_ZXZName = input.zxzname.Trim();
            clmodel.F_ZXAtt = input.zxatt.Trim();
            clmodel.F_WHWDKey = input.whwdkey.Trim();
            clmodel.F_WHBDKey = input.whbdkey.Trim();

            clmodel.F_IVRKey = input.ivrkey;
            clmodel.F_Des = input.des;

            clmodel.F_LastModifyBy = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            clmodel.F_LastModifyOn = DateTime.Now;

            var res = await _sys_seatgroupRepository.Update(clmodel);

            if (res)
                return Success("坐席组保存成功");
            else
            {
                return Error("坐席组保存失败");
            }
        }

        [Authorize]
        [HttpPost("delete")]
        public async Task<IActionResult> Remove(int[] ids)
        {
            //使用逻辑删除
            //物理删除的数据无法恢复
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    var ml = await _sys_seatgroupRepository.GetSingle(x => x.F_ZXZID == item);
                    ml.F_State = (int)EnumDelState.Delete;
                    if (await _sys_seatgroupRepository.Update(ml))
                        res += 1;
                }
                if (res == ids.Length)
                    return Success("删除成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分删除失败，请查看后重新操作");
                else
                    return Error("删除失败，请查看后重新操作");
            }
            else
                return Error("请选择要删除的记录");
        }

        #region 私有方法
        /// <summary>
        /// 根据坐席组编号查询是否存在此坐席组编号
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        private async Task<bool> GetExistByCodeAsync(string code, int id)
        {
            long c = 0;
            if (id > 0)
                c = await _sys_seatgroupRepository.GetCount(x => x.F_ZXZCode.Equals(code) && x.F_ZXZID != id && x.F_State == (int)EnumDelState.Enabled);
            else
                c = await _sys_seatgroupRepository.GetCount(x => x.F_ZXZCode.Equals(code) && x.F_State == (int)EnumDelState.Enabled);

            return c > 0;
        }
        /// <summary>
        /// 根据坐席组名称查询是否存在此坐席组编号
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        private async Task<bool> GetExistByNameAsync(string name, int id)
        {
            long c = 0;
            if (id > 0)
                c = await _sys_seatgroupRepository.GetCount(x => x.F_ZXZName.Equals(name) && x.F_ZXZID != id && x.F_State == (int)EnumDelState.Enabled);
            else
                c = await _sys_seatgroupRepository.GetCount(x => x.F_ZXZName.Equals(name) && x.F_State == (int)EnumDelState.Enabled);
            
            return c > 0;
        }
        #endregion
    }
}