using System;
using System.Collections.Generic;
using System.Common;
using System.IRepositories;
using System.Linq;
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.Traffic
{
    [Authorize]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class SetDutyNumberController : BaseController
    {
        private readonly ISys_CallDutyNumberRepository _sys_calldutynumberRepository;
        private readonly ISys_SeatGroupRepository _sys_seatgroupRepository;
        public SetDutyNumberController(ISys_CallDutyNumberRepository sys_calldutynumberRepository, ISys_SeatGroupRepository sys_seatgroupRepository)
        {
            _sys_calldutynumberRepository = sys_calldutynumberRepository;
            _sys_seatgroupRepository = sys_seatgroupRepository;
        }
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListsByPage(string key, int groupid=0, 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 (groupid>0)
                conModels.Add(new ConditionalModel() { FieldName = "F_GroupId", ConditionalType = ConditionalType.Equal, FieldValue = groupid.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_DutyNumber", ConditionalType = ConditionalType.Like, FieldValue = key }),
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or, new ConditionalModel() { FieldName = "F_Remark", ConditionalType = ConditionalType.Like, FieldValue = key })
                    }
                });
            }
            #endregion
            int recordCount = 0;
            var list = await _sys_calldutynumberRepository.GetListViewByPage(conModels, new MyPageModel() { PageIndex = pageindex, PageSize = pagesize, PageCount = recordCount }, "F_CreateOn desc");
            
            return Success("成功", list);
        }

        /// <summary>
        /// 获取实体
        /// </summary>
        [HttpGet("getdetails")]
        public async Task<IActionResult> GetDetails(int id)
        {
            if (id <= 0)
                return Error("获取参数失败");
            var dModel = await _sys_calldutynumberRepository.GetSingle(x => x.F_ID == id && x.F_State == (int)EnumDelState.Enabled);

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

        /// <summary>
        /// 添加
        /// </summary>
        [HttpPost("add")]
        public async Task<IActionResult> Add(CallDutyNumberInput input)
        {
            #region 验证
            if (string.IsNullOrWhiteSpace(input.dutynumber))
            {
                return Error("值班电话不能为空");
            }
            if (input.groupid <= 0)
            {
                return Error("请选择坐席组");
            }
            DateTime st = new DateTime();
            if (!DateTime.TryParse(input.dutytime, out st))
                return Error("值班时间格式不正确");
            #endregion
            T_Sys_CallDutyNumber clmodel = new T_Sys_CallDutyNumber();
            clmodel.F_DutyNumber = input.dutynumber;
            clmodel.F_Groupid = input.groupid;
            clmodel.F_ZBTime = DateTime .Parse (  input.dutytime);
            clmodel.F_Remark = input.remark;

            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_calldutynumberRepository.Add(clmodel);
            if (res > 0)
                return Success("保存成功");
            else
            {
                return Error("保存失败");
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        [HttpPost("update")]
        public async Task<IActionResult> Edit(CallDutyNumberInput input)
        {
            #region
            if (input.id <= 0)
                return Error("请选择要编辑的数据");
            if (string.IsNullOrWhiteSpace(input.dutynumber))
            {
                return Error("值班电话不能为空");
            }
            if (input.groupid<=0)
            {
                return Error("请选择坐席组");
            }
            DateTime st = new DateTime();
            if (!DateTime.TryParse(input.dutytime, out st))
                return Error("值班时间格式不正确");
            #endregion

            var clmodel = await _sys_calldutynumberRepository.GetSingle(x => x.F_ID == input.id && x.F_State == (int)EnumDelState.Enabled);
            if (clmodel == null)
                return Error("信息获取失败");
            clmodel.F_DutyNumber = input.dutynumber;
            clmodel.F_Groupid = input.groupid;
            clmodel.F_ZBTime = DateTime.Parse(input.dutytime);
            clmodel.F_Remark = input.remark;

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

            var res = await _sys_calldutynumberRepository.Update(clmodel);

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

        [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_calldutynumberRepository.GetSingle(x => x.F_ID == item);
                    ml.F_State = (int)EnumDelState.Delete;
                    ml.F_DeleteBy = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
                    ml.F_DeleteOn = DateTime.Now;
                    if (await _sys_calldutynumberRepository.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("请选择要删除的记录");
        }
    }
}