using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MadRunFabric.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Logging;
using DistributionApi.IRepositories;
using Api.SignToken;
using System.Security.Claims;
using MadRunFabric.Model;
using Microsoft.Extensions.Configuration;

namespace DistributionApi.Controllers
{
    /// <summary>
    /// 工单评价 - 省三院
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Route("api/[controller]")]
    [Produces("application/json")]
    public class DistriWorkOrderEvaluateController : BaseController
    {
        private readonly ILogger<DistriWorkOrderEvaluateController> _logger;
        private readonly IConfiguration _configuration;
        private readonly ISys_User_AccountRepository _sys_user_accountRepository;
        private readonly ISignTokenService _signTokenService;
        private readonly IDistri_Workorder_EvaluateRepository _distri_workorder_evaluaterepository;
        private readonly IDistri_GoodsRepository _distri_goodsrepository;
        public DistriWorkOrderEvaluateController(
           ILogger<DistriWorkOrderEvaluateController> logger,
            IConfiguration configuration,
            ISys_User_AccountRepository sys_user_accountRepository,
           ISignTokenService signTokenService,
           IDistri_Workorder_EvaluateRepository distri_workorder_evaluaterepository,
           IDistri_GoodsRepository distri_goodsrepository
           )
        {
            _logger = logger;
            _configuration = configuration;
            _sys_user_accountRepository = sys_user_accountRepository;
            _signTokenService = signTokenService;
            _distri_workorder_evaluaterepository = distri_workorder_evaluaterepository;
            _distri_goodsrepository = distri_goodsrepository;
        }

        /// <summary>
        /// 获取工单评价列表分页 by page
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet("getlistbypage")]
        public IActionResult GetListByPageAsync(string keyword, string projectid, string stime, string etime, int datetype = -1, int pageindex = 1, int pagesize = 10)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(usercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();
            
            var userinfos = _sys_user_accountRepository.GetUserInfo(usercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            //获取当天、本周、本月、本年、累计时间
            if (datetype != -1)
            {
                GetStartEndTime(datetype, out stime, out etime);
            }
            //获取数据
            int recordCount = 0;
            var result = _distri_workorder_evaluaterepository.GetListsByPage(keyword, projectid, userinfo, usercode, stime, etime, pageindex, pagesize, out recordCount);
            var obj = new
            {
                rows = result.ToList(),
                total = recordCount
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 获取当天、本周、本月、本年、累计时间
        /// </summary>
        /// <param name="datetype"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        public void GetStartEndTime(int datetype, out string start, out string end)
        {
            start = string.Empty;
            end = string.Empty;

            var datenow = DateTime.Now;
            var datestart = datenow;
            var dateend = datenow;
            switch (datetype)
            {
                case 0://当天
                    break;
                case 1://本周
                    int n = (int)datenow.DayOfWeek == 0 ? 7 : (int)datenow.DayOfWeek;
                    datestart = datenow.AddDays(1 - n);//本周周一
                    dateend = datestart.AddDays(6);//本周周日
                    break;
                case 2://本月
                    datestart = datenow.AddDays(1 - datenow.Day);  //本月月初  
                    dateend = datestart.AddMonths(1).AddDays(-1);  //本月月末  
                    break;
                case 3://本年
                    datestart = new DateTime(datenow.Year, 1, 1);  //本年年初  
                    dateend = new DateTime(datenow.Year, 12, 31);  //本年年末  
                    break;
                case 4://全部
                    break;
                default:
                    break;
            }
            if (datetype != 4)
            {
                start = datestart.ToString("yyyy-MM-dd");
                end = dateend.ToString("yyyy-MM-dd");
            }
        }

        /// <summary>
        /// 获取工单评价详情
        /// </summary>
        [HttpGet("getsingle")]
        public IActionResult GetSingleAsync(string id)
        {
            var model = _distri_workorder_evaluaterepository.GetDetails(id);
            return Success("获取成功", model);
        }

        /// <summary>
        /// 删除工单评价
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> DeleteAsync(string[] ids)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string username = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            //使用逻辑删除
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var id in ids)
                {
                    var model = await _distri_workorder_evaluaterepository.GetSingle(id);
                    model.isdelete = 1;
                    model.deleteby = usercode;
                    model.deletetime = DateTime.Now;
                    if (await _distri_workorder_evaluaterepository.UpdateOne(model))
                    {
                        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>
        /// 获取我的工单评价分页 by page
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet("getmylistbypage")]
        public IActionResult GetMyListByPageAsync(string keyword, string projectid, string stime, string etime, int datetype = -1, int pageindex = 1, int pagesize = 10)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(usercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();
            
            var userinfos = _sys_user_accountRepository.GetUserInfo(usercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            //获取当天、本周、本月、本年、累计时间
            if (datetype != -1)
            {
                GetStartEndTime(datetype, out stime, out etime);
            }
            //获取数据
            int recordCount = 0;
            var result = _distri_workorder_evaluaterepository.GetMyListsByPage(keyword, projectid, userinfo, usercode, stime, etime, pageindex, pagesize, out recordCount);
            
            var obj = new
            {
                rows = result.ToList(),
                total = recordCount
            };
            return Success("获取成功11", obj);
        }

        #endregion
    }
}