using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using CallCenterApi.IRepositories;
using Microsoft.Extensions.Logging;
using MadRunFabric.Model;
using MadRunFabric.Common;
using Microsoft.AspNetCore.Authorization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using MongoDB.Driver;
using MadRunFabric.Model.CallCenterApi;
using System.Security.Claims;
using SignTokenApi.IRepositories;
using CallCenterApi.Input;

namespace CallCenterApi.Controllers
{
    /// <summary>
    /// 工单控制器
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class BusOrderController : BaseController
    {
        private readonly ILogger<BusOrderController> _logger;
        private readonly IBus_Order_BaseRepository _bus_order_baseRepository;
        private readonly IBus_Order_ItemRepository _bus_order_itemRepository;

        public BusOrderController(ILogger<BusOrderController> logger, IBus_Order_BaseRepository bus_order_baseRepository, IBus_Order_ItemRepository bus_order_itemRepository)
        {
            _logger = logger;
            _bus_order_baseRepository = bus_order_baseRepository;
            _bus_order_itemRepository = bus_order_itemRepository;
        }

        /// <summary>
        /// 分页获取
        /// </summary>
        [HttpGet("getlistbypage")]
        public IActionResult GetListsByPageAsync(string ordercode, string key, string phone, string province, string city, string sourceid, 
            string typeid, string deptid, string stime, string etime,int state = -1, int pageindex = 1, int pagesize = 10)
        {
            int recordCount = 0;
            var result = _bus_order_baseRepository.GetListsByPage(ordercode, key, phone, province, city, sourceid, typeid, deptid, 
                stime, etime, state, 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 ordercode)
        {
            var cls = await _bus_order_baseRepository.Get(p => p.ordercode == ordercode && p.isdelete == 0);
            var clmodel = cls.FirstOrDefault();
            if (clmodel != null)
            {
                var model = _bus_order_baseRepository.GetDetails(ordercode);
                var item = await _bus_order_itemRepository.Get(s => s.ordercode.Equals(clmodel.ordercode) & s.isdelete == 0);
                var obj = new
                {
                    model,
                    item,
                };

                return Success("获取成功", obj);
            }
            else
            {
                return Error("获取失败");
            }
        }

        /// <summary>
        /// 添加
        /// </summary>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(BusOrderBaseInput input)
        {
            if (string.IsNullOrWhiteSpace(input.phone))
            {
                return Error("请输入号码");
            }
            //if (string.IsNullOrWhiteSpace(input.title))
            //{
            //    return Error("请输入标题");
            //}
            if (string.IsNullOrWhiteSpace(input.content))
            {
                return Error("请输入内容");
            }

            Bus_Order_Base clmodel = new Bus_Order_Base();
            //时间戳作为编号
            clmodel.ordercode = DateTime.Now.ToString("yyyyMMddHHmmssfff");

            string optuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string optusername = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            clmodel.province = input.province;//省
            clmodel.city = input.city;//市
            clmodel.unique_id = input.unique_id;
            clmodel.callrecordid = input.callrecordid;
            clmodel.leaverecordid = input.leaverecordid;
            clmodel.name = input.name;
            clmodel.phone = input.phone;
            clmodel.sex = input.sex;
            clmodel.address = input.address;
            clmodel.sourceid = input.sourceid;
            clmodel.typeid = input.typeid;
            clmodel.deptid = input.deptid;
            clmodel.title = input.title;
            clmodel.content = input.content;
            if (input.files != null)
            {
                clmodel.files = input.files;
            }
            else
            {
                clmodel.files = new List<FileBaseModel>();
            }

            clmodel.state = (int)EnumOrderType.create;
            clmodel.resultfiles = new List<FileBaseModel>();

            clmodel.createuser = optuser;
            clmodel.createusername = optusername;
            clmodel.isdelete = 0;
            clmodel.createtime = DateTime.Now;

            bool bl = await _bus_order_baseRepository.Add(clmodel);

            if (bl)
            {
                AddItems(clmodel.ordercode, clmodel.state, optuser + "(" + optusername + "） 创建", clmodel.files, optuser, optusername);
                return Success("保存成功");
            }
            else
                return Error("保存失败");

        }

        /// <summary>
        /// 修改
        /// </summary>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(BusOrderBaseInput input)
        {
            string optuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string optusername = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            var cls = await _bus_order_baseRepository.Get(p => p.ordercode == input.ordercode && p.isdelete == 0);
            var clmodel = cls.FirstOrDefault();
            if (clmodel != null && clmodel.createuser == optuser && clmodel.state == (int)EnumOrderType.create)
            {
                if (string.IsNullOrWhiteSpace(input.phone))
                {
                    return Error("请输入号码");
                }
                //if (string.IsNullOrWhiteSpace(input.title))
                //{
                //    return Error("请输入标题");
                //}
                if (string.IsNullOrWhiteSpace(input.content))
                {
                    return Error("请输入内容");
                }

                clmodel.province = input.province;//省
                clmodel.city = input.city;//市
                clmodel.unique_id = input.unique_id;
                clmodel.callrecordid = input.callrecordid;
                clmodel.leaverecordid = input.leaverecordid;
                clmodel.name = input.name;
                clmodel.phone = input.phone;
                clmodel.sex = input.sex;
                clmodel.address = input.address;
                clmodel.sourceid = input.sourceid;
                clmodel.typeid = input.typeid;
                clmodel.deptid = input.deptid;
                clmodel.title = input.title;
                clmodel.content = input.content;
                if (input.files != null)
                {
                    clmodel.files = input.files;
                }
                else
                {
                    clmodel.files = new List<FileBaseModel>();
                }

                var res = await _bus_order_baseRepository.UpdateOne(clmodel);
                if (res)
                {
                    AddItems(clmodel.ordercode, clmodel.state, optuser + "(" + optusername + "） 修改", clmodel.files, optuser, optusername);
                    return Success("保存成功");
                }
                else
                    return Error("保存失败");
            }

            return Error("保存失败");
        }

        /// <summary>
        /// 处理
        /// </summary>
        [HttpPost("deal")]
        public async Task<IActionResult> UpdateDealAsync(string ordercode, string result, List<FileBaseModel> files)
        {
            if (string.IsNullOrWhiteSpace(ordercode))
            {
                return Error("参数错误");
            }
            if (string.IsNullOrWhiteSpace(result))
            {
                return Error("请输入处理结果");
            }

            string optuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string optusername = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            var cls = await _bus_order_baseRepository.Get(p => p.ordercode == ordercode && p.isdelete == 0);
            var clmodel = cls.FirstOrDefault();
            if (clmodel != null && clmodel.state == (int)EnumOrderType.create)
            {
                clmodel.state = (int)EnumOrderType.deal;
                clmodel.dealuser = optuser;
                clmodel.dealusername = optusername;
                clmodel.result = result;
                if (files != null)
                {
                    clmodel.resultfiles = files;
                }
                else
                {
                    clmodel.resultfiles = new List<FileBaseModel>();
                }

                clmodel.dealtime = DateTime.Now;

                await _bus_order_baseRepository.UpdateOne(clmodel);

                AddItems(clmodel.ordercode, clmodel.state, optuser + "(" + optusername + "） 处理，结果：" + result, clmodel.resultfiles, optuser, optusername);

                return Success("处理成功");
            }

            return Error("处理失败");
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> RemoveAsync(string[] ids, int channel = 1)
        {
            string optuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string optusername = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            //使用逻辑删除
            //物理删除的数据无法恢复
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var id in ids)
                {
                    var ml = await _bus_order_baseRepository.GetSingle(id);
                    ml.isdelete = 1;
                    ml.deleteuser = optuser;
                    ml.deletetime = DateTime.Now;
                    if (await _bus_order_baseRepository.UpdateOne(ml))
                    {
                        res += 1;
                        AddItems(ml.ordercode, ml.state, optuser + "(" + optusername + "） 删除", new List<FileBaseModel>(), optuser, optusername);
                    }
                }
                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="wocode">编号</param>
        /// <param name="wostate">状态</param>
        /// <param name="detail">处理说明</param>
        /// <param name="files">附件</param>
        /// <param name="optuser">当前操作人</param>
        /// <param name="optusername">当前操作人姓名</param>
        private async void AddItems(string ordercode, int state, string detail, List<FileBaseModel> files, string optuser, string optusername)
        {
            Bus_Order_Item itemsmodel = new Bus_Order_Item();
            itemsmodel.ordercode = ordercode;
            itemsmodel.state = state;
            itemsmodel.isdelete = 0;
            itemsmodel.createuser = optuser;
            itemsmodel.createusername = optusername;
            itemsmodel.createtime = DateTime.Now;
            itemsmodel.detail = detail;
            itemsmodel.files = files;
            await _bus_order_itemRepository.Add(itemsmodel);
        }

        /// <summary>
        /// 获取日周月年工单状态数量统计
        /// </summary>
        [HttpGet("getworkorderstatecount")]
        public async Task<IActionResult> GetWorkOrderStateCountReportAsync(int datetype = 0)
        {

            string optuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string stime = string.Empty; string etime = string.Empty;
            if (datetype != 0)
            {
                GetStartEndTime(datetype, out stime, out etime);
            }

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


            var wwcflist = flist.ToList();
            var ywcflist = flist.ToList();

            if (!string.IsNullOrWhiteSpace(stime))
            {
                wwcflist.Add(Builders<Bus_Order_Base>.Filter.Gt("createtime", DateTime.Parse(stime.Trim())));
                ywcflist.Add(Builders<Bus_Order_Base>.Filter.Gt("dealtime", DateTime.Parse(stime.Trim())));
            }
            if (!string.IsNullOrWhiteSpace(etime))
            {
                wwcflist.Add(Builders<Bus_Order_Base>.Filter.Lt("createtime", DateTime.Parse(etime.Trim())));
                ywcflist.Add(Builders<Bus_Order_Base>.Filter.Lt("dealtime", DateTime.Parse(etime.Trim())));
            }

            wwcflist.Add(Builders<Bus_Order_Base>.Filter.Eq("state", (int)EnumOrderType.create));
            var wwcfilter = Builders<Bus_Order_Base>.Filter.And(wwcflist);

            ywcflist.Add(Builders<Bus_Order_Base>.Filter.Eq("state", (int)EnumOrderType.deal));
            var ywcfilter = Builders<Bus_Order_Base>.Filter.And(ywcflist);

            var wwccount = await _bus_order_baseRepository.CountAsync(wwcfilter);
            var ywccount = await _bus_order_baseRepository.CountAsync(ywcfilter);

            var obj = new
            {
                wwccount,
                ywccount
            };

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

        /// <summary>
        /// 获取日周月年工单类型统计
        /// </summary>
        [HttpGet("getworkordertypecount")]
        public IActionResult GetWorkOrderTypeCountReport(int datetype = 0)
        {
            string optuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string stime = string.Empty; string etime = string.Empty;
            if (datetype != 0)
            {
                GetStartEndTime(datetype, out stime, out etime);
            }

            var result = _bus_order_baseRepository.GetWorkOrderTypeCountReport(stime, etime, optuser);
            return Success("获取成功", result);
        }

        /// <summary>
        /// 获取日周月年工单来源统计
        /// </summary>
        [HttpGet("getworkordersourcecount")]
        public IActionResult GetWorkOrderSourceCountReport(int datetype = 0)
        {
            string optuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string stime = string.Empty; string etime = string.Empty;
            if (datetype != 0)
            {
                GetStartEndTime(datetype, out stime, out etime);
            }

            var result = _bus_order_baseRepository.GetWorkOrderSourceCountReport(stime, etime, optuser);
            return Success("获取成功", result);
        }

        /// <summary>
        /// 获取日周月年工单24小时统计
        /// </summary>
        [HttpGet("getworkorder24count")]
        public IActionResult GetWorkOrder24CountReport(int datetype = 0)
        {
            string optuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string stime = string.Empty; string etime = string.Empty;
            if (datetype != 0)
            {
                GetStartEndTime(datetype, out stime, out etime);
            }

            var result = _bus_order_baseRepository.GetWorkOrder24CountReport(stime, etime, optuser);
            return Success("获取成功", result);
        }

        /// <summary>
        /// 获取用户工单排行榜
        /// </summary>
        [HttpGet("getusercountrank")]
        public IActionResult GetUserCountRank(int top = 0,int datetype = 0)
        {
            string stime = string.Empty; string etime = string.Empty;
            if (datetype != 0)
            {
                GetStartEndTime(datetype, out stime, out etime);
            }

            var result = _bus_order_baseRepository.GetUserCountRank(top,stime, etime);

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

        /// <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 1://当天
                    break;
                case 2://本周
                    int n = (int)datenow.DayOfWeek == 0 ? 7 : (int)datenow.DayOfWeek;
                    datestart = datenow.AddDays(1 - n);//本周周一
                    dateend = datestart.AddDays(6);//本周周日
                    break;
                case 3://本月
                    datestart = datenow.AddDays(1 - datenow.Day);  //本月月初  
                    dateend = datestart.AddMonths(1).AddDays(-1);  //本月月末  
                    break;
                case 4://本年
                    datestart = new DateTime(datenow.Year, 1, 1);  //本年年初  
                    dateend = new DateTime(datenow.Year, 12, 31);  //本年年末  
                    break;
                default:
                    break;
            }

            start = datestart.ToString("yyyy-MM-dd") +" 00:00:00";
            end = dateend.ToString("yyyy-MM-dd") + " 23:59:59";
        }
    }
}
