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 WorkOrderApi.IRepositories;
using WorkOrderApi.Input;
using MadRunFabric.Model.WorkOrderApi;
using System.Security.Claims;
using MongoDB.Driver;
using Microsoft.Extensions.Configuration;
using SignTokenApi.IRepositories;

namespace WorkOrderApi.Areas.Hy_Order.Controllers
{
    /// <summary>
    /// 工单 - 售后管理系统
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Route("api/[controller]")]
    [Produces("application/json")]
    public class BaseWorkOrderController : BaseController
    {
        private readonly ILogger<WorkOrderController> _logger;
        private readonly IBus_WorkOrder_BaseRepository _bus_workorder_baseRepository;
        private readonly IBus_WorkOrder_ItemRepository _bus_workorder_itemRepository;
        private readonly IBus_Msg_ListRepository _bus_msg_listRepository;
        private readonly IConfiguration _configuration;
        private readonly ISys_User_AccountRepository _sys_user_accountRepository;

        public BaseWorkOrderController(
            ILogger<WorkOrderController> logger,
            IBus_WorkOrder_BaseRepository bus_workorder_baseRepository,
            IBus_WorkOrder_ItemRepository bus_workorder_itemRepository,
            IBus_Msg_ListRepository bus_msg_listRepository,
            IConfiguration configuration,
            ISys_User_AccountRepository sys_user_accountRepository
            )
        {
            _logger = logger;
            _bus_workorder_baseRepository = bus_workorder_baseRepository;
            _bus_workorder_itemRepository = bus_workorder_itemRepository;
            _bus_msg_listRepository = bus_msg_listRepository;
            _configuration = configuration;
            _sys_user_accountRepository = sys_user_accountRepository;
        }

        /// <summary>
        /// 获取工单分页
        /// </summary>
        [HttpGet("getlistbypage")]
        public IActionResult GetListsByPageAsync(string ordercode, string keyword, 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_workorder_baseRepository.GetListsByPage(ordercode, keyword, 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_workorder_baseRepository.Get(p => p.ordercode == ordercode && p.isdelete == 0);
            var clmodel = cls.FirstOrDefault();
            if (clmodel != null)
            {
                var model = _bus_workorder_baseRepository.GetDetails(ordercode);
                var item = await _bus_workorder_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(WorkOrderInput input)
        {
            #region 判断验证
            if (string.IsNullOrWhiteSpace(input.name))
                return Error("请输入客户姓名");
            if (string.IsNullOrEmpty(input.phone))
                return Error("请输入客户电话");
            //if (string.IsNullOrEmpty(input.content))
            //    return Error("请输入内容");
            #endregion

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

            var model = new Bus_WorkOrder_Base();
            #region model 添加工单对象
            model.unique_id = input.unique_id;
            model.ordercode = DateTime.Now.ToString("yyyyMMddHHmmssfff");   //工单编号 - 时间戳
            model.callrecordid = input.callrecordid;
            model.typeid = input.typeid;
            model.state = (int)EnumOrderType.create;    //工单状态:0未处理,1已处理

            model.customerid = input.customerid;
            model.name = input.name;
            model.company = input.company;
            model.callintel = input.callintel;
            model.phone = input.phone;
            model.province = input.province;    //省
            model.city = input.city;            //市

            model.proid = input.proid;
            model.projectname = input.projectname;
            model.address = input.address;
            model.faulty_equipment = input.faulty_equipment;
            model.content = input.content;
            model.faulty_typeid = input.faulty_typeid;
            model.faulty_type2id = input.faulty_type2id;
            model.sourceid = input.sourceid;
            model.productive = input.productive;

            model.deptid = input.deptid;
            model.createuser = usercode;
            model.createusername = username;
            model.createtime = DateTime.Now;
            model.touser = input.touser;
            model.businesstype = input.businesstype;
            model.dealinstantly = input.dealinstantly;
            model.iseffective = input.iseffective;
            #endregion
            bool bl = await _bus_workorder_baseRepository.Add(model);
            if (bl)
            {
                #region 添加item
                var modelb = new Bus_WorkOrder_Item();
                #region model 添加工单对象

                modelb.ordercode = model.ordercode;//DateTime.Now.ToString("yyyyMMddHHmmssfff");   //工单编号 - 时间戳

                modelb.typeid = input.typeid;
                modelb.state = (int)EnumOrderType.create;    //工单状态:0未处理,1已处理
                modelb.createuser = usercode;
                modelb.createusername = username;
                modelb.createtime = DateTime.Now;
                #endregion
                bool b = await _bus_workorder_itemRepository.Add(modelb);
                #endregion
                AddItems(model.ordercode, model.state, usercode + "(" + username + "） 创建", usercode, username);
                return Success("保存成功");
            }
            else
                return Error("保存失败");
        }

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

            var model = (await _bus_workorder_baseRepository.Get(p => p.ordercode == input.ordercode && p.isdelete == 0)).FirstOrDefault();
            if (model != null && model.createuser == usercode && model.state == (int)EnumOrderType.create)
            {
                #region 判断验证
                if (string.IsNullOrWhiteSpace(input.name))
                    return Error("请输入客户姓名");
                if (string.IsNullOrEmpty(input.callintel))
                    return Error("请输入来电电话");
                //if (string.IsNullOrEmpty(input.content))
                //    return Error("请输入内容");
                #endregion

                #region model 添加工单对象
                model.typeid = input.typeid;
                model.name = input.name;
                model.company = input.company;
                model.phone = input.phone;
                model.province = input.province;    //省
                model.city = input.city;            //市

                model.projectname = input.projectname;
                model.address = input.address;
                model.faulty_equipment = input.faulty_equipment;
                model.content = input.content;
                model.faulty_typeid = input.faulty_typeid;
                model.faulty_type2id = input.faulty_type2id;
                model.sourceid = input.sourceid;
                model.productive = input.productive;
                model.dealinstantly = input.dealinstantly;
                model.iseffective = input.iseffective;
                model.deptid = input.deptid;
                model.touser = input.touser;
                model.businesstype = input.businesstype;
                #endregion

                bool b = await _bus_workorder_baseRepository.UpdateOne(model);
                if (b)
                {
                    AddItems(model.ordercode, model.state, usercode + "(" + username + "） 修改", usercode, username);
                    return Success("保存成功");
                }
                else
                    return Error("保存失败");
            }
            return Error("操作失败");
        }

        /// <summary>
        /// 处理
        /// </summary>
        [HttpPost("deal")]
        public async Task<IActionResult> DealAsync(string ordercode, string result)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string username = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;
            #region 判断验证
            if (string.IsNullOrWhiteSpace(ordercode))
                return Error("参数错误");
            if (string.IsNullOrWhiteSpace(result))
                return Error("请输入处理结果");
            #endregion

            var model = (await _bus_workorder_baseRepository.Get(p => p.ordercode == ordercode && p.isdelete == 0)).FirstOrDefault();
            if (model != null && model.state == (int)EnumOrderType.create)
            {
                model.state = (int)EnumOrderType.complete;
                model.dealuser = usercode;
                model.dealusername = username;
                model.result = result;
                model.dealtime = DateTime.Now;
                await _bus_workorder_baseRepository.UpdateOne(model);
                AddItems(model.ordercode, model.state, usercode + "(" + username + "） 处理，结果：" + result, usercode, username);
                return Success("处理成功");
            }

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

        /// <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 _bus_workorder_baseRepository.GetSingle(id);
                    model.isdelete = 1;
                    model.deleteuser = usercode;
                    model.deletetime = DateTime.Now;
                    if (await _bus_workorder_baseRepository.UpdateOne(model))
                    {
                        res += 1;
                        AddItems(model.ordercode, model.state, usercode + "(" + username + "） 删除", usercode, username);
                    }
                }
                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="optuser">当前操作人</param>
        /// <param name="optusername">当前操作人姓名</param>
        private async void AddItems(string ordercode, int state, string detail, string usercode, string username)
        {
            var model = new Bus_Msg_List();
            model.ordercode = ordercode;
            model.state = state;
            model.createuser = usercode;
            model.createusername = username;
            model.createtime = DateTime.Now;
            model.detail = detail;
            await _bus_msg_listRepository.Add(model);
        }

        /// <summary>
        /// 获取工单动态
        /// </summary>
        [HttpGet("getdt")]
        public async Task<IActionResult> GetDTAsync(string ordercode)
        {
            var cls = await _bus_msg_listRepository.Get(p => p.ordercode == ordercode && p.isdelete == 0);

            if (cls != null)
            {


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


        //2019-5-7添加工单指派
        /// <summary>
        /// 获取待指派工单
        /// </summary>
        [HttpGet("getdzplist")]
        public IActionResult GetDZPListAsync(string ordercode, string keyword, 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)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            var list = _sys_user_accountRepository.Get(x => x.usercode == usercode && x.delete_flag == false);
            if (list.Result != null)
            {
                foreach (var item in list.Result)
                {
                    int seatright = item.seat_right;
                    if (seatright == 1)
                    {
                        usercode = "";
                    }
                }
            }
            int recordcount = 0;
            //var result = _bus_workorder_baseRepository.GetOrderListsByPage("", "", "", "", 0,  "", "", "", "", pageindex, pagesize, out recordcount);
            var result = _bus_workorder_baseRepository.GetOrderListsByPage("", "", "", "", 0, "", "", "", usercode, phone, province, city, sourceid, typeid, deptid, pageindex, pagesize, out recordcount, 0);
            var obj = new
            {
                rows = result.ToList(),
                total = recordcount
            };

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

        /// <summary>
        /// 获取待接单列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("getdjdlist")]
        public IActionResult GetDJDListAsync(string ordercode, string keyword, 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)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

            var list = _sys_user_accountRepository.Get(x => x.usercode == usercode && x.delete_flag == false);
            if (list.Result != null)
            {
                foreach (var item in list.Result)
                {
                    int seatright = item.seat_right;
                    if (seatright == 1)
                    {
                        usercode = "";
                    }
                }
            }

            int recordcount = 0;
            //var result =  _bus_workorder_baseRepository.GetOrderListsByPage("","","","",2,"" ,"","","", pageindex, pagesize,out recordcount);
            var result = _bus_workorder_baseRepository.GetOrderListsByPage("", "", "", "", 2, usercode, "", "", "", phone, province, city, sourceid, typeid, deptid, pageindex, pagesize, out recordcount, 0);
            var obj = new
            {
                rows = result.ToList(),
                total = recordcount
            };

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

        /// <summary>
        /// 获取待处理列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("getdcllist")]
        public IActionResult GetDCLListAsync(string ordercode, string keyword, 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)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            var list = _sys_user_accountRepository.Get(x => x.usercode == usercode && x.delete_flag == false);
            if (list.Result != null)
            {
                foreach (var item in list.Result)
                {
                    int seatright = item.seat_right;
                    if (seatright == 1)
                    {
                        usercode = "";
                    }
                }
            }
            int recordcount = 0;
            //var result = _bus_workorder_baseRepository.GetOrderListsByPage("", "", "", "", 3,"", "", "", "", pageindex, pagesize, out recordcount);
            var result = _bus_workorder_baseRepository.GetOrderListsByPage("", "", "", "", 3, "", usercode, "", "", phone, province, city, sourceid, typeid, deptid, pageindex, pagesize, out recordcount, 0);
            var obj = new
            {
                rows = result.ToList(),
                total = recordcount
            };

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

        /// <summary>
        /// 获取已处理列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("getycllist")]
        public IActionResult GetYCLListAsync(string ordercode, string keyword, 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)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            var list = _sys_user_accountRepository.Get(x => x.usercode == usercode && x.delete_flag == false);
            if (list.Result != null)
            {
                foreach (var item in list.Result)
                {
                    int seatright = item.seat_right;
                    if (seatright == 1)
                    {
                        usercode = "";
                    }
                }
            }
            int recordcount = 0;
            //var result = _bus_workorder_baseRepository.GetOrderListsByPage("", "", "", "", 9, "", "", "", "", pageindex, pagesize, out recordcount);
            var result = _bus_workorder_baseRepository.GetOrderListsByPage("", "", "", "", 9, "", usercode, "", "", phone, province, city, sourceid, typeid, deptid, pageindex, pagesize, out recordcount, 0);
            var obj = new
            {
                rows = result.ToList(),
                total = recordcount
            };

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

        /// <summary>
        /// 处理工单
        /// </summary>
        [HttpPost("dealorder")]
        public async Task<IActionResult> DealWAsync(string ordercode, string result, string touser, string todept, string helper, string helpcontent, int dealtype = 0)//dealtype为0时指派，为1时接单，为2时处理，3为撤回，4为退回
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string username = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            #region 判断验证
            if (string.IsNullOrWhiteSpace(ordercode))
                return Error("参数错误");
            //if (string.IsNullOrWhiteSpace(result))
            //    return Error("请输入处理结果");
            #endregion

            var model0 = (await _bus_workorder_baseRepository.Get(p => p.ordercode == ordercode && p.isdelete == 0)).FirstOrDefault();
            if (model0 != null && dealtype == 0)//指派工单model0.state == (int)EnumOrderType.create
            {
                if (model0.zptime == null || model0.zptime.ToString() == "")//记录指派时间用于计算工单时效
                {
                    model0.zptime = DateTime.Now;
                }
                model0.zpusercode = usercode;
                model0.state = (int)EnumOrderType.appoint;
                await _bus_workorder_baseRepository.UpdateOne(model0);

                var model = (await _bus_workorder_itemRepository.Get(p => p.ordercode == ordercode && p.isdelete == 0)).FirstOrDefault();
                if (model != null)
                {
                    model.state = (int)EnumOrderType.appoint;
                    model.touser = touser;
                    model.todept = todept;
                    model.zpcontent = result;
                    model.zptime = DateTime.Now;
                    model.zpusercode = usercode;
                    await _bus_workorder_itemRepository.UpdateOne(model);
                }

                AddItems(model.ordercode, model.state, usercode + "向" + touser + "指派了工单：" + ordercode, usercode, username);
                return Success("指派成功");
            }
            else if (model0 != null && dealtype == 1)
            {
                model0.state = (int)EnumOrderType.accept;
                await _bus_workorder_baseRepository.UpdateOne(model0);
                var model = (await _bus_workorder_itemRepository.Get(p => p.ordercode == ordercode && p.isdelete == 0)).FirstOrDefault();
                if (model != null)
                {
                    model.state = (int)EnumOrderType.accept;
                    model.sureuser = usercode;
                    model.suretime = DateTime.Now;
                    await _bus_workorder_itemRepository.UpdateOne(model);
                }
                AddItems(model.ordercode, model.state, usercode + "已接工单：" + ordercode, usercode, username);
                return Success("接单成功");
            }
            else if (model0 != null && dealtype == 2)
            {
                model0.dealuser = usercode;
                model0.dealtime = DateTime.Now;
                model0.state = (int)EnumOrderType.complete;
                model0.result = result;
                await _bus_workorder_baseRepository.UpdateOne(model0);
                var model = (await _bus_workorder_itemRepository.Get(p => p.ordercode == ordercode && p.isdelete == 0)).FirstOrDefault();
                if (model != null)
                {
                    model.state = (int)EnumOrderType.complete;
                    model.dealuser = usercode;
                    model.dealtime = DateTime.Now;

                    model.helper = helper;
                    model.helpcontent = helpcontent;
                    await _bus_workorder_itemRepository.UpdateOne(model);
                }
                AddItems(model.ordercode, model.state, usercode + "处理工单：" + ordercode, usercode, username);
                return Success("处理成功");
            }
            else if (model0 != null && dealtype == 3)//撤回
            {
                model0.state = (int)EnumOrderType.create;
                await _bus_workorder_baseRepository.UpdateOne(model0);
                var model = (await _bus_workorder_itemRepository.Get(p => p.ordercode == ordercode && p.isdelete == 0)).FirstOrDefault();
                if (model != null)
                {
                    model.state = (int)EnumOrderType.create;
                    model.touser = "";
                    model.touser = "";
                    await _bus_workorder_itemRepository.UpdateOne(model);
                }
                AddItems(model.ordercode, model.state, usercode + "撤回工单：" + ordercode, usercode, username);
                return Success("撤回成功");
            }
            else if (model0 != null && dealtype == 4)//退回
            {
                model0.state = (int)EnumOrderType.create;
                await _bus_workorder_baseRepository.UpdateOne(model0);
                var model = (await _bus_workorder_itemRepository.Get(p => p.ordercode == ordercode && p.isdelete == 0)).FirstOrDefault();
                if (model != null)
                {
                    model.state = (int)EnumOrderType.create;
                    model.touser = "";
                    model.touser = "";
                    await _bus_workorder_itemRepository.UpdateOne(model);
                }
                AddItems(model.ordercode, model.state, usercode + "退回工单：" + ordercode, usercode, username);
                return Success("退回成功");
            }


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

        //获取工单统计数据
        #region 获取工单统计数据
        /// <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_WorkOrder_Base>>();
            flist.Add(Builders<Bus_WorkOrder_Base>.Filter.Eq("isdelete", 0));


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

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

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

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

            var wwccount = await _bus_workorder_baseRepository.CountAsync(wwcfilter);
            var ywccount = await _bus_workorder_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_workorder_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_workorder_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;
            if (optuser == "8000")
            {
                optuser = "";//8000帐号可以查看所有数据
            }
            string stime = string.Empty; string etime = string.Empty;
            if (datetype != 0)
            {
                GetStartEndTime(datetype, out stime, out etime);
            }

            var result = _bus_workorder_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_workorder_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";
        }
        #endregion
    }
}
