using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using EquipmentApi.IRepositories;
using MadRunFabric.Model;
using EquipmentApi.Model.Input;
using MadRunFabric.Common;
using MadRunFabric.Common.Enums;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;

namespace EquipmentApi.Controllers.workordermanage
{
    /// <summary>
    /// 报修工单评价控制器
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class WoRepairEvaluateController : BaseController
    {
        private readonly ILogger<WoRepairEvaluateController> _logger;
        private readonly IWo_Repair_EvaluateRepository _wo_repair_evaluateRepository;

        public WoRepairEvaluateController(ILogger<WoRepairEvaluateController> logger, IWo_Repair_EvaluateRepository wo_repair_evaluateRepository,
            IWo_Repair_BaseRepository wo_repair_baseRepository, IWo_Repair_ItemsRepository wo_repair_itemsRepository)
        {
            _logger = logger;
            _wo_repair_evaluateRepository = wo_repair_evaluateRepository;
        }

        /// <summary>
        /// 分页获取
        /// </summary>
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListByPageAsync(string stime, string etime, int ismyd, int pageindex = 1, int pagesize = 10)
        {
            //排序字段
            var sort = Builders<Wo_Repair_Evaluate>.Sort.Descending("createtime");

            //根据条件查询集合
            var flist = new List<FilterDefinition<Wo_Repair_Evaluate>>();
            flist.Add(Builders<Wo_Repair_Evaluate>.Filter.Eq("isdelete", 0));

            if (!string.IsNullOrWhiteSpace(stime))
            {
                DateTime dt2 = new DateTime();
                if (DateTime.TryParse(stime.Trim() + " 00:00:00", out dt2))
                    flist.Add(Builders<Wo_Repair_Evaluate>.Filter.Gt("createtime", stime));
            }
            if (!string.IsNullOrWhiteSpace(etime))
            {
                DateTime dt2 = new DateTime();
                if (DateTime.TryParse(etime.Trim() + " 23:59:59", out dt2))
                    flist.Add(Builders<Wo_Repair_Evaluate>.Filter.Lt("createtime", etime));
            }
            if (ismyd > 0)
            {
                if (ismyd == 1)
                    flist.Add(Builders<Wo_Repair_Evaluate>.Filter.Where(c => c.score >= 3));
                else
                    flist.Add(Builders<Wo_Repair_Evaluate>.Filter.Where(c => c.score < 3));
            }

            var filter = Builders<Wo_Repair_Evaluate>.Filter.And(flist);
            var list = await _wo_repair_evaluateRepository.GetByPage(filter, pageindex, pagesize, sort);
            var count = await _wo_repair_evaluateRepository.CountAsync(filter);
            var obj = new
            {
                rows = list,
                total = count,
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 分页获取
        /// </summary>
        [HttpGet("getlistsbypage")]
        public IActionResult GetListsByPageAsync(string stime, string etime, int ismyd, int pageindex = 1, int pagesize = 10)
        {
            int recordCount = 0;
            var result = _wo_repair_evaluateRepository.GetListsByPage(stime, etime, ismyd, pageindex, pagesize, out recordCount);
            var obj = new
            {
                rows = result.ToList(),
                total = recordCount,
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 获取评价信息
        /// </summary>
        [HttpGet("getsingle")]
        public async Task<IActionResult> GetSingleAsync(string id)
        {
            var dModel = await _wo_repair_evaluateRepository.GetSingle(id.Trim());

            return Success("获取评价信息成功", dModel);

        }

        /// <summary>
        /// 删除评价信息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> RemoveAsync(string[] ids)
        {
            //使用逻辑删除
            //物理删除的数据无法恢复
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                string optuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
                foreach (var item in ids)
                {
                    var ml = await _wo_repair_evaluateRepository.GetSingle(item);
                    ml.isdelete = 1;
                    ml.deleteuser = optuser;
                    ml.deletetime = DateTime.Now;
                    if (await _wo_repair_evaluateRepository.UpdateOne(ml))
                        res += 1;
                }
                if (res == ids.Length)
                    return Success("评价信息删除成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分评价信息删除失败");
                else
                    return Error("评价信息删除失败");

            }
            else
                return Error("请选择要删除的记录");
        }
    }
}