using System;
using System.Collections.Generic;
using System.Common;
using System.IRepositories;
using System.IRepositories.Sys;
using System.Linq;
using System.Model.Sys;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace TVShoppingCallCenter_ZLJ.Controllers.System
{
    [Authorize]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class BottomNumberController : BaseController
    {
        private readonly ISys_BottomNumberRepository _sys_bottomnumberrepository;
        private readonly ISys_SeatGroupRepository _sys_seatGroupRepository;
        public BottomNumberController(ISys_BottomNumberRepository sys_bottomnumberrepository
            , ISys_SeatGroupRepository sys_seatGroupRepository)
        {
            _sys_bottomnumberrepository = sys_bottomnumberrepository;
            _sys_seatGroupRepository = sys_seatGroupRepository;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(T_Sys_BottomNumber input)
        {
            if (string.IsNullOrEmpty(input.F_Name))
                return Error("请输入名称");
            if (string.IsNullOrEmpty(input.F_ZXZCode))
                return Error("请选择坐席组");
            if (string.IsNullOrEmpty(input.F_Tel))
                return Error("请输入底号");
            var model = await _sys_bottomnumberrepository.GetListALL(x => x.F_Tel == input.F_Tel.Trim() &&
          x.F_IsDelete == 0);
            if (model.Count ()>0)
            {
                return Error("不能添加重复的底号");
            }
            else
            {
                input.F_CreateOn = DateTime.Now;
                input.F_IsDelete = 0;
                input.F_CreateBy = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
                var res = await _sys_bottomnumberrepository.Add(input);
                if (res > 0)
                {
                    return Success("添加成功");
                }
                else
                {
                    return Error("添加失败");
                }
            }
            
        }
        /// <summary>
        /// 修改
        /// </summary>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(T_Sys_BottomNumber input)
        {
            if (input.F_ID <= 0)
                return Error("参数错误");
            if (string.IsNullOrEmpty(input.F_Name))
                return Error("请输入名称");
            if (string.IsNullOrEmpty(input.F_ZXZCode))
                return Error("请选择坐席组");
            if (string.IsNullOrEmpty(input.F_Tel))
                return Error("请输入底号");
            var model = await _sys_bottomnumberrepository.GetSingle(x => x.F_ID == input.F_ID);
            if (model == null)
                return Error("操作失败");
            var bottomnumber = await _sys_bottomnumberrepository.GetListALL(x => x.F_Tel == input.F_Tel.Trim() &&
        x.F_IsDelete == 0&&x .F_Tel != model .F_Tel );
            if (bottomnumber.Count() > 0)
            {
                return Error("不能修改为已有的底号");
            }
            else
            {
                input.F_IsDelete = 0;
                input.F_CreateBy = model.F_CreateBy;
                input.F_CreateOn = model.F_CreateOn;
                model = input;
                model.F_LastModifyOn = DateTime.Now;
                model.F_LastModifyBy = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
                var b = await _sys_bottomnumberrepository.Update(model);
                if (b)
                    return Success("修改成功");
            }
             
            return Error("修改失败");
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> Remove(int[] ids)
        {
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    var model = await _sys_bottomnumberrepository.GetSingle(x => x.F_ID == item);
                    model.F_IsDelete = (int)EnumUserCountState.Delete;
                    model.F_DeleteOn = DateTime.Now.ToLocalTime();
                    model.F_DeleteBy = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
                    if (_sys_bottomnumberrepository.Update(model).Result)
                        res += 1;
                }
                if (res == ids.Length)
                    return Success("删除成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分删除失败，请查看后重新操作");
                else
                    return Error("删除失败，请查看后重新操作");
            }
            else
                return Error("请选择要删除的记录");
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet("getlist")]
        public async Task<IActionResult> GetLisAsync(string keyword, string code, int pageindex = 1, int pagesize = 20)
        {
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            #region 条件筛选
            conModels.Add(new ConditionalModel() { FieldName = "F_IsDelete", ConditionalType = ConditionalType.Equal, FieldValue = ((int)EnumUserCountState.Enabled).ToString() });
            if (!string.IsNullOrEmpty(keyword))
            {
                conModels.Add(new ConditionalCollections()
                {
                    ConditionalList = new List<KeyValuePair<WhereType, ConditionalModel>>()
                    {
                        new  KeyValuePair<WhereType, ConditionalModel>(WhereType.And, new ConditionalModel() { FieldName = "F_Tel", ConditionalType = ConditionalType.Like, FieldValue = keyword }),
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or , new ConditionalModel() { FieldName = "F_Name", ConditionalType = ConditionalType.Like, FieldValue = keyword }),
                    }
                });
            }
            if (!string .IsNullOrEmpty (code))
            conModels.Add(new ConditionalModel() { FieldName = "F_ZXZCode", ConditionalType = ConditionalType.Equal, FieldValue = code });
            #endregion
            int recordCount = 0;
            var list = await _sys_bottomnumberrepository.GetListByPage(conModels, new MyPageModel() { PageIndex = pageindex, PageSize = pagesize, PageCount = recordCount },"F_ID DESC");


            var obj = new
            {
                state = "success",
                message = "成功",
                rows = WokeTimes(list),
                total = list.Totals,
            };

            return Content(obj.ToJson());
        }
        private PageData<T_Sys_BottomNumber> WokeTimes(PageData<T_Sys_BottomNumber> pageData)

        {
            foreach (var it in pageData.Rows)
            {
                it.F_ZXZCode  = _sys_seatGroupRepository.GetListALL(x => x.F_ZXZCode == it.F_ZXZCode).Result != null ? _sys_seatGroupRepository.GetListALL(x => x.F_ZXZCode == it.F_ZXZCode).Result.FirstOrDefault().F_ZXZName : "";
            }
            return pageData;
        }
        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpGet("getdetails")]
        public async Task<IActionResult> GetDetailsAsync(int id)
        {
            if (id <= 0)
                return Error("参数错误");

            var model = await _sys_bottomnumberrepository.GetSingle(x => x.F_ID == id);
            if (model == null)
            {
                return Error("获取失败");
            }

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