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.Traffic
{
    [Authorize]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class SetWorkTimeController : BaseController
    {
        private readonly ISys_WorkTimesRepository _sys_worktimeRepository;
        private readonly ISys_SeatGroupRepository _sys_seatGroupRepository;
        public SetWorkTimeController(ISys_WorkTimesRepository sys_worktimeRepository,
            ISys_SeatGroupRepository sys_seatGroupRepository)
        {
            _sys_worktimeRepository = sys_worktimeRepository;
            _sys_seatGroupRepository = sys_seatGroupRepository;
        }

        /// <summary>
        /// 获取工作时间列表
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListsByPage(string key,string groupcode, 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 (groupcode))
                conModels.Add(new ConditionalModel() { FieldName = "F_GroupCode", ConditionalType = ConditionalType.Equal, FieldValue = groupcode });
            if (!string.IsNullOrEmpty(key))
            {
                conModels.Add(new ConditionalCollections()
                {
                    ConditionalList = new List<KeyValuePair<WhereType, ConditionalModel>>()
                    {
                        new  KeyValuePair<WhereType, ConditionalModel>(WhereType.And, new ConditionalModel() { FieldName = "F_Name", ConditionalType = ConditionalType.Like, FieldValue = key }),
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or , new ConditionalModel() { FieldName = "F_GroupCode", 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_worktimeRepository.GetListByPage(conModels, new MyPageModel() { PageIndex = pageindex, PageSize = pagesize, PageCount = recordCount }, "F_CreateOn desc");

            return Success("成功", WokeTimes( list));
        }
        private PageData <T_Sys_WorkTimes > WokeTimes(PageData<T_Sys_WorkTimes> pageData )

        {
            foreach (var it in pageData.Rows )
            {
                it.F_GroupCode = _sys_seatGroupRepository.GetListALL(x => x.F_ZXZCode == it.F_GroupCode).Result != null ? _sys_seatGroupRepository.GetListALL(x => x.F_ZXZCode == it.F_GroupCode).Result.FirstOrDefault().F_ZXZName :"";
            }
            return pageData;
        }
        /// <summary>
        /// 获取实体
        /// </summary>
        [HttpGet("getdetails")]
        public async Task<IActionResult> GetDetails(int id)
        {
            if (id > 0)
            {
                var dModel = await _sys_worktimeRepository.GetSingle(x => x.F_Id == id && x.F_State == (int)EnumDelState.Enabled);

                if (dModel != null)
                {
                    return Success("获取工作时间成功", dModel);
                }
                else
                {
                    return Error("获取工作时间失败");
                }
            }
            else
            {
                return Error("获取参数失败");
            }
        }
      
        /// <summary>
        /// 添加工作时间
        /// </summary>
        [HttpPost("add")]
        public async Task<IActionResult> Add(WorkTimeInput input)
        {
            #region 验证
            if (string.IsNullOrWhiteSpace(input.startdate))
            {
                return Error("开始时间不能为空");
            }
            if (string.IsNullOrWhiteSpace(input.enddate))
            {
                return Error("结束时间不能为空");
            }
            DateTime st = new DateTime(), et = new DateTime();
            if (!DateTime.TryParse(input.startdate, out st))
                return Error("开始时间格式不正确");
            if (!DateTime.TryParse(input.enddate, out et))
                return Error("结束时间格式不正确");
            if (await GetExistAsync(input.startdate, input.enddate, input.groupcode, input.id))
                return Error("已存在此时段的记录，请重新输入！");
            #endregion
            T_Sys_WorkTimes clmodel = new T_Sys_WorkTimes();
            clmodel.F_StartDate = input.startdate.Trim();
            clmodel.F_EndDate = input.enddate.Trim();
            clmodel.F_GroupCode = input.groupcode;
            clmodel.F_Name = input.name;
            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_worktimeRepository.Add(clmodel);
            if (res > 0)
                return Success("保存成功");
            else
            {
                return Error("保存失败");
            }
        }

        /// <summary>
        /// 修改工作时间
        /// </summary>
        [HttpPost("update")]
        public async Task<IActionResult> Edit(WorkTimeInput input)
        {
            #region
            if (input.id <= 0)
                return Error("请选择要编辑的数据");
            if (string.IsNullOrWhiteSpace(input.startdate))
            {
                return Error("开始时间不能为空");
            }
            if (string.IsNullOrWhiteSpace(input.enddate))
            {
                return Error("结束时间不能为空");
            }
            DateTime st = new DateTime(), et = new DateTime();
            if (!DateTime.TryParse(input.startdate, out st))
                return Error("开始时间格式不正确");
            if (!DateTime.TryParse(input.enddate, out et))
                return Error("结束时间格式不正确");
            if (await GetExistAsync(input.startdate,input.enddate,input.groupcode, input.id))
                return Error("已存在此时段的记录，请重新输入！");
            #endregion

            var clmodel = await _sys_worktimeRepository.GetSingle(x => x.F_Id == input.id && x.F_State == (int)EnumDelState.Enabled);
            if (clmodel == null)
                return Error("信息获取失败");
            clmodel.F_StartDate = input.startdate.Trim();
            clmodel.F_EndDate = input.enddate.Trim();
            clmodel.F_GroupCode = input.groupcode.Trim();
            clmodel.F_Name = input.name.Trim();
            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_worktimeRepository.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_worktimeRepository.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_worktimeRepository.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> GetExistAsync(string startdate,string enddate,string groupcode, int id)
        {

            Expression<Func<T_Sys_WorkTimes, bool>> eq = a => a.F_State == (int)EnumDelState.Enabled;
            eq = eq.And(b => b.F_StartDate == startdate);
            eq = eq.And(b => b.F_EndDate == enddate);
            if (!string.IsNullOrWhiteSpace(groupcode))
                eq = eq.And(b => b.F_GroupCode == groupcode);
            if(id>0)
                eq = eq.And(b => b.F_Id != id);
            long c = await _sys_worktimeRepository.GetCount(eq);

            return c > 0;
        }
        #endregion
    }
}