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

namespace EquipmentApi.Controllers.workordermanage
{
    /// <summary>
    /// 洗涤工单管理
    /// </summary>
    //[Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class WoWashController : BaseController
    {
        private readonly ILogger<WoWashController> _logger;
        private readonly IWo_WashRepository _wo_washrepository;

        public WoWashController(
            ILogger<WoWashController> logger,
            IWo_WashRepository wo_washrepository
            )
        {
            _logger = logger;
            _wo_washrepository = wo_washrepository;
        }

        /// <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 async Task<IActionResult> GetListByPageAsync( string keyword, string stime, string etime, int pageindex = 1, int pagesize = 10)
        {
            #region 条件信息
            ////排序字段
            var sort = Builders<Wo_Wash>.Sort.Descending("createtime");
            //根据条件查询集合
            var listfilter = new List<FilterDefinition<Wo_Wash>>();
            listfilter.Add(Builders<Wo_Wash>.Filter.Eq("isdelete", 0));
            if (!string.IsNullOrEmpty(stime))
                listfilter.Add(Builders<Wo_Wash>.Filter.Gt("createtime", stime));
            if (!string.IsNullOrEmpty(etime))
                listfilter.Add(Builders<Wo_Wash>.Filter.Lt("createtime", etime));
            //模糊查询
            if (!string.IsNullOrEmpty(keyword))
                listfilter.Add(Builders<Wo_Wash>.Filter.Where(s => s.wocode.Contains(keyword)));
            #endregion
            int recordCount = 0;
            var filter = Builders<Wo_Wash>.Filter.And(listfilter);
            var list = await _wo_washrepository.GetByPage(filter, pageindex, pagesize, sort);
            var redCount = await _wo_washrepository.CountAsync(filter);   //获取总数
            recordCount = int.Parse(redCount.ToString());

            var obj = new
            {
                rows = list,
                total = recordCount,
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 获取洗涤工单列表 by page - 关联查询 demo1 不用
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet("getlist1")]
        public IActionResult GetList1(string keyword, string stime, string etime, int pageindex = 1, int pagesize = 10)
        {
            //排序
            var sort = new BsonDocument();
            sort.Add("createtime", -1);     //1升序 -1降序
            //根据条件查询集合
            var match = new BsonDocument();
            match.Add("isdelete", 0);
            if (!string.IsNullOrEmpty(keyword))
                match.Add("wocode", keyword);
            //if (!string.IsNullOrEmpty(keyword))
            //    match.Add("wocode", new BsonDocument { { "$regex", "/"+ keyword + ".*/i" } });
            if (!string.IsNullOrEmpty(stime))
                match.Add("createtime", new BsonDocument { { "$gte", stime } });
            if (!string.IsNullOrEmpty(etime))
                match.Add("createtime", new BsonDocument { { "$lte", etime } });
            //match.Add("wocode", new BsonDocument{{ "$gt", "1522224861449" } });

            var list = _wo_washrepository.GetList1(match, pageindex, pagesize, sort);
            var obj = new
            {
                rows = list
            };
            return Content(obj.ToJson());
            //return Success("获取成功", obj);
        }

        /// <summary>
        /// 获取洗涤工单列表 - 关联查询
        /// </summary>
        /// <returns></returns>
        [HttpGet("getlistsbypage")]
        public IActionResult GetListsByPage(string keyword, string stime, string etime, int pageIndex = 1, int pageSize = 10)
        {
            int recordCount = 0;
            var result = _wo_washrepository.GetListsByPage(keyword, stime, etime, pageIndex, pageSize, out recordCount);
            var obj = new
            {
                rows = result,
                total = recordCount,
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 获取洗涤工单详情 by id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("getdetailes")]
        public async Task<IActionResult> GetDetailsAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");
            var model = await _wo_washrepository.GetSingle(id);
            if (model != null)
            {
                var result = new
                {
                    id = model.id,
                    wocode = model.wocode,
                    channel = model.channel,
                    projectid = model.projectid,
                    provincecode = model.provincecode,
                    citycode = model.citycode,
                    departmentsid = model.departmentsid,
                    floorid = model.floorid,
                    personid = model.personid,
                    tasktype = model.tasktype,
                    createtime = model.createtime,
                    tasktime = model.tasktime,
                    batchesnumber = model.batchesnumber,
                    bigsheetnum = model.bigsheetnum,
                    quiltcovernum = model.quiltcovernum,
                    pillowcasenum = model.pillowcasenum,
                    pillownum = model.pillownum,
                    clothesnum = model.clothesnum,
                    pantsnum = model.pantsnum,
                    whitepatientclothesnum = model.whitepatientclothesnum,
                    whitepatientpantsnum = model.whitepatientpantsnum,
                    singlelayer = model.singlelayer,
                    doublelayer = model.doublelayer,
                    quiltnum = model.quiltnum,
                    matnum = model.matnum,
                    coolquiltnum = model.coolquiltnum,
                    bedspreadnum = model.bedspreadnum,
                    blindsnum = model.blindsnum,
                    workclothesnum = model.workclothesnum,
                    nurseclothesnum = model.nurseclothesnum,
                    nursepantnum = model.nursepantnum,
                    constraintsnum = model.constraintsnum,
                    hatsnum = model.hatsnum,
                };
                return Success("获取成功！", result);
            }
            return Error("获取失败");
        }

        /// <summary>
        /// 获取洗涤工单详情 by id - 关联查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("getdetails")]
        public IActionResult GetDetails(string id)
        {
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");
            var model = _wo_washrepository.GetDetails(id);
            if (model != null)
            {
                //var result = new
                //{
                //    id = model.id,
                //    wocode = model.wocode,
                //    channel = model.channel,
                //    projectid = model.projectid,
                //    provincecode = model.provincecode,
                //    citycode = model.citycode,
                //    projectname = model.projectname,
                //    provincename = model.provincename,
                //    cityname = model.cityname,
                //    departmentsid = model.departmentsid,
                //    departmentsname = model.departmentsname,
                //    floorid = model.floorid,
                //    floorname = model.floorname,
                //    createtime = model.createtime,
                //    isdelete = model.isdelete,    //                
                //    personid = model.personid,
                //    tasktype = model.tasktype,
                //    tasktime = model.tasktime,
                //    bigsheetnum = model.bigsheetnum,
                //    quiltcovernum = model.quiltcovernum,
                //    pillowcasenum = model.pillowcasenum,
                //    pillownum = model.pillownum,
                //    clothesnum = model.clothesnum,
                //    pantsnum = model.pantsnum,
                //    whitepatientclothesnum = model.whitepatientclothesnum,
                //    whitepatientpantsnum = model.whitepatientpantsnum,
                //    singlelayer = model.singlelayer,
                //    doublelayer = model.doublelayer,
                //    quiltnum = model.quiltnum,
                //    matnum = model.matnum,
                //    coolquiltnum = model.coolquiltnum,
                //    bedspreadnum = model.bedspreadnum,
                //    blindsnum = model.blindsnum,
                //    workclothesnum = model.workclothesnum,
                //    nurseclothesnum = model.nurseclothesnum,
                //    nursepantnum = model.nursepantnum,
                //    constraintsnum = model.constraintsnum,
                //    hatsnum = model.hatsnum,
                //    createby = model.createby,
                //};
                return Success("获取成功！", model);
            }
            return Error("获取失败");
        }

        /// <summary>
        /// 添加洗涤工单信息
        /// </summary>
        /// <param name="apptype"></param>
        /// <param name="versionname"></param>
        /// <param name="versioncode"></param>
        /// <param name="ordernum"></param>
        /// <param name="downurl"></param>
        /// <param name="httpurl"></param>
        /// <param name="note"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(WoWashInput input)
        {
            if (string.IsNullOrEmpty(input.projectid))
                return Error("项目名称不能为空");
            if (string.IsNullOrEmpty(input.departmentsid))
                return Error("科室名称不能为空");
            if (string.IsNullOrEmpty(input.floorid))
                return Error("楼层名称地址不能为空");
            if (string.IsNullOrEmpty(input.personid))
                return Error("负责人不能为空");
            var model = new Wo_Wash();
            //时间戳作为工单编号
            var ordercode = DateTimeConvert.ToTimespan().ToString();
            model.wocode = ordercode;
            model.channel = input.channel;
            model.projectid = input.projectid;
            model.provincecode = input.provincecode;
            model.citycode = input.citycode;
            model.departmentsid = input.departmentsid;
            model.floorid = input.floorid;
            model.personid = input.personid;
            model.tasktype = input.tasktype;
            model.createtime = DateTime.Now.ToLocalTime();
            model.tasktime = input.tasktime;
            model.batchesnumber = input.batchesnumber;
            model.bigsheetnum = input.bigsheetnum;
            model.quiltcovernum = input.quiltcovernum;
            model.pillowcasenum = input.pillowcasenum;
            model.pillownum = input.pillownum;
            model.clothesnum = input.clothesnum;
            model.pantsnum = input.pantsnum;
            model.whitepatientclothesnum = input.whitepatientclothesnum;
            model.whitepatientpantsnum = input.whitepatientpantsnum;
            model.singlelayer = input.singlelayer;
            model.doublelayer = input.doublelayer;
            model.quiltnum = input.quiltnum;
            model.matnum = input.matnum;
            model.coolquiltnum = input.coolquiltnum;
            model.bedspreadnum = input.bedspreadnum;
            model.blindsnum = input.blindsnum;
            model.workclothesnum = input.workclothesnum;
            model.nurseclothesnum = input.nurseclothesnum;
            model.nursepantnum = input.nursepantnum;
            model.constraintsnum = input.constraintsnum;
            model.hatsnum = input.hatsnum;
            model.createby = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            model.isdelete = 0;
            #region 添加信息
            //model.wocode = ordercode;
            //model.channel = 2;
            //model.projectid = "5aab6f580d26390eac2bdc82";
            //model.provincecode = "110000";
            //model.citycode = "110200";
            //model.departmentsid = "5abb2dc0802c923fc86f1825";
            //model.floorid = "5abb0d0e6dc92e69382efeea";   //1号楼1单元1206
            //model.personid = "8000";
            //model.tasktype = 1;
            //model.createtime = DateTime.Now.ToLocalTime();
            //model.tasktime = DateTime.Now.AddDays(10).ToLocalTime();
            //model.batchesnumber = "456789";
            //model.bigsheetnum = 1;
            //model.quiltcovernum = 1;
            //model.pillowcasenum = 1;
            //model.pillownum = 1;
            //model.clothesnum = 1;
            //model.pantsnum = 1;
            //model.whitepatientclothesnum = 1;
            //model.whitepatientpantsnum = 1;
            //model.singlelayer = 1;
            //model.doublelayer = 1;
            //model.quiltnum = 1;
            //model.matnum = 1;
            //model.coolquiltnum = 1;
            //model.bedspreadnum = 1;
            //model.blindsnum = 1;
            //model.workclothesnum = 1;
            //model.nurseclothesnum = 1;
            //model.nursepantnum = 1;
            //model.constraintsnum = 1;
            //model.hatsnum = 1;
            //model.isdelete = 0;
            #endregion
            bool b = await _wo_washrepository.Add(model);
            if (b)
                return Success("添加成功");
            //日志
            _logger.LogError($"洗涤工单：{ordercode}添加失败");
            return Error("添加失败");
        }

        /// <summary>
        /// 修改洗涤工单信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(WoWashInput input)
        {
            if (string.IsNullOrEmpty(input.id))
                return Error("id不能为空");
            if (string.IsNullOrEmpty(input.projectid))
                return Error("项目名称不能为空");
            if (string.IsNullOrEmpty(input.departmentsid))
                return Error("科室名称不能为空");
            if (string.IsNullOrEmpty(input.floorid))
                return Error("楼层名称地址不能为空");
            if (string.IsNullOrEmpty(input.personid))
                return Error("负责人不能为空");

            var model = new Wo_Wash();
            model = await _wo_washrepository.GetSingle(input.id);
            if (model == null)
                return Error("操作失败");
            //model.wocode = input.wocode;
            //model.channel = input.channel;
            model.projectid = input.projectid;
            model.provincecode = input.provincecode;
            model.citycode = input.citycode;
            model.departmentsid = input.departmentsid;
            model.floorid = input.floorid;
            model.personid = input.personid;
            model.tasktype = input.tasktype;
            //model.createtime = input.createtime;
            model.tasktime = input.tasktime;
            model.batchesnumber = input.batchesnumber;
            model.bigsheetnum = input.bigsheetnum;
            model.quiltcovernum = input.quiltcovernum;
            model.pillowcasenum = input.pillowcasenum;
            model.pillownum = input.pillownum;
            model.clothesnum = input.clothesnum;
            model.pantsnum = input.pantsnum;
            model.whitepatientclothesnum = input.whitepatientclothesnum;
            model.whitepatientpantsnum = input.whitepatientpantsnum;
            model.singlelayer = input.singlelayer;
            model.doublelayer = input.doublelayer;
            model.quiltnum = input.quiltnum;
            model.matnum = input.matnum;
            model.coolquiltnum = input.coolquiltnum;
            model.bedspreadnum = input.bedspreadnum;
            model.blindsnum = input.blindsnum;
            model.workclothesnum = input.workclothesnum;
            model.nurseclothesnum = input.nurseclothesnum;
            model.nursepantnum = input.nursepantnum;
            model.constraintsnum = input.constraintsnum;
            model.hatsnum = input.hatsnum;
            //model.isdelete = 0;
            bool b = await _wo_washrepository.Update(model);
            if (b)
                return Success("保存成功");
            //日志
            _logger.LogError($"洗涤工单：{model.wocode}修改失败");
            return Error("保存失败");
        }

        /// <summary>
        /// 删除洗涤工单信息 by ids
        /// </summary>
        /// <param name="ids">string[] id</param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> DeleteAsync(string[] ids)
        {
            int num = 0;
            if (ids == null && ids.Length <= 0)
                return Error("请选择要删除的记录");
            foreach (var item in ids)
            {
                var model = await _wo_washrepository.GetSingle(item);
                model.isdelete = -1;
                if (await _wo_washrepository.Update(model))
                    num += 1;
            }
            if (num == ids.Length)
                return Success("删除成功");
            if (num > 0 && num < ids.Length)
                return Error("部分删除失败，请查看后重新操作");
            return Error("删除失败，请查看后重新操作");
        }

        #region 移动端 App
        /// <summary>
        /// 获取洗涤工单列表
        /// </summary>
        /// <param name="keyword">模糊查询</param>
        /// <param name="projectid">项目id</param>
        /// <param name="departmentsid">科室id</param>
        /// <param name="floorid">楼层id</param>
        /// <param name="personid">负责人id</param>
        /// <param name="tasktype">任务状态id(0实收，1实发)</param>
        /// <param name="createtime">添加时间</param>
        /// <returns></returns>
        [HttpGet("getapplist")]
        public async Task<IActionResult> GetAppList(string keyword,string projectid,string departmentsid,string floorid,string personid,string createtime, int tasktype = -1)
        {
            #region 条件信息
            //排序字段
            var sort = Builders<Wo_Wash>.Sort.Descending("createtime");
            //根据条件查询集合
            var listfilter = new List<FilterDefinition<Wo_Wash>>();
            listfilter.Add(Builders<Wo_Wash>.Filter.Eq("isdelete", 0));
            if (!string.IsNullOrEmpty(projectid))
                listfilter.Add(Builders<Wo_Wash>.Filter.Eq("projectid", projectid));
            if (!string.IsNullOrEmpty(departmentsid))
                listfilter.Add(Builders<Wo_Wash>.Filter.Eq("departmentsid", departmentsid));
            if (!string.IsNullOrEmpty(floorid))
                listfilter.Add(Builders<Wo_Wash>.Filter.Eq("floorid", floorid));
            if (!string.IsNullOrEmpty(personid))
                listfilter.Add(Builders<Wo_Wash>.Filter.Eq("personid", personid));
            if (tasktype > 0)
                listfilter.Add(Builders<Wo_Wash>.Filter.Eq("tasktype", tasktype));
            //时间查询
            if (!string.IsNullOrEmpty(createtime))
            {
                string stime = createtime + "00:00:00";
                string etime = createtime + "23:59:59";
                listfilter.Add(Builders<Wo_Wash>.Filter.Gt("createtime", stime));
                listfilter.Add(Builders<Wo_Wash>.Filter.Lt("createtime", etime));
            }
            //模糊查询
            if (!string.IsNullOrEmpty(keyword))
                listfilter.Add(Builders<Wo_Wash>.Filter.Where(s => s.wocode.Contains(keyword)));
            #endregion
            var filter = Builders<Wo_Wash>.Filter.And(listfilter);
            var list = await _wo_washrepository.Get(filter, null, sort);
            //var list = await _wo_washrepository.GetAll();
            return Success("获取全部数据成功", list);            
        }

        /// <summary>
        /// 获取洗涤工单列表 - 关联查询
        /// </summary>
        /// <returns></returns>
        [HttpGet("getapplists")]
        public IActionResult GetAppLists(string keyword, string projectid, string departmentsid, string floorid, string personid, string createtime, int tasktype = -1)
        {
            var result = _wo_washrepository.GetAppLists(keyword, projectid, departmentsid, floorid, personid, createtime, tasktype);
            return Success("获取成功", result);
        }
        #endregion
    }
}