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

namespace EquipmentApi.Controllers
{
    /// <summary>
    /// 项目管理控制器，对项目信息的操作
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class ProjectInfoController : BaseController
    {
        private readonly ILogger<ProjectInfoController> _logger;
        private readonly IConfiguration _configuration;
        private readonly ISys_User_AccountRepository _sys_user_accountRepository;
        private readonly IPro_Project_InfoRepository _pro_project_infoRepository;
        private readonly IPro_Project_LogRepository _project_logRepository;
        private readonly ISignTokenService _signTokenService;
        private readonly IMapper _mapper;

        public ProjectInfoController(
            ILogger<ProjectInfoController> logger,
            IConfiguration configuration,
            ISys_User_AccountRepository sys_user_accountRepository,
            IPro_Project_InfoRepository project_infoRepository, 
            IPro_Project_LogRepository project_logRepository,
            ISignTokenService signTokenService, IMapper mapper)
        {
            _logger = logger;
            _configuration = configuration;
            _sys_user_accountRepository = sys_user_accountRepository;
            _pro_project_infoRepository = project_infoRepository;
            _project_logRepository = project_logRepository;
            _signTokenService = signTokenService;
            _mapper = mapper;
        }

        /// <summary>
        /// 获取所有项目列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("getlistdrop")]
        public async Task<IActionResult> GetListdrop()
        {
            var list = await _pro_project_infoRepository.Get(x => x.isdelete == 0);

            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            if (userinfo.isallproject == 0)
                list = list.Where(x => userinfo.projectlist.Contains(x.id));

            var listmodel = new List<DropListDto>();
            foreach (var item in list)
            {
                var model = new DropListDto();
                model.id = item.id;
                model.text = item.project_name;
                listmodel.Add(model);
            }
            return Success("成功", listmodel);
        }

        /// <summary>
        /// 项目管理列表 by page - 不用
        /// </summary>
        /// <param name="apptype">应用分类（0android 1ios）</param>
        /// <param name="keyword">版本编号</param>
        /// <param name="createtime">添加开始时间</param>
        /// <param name="createtime">添加结束时间</param>
        /// <param name="pageindex">当前页</param>
        /// <param name="pagesize">每页条数</param>
        /// <returns></returns>
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListsByPageAsync(string keyword, string stime, string etime, int pageindex = 1, int pagesize = 10)
        {
            ////排序字段
            var sort = Builders<Pro_Project_Info>.Sort.Descending("createtime");
            //根据条件查询集合
            var listApp = new List<FilterDefinition<Pro_Project_Info>>();
            listApp.Add(Builders<Pro_Project_Info>.Filter.Eq("isdelete", 0));
            if (!string.IsNullOrEmpty(stime))
                listApp.Add(Builders<Pro_Project_Info>.Filter.Gte("createtime", stime + " 00:00:00"));
            if (!string.IsNullOrEmpty(etime))
                listApp.Add(Builders<Pro_Project_Info>.Filter.Lte("createtime", etime + " 23:59:59"));
            //模糊查询(项目名称，项目属性，项目负责人)
            if (!string.IsNullOrEmpty(keyword))
                listApp.Add(Builders<Pro_Project_Info>.Filter.Where(s => s.project_name.Contains(keyword) || s.project_property.Contains(keyword) || s.project_resperson.Contains(keyword)));

            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            if (userinfo.isallproject == 0)
                listApp.Add(Builders<Pro_Project_Info>.Filter.Where(s => userinfo.projectlist.Contains(s.id)));

            int recordCount = 0;

            var filter = Builders<Pro_Project_Info>.Filter.And(listApp);
            var list = await _pro_project_infoRepository.GetByPage(filter, pageindex, pagesize, sort);
            var redCount = await _pro_project_infoRepository.CountAsync(filter);   //获取总数
            recordCount = int.Parse(redCount.ToString());

            var obj = new
            {
                state = "success",
                message = "成功",
                rows = list,
                total = recordCount,
            };
            return Content(obj.ToJson());
        }

        /// <summary>
        /// 项目管理列表 - 关联查询
        /// </summary>
        /// <returns></returns>
        [HttpGet("getlistsbypage")]
        public IActionResult GetListsByPage(string keyword, string stime, string etime, int isdq = -1, int pageIndex = 1, int pageSize = 10)
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            int recordCount = 0;
            var result = _pro_project_infoRepository.GetListsByPage(keyword, stime, etime, isdq, userinfo, pageIndex, pageSize, out recordCount);
            var obj = new
            {
                rows = result,
                total = recordCount,
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 项目详情 by id
        /// </summary>
        /// <param name="id">项目id</param>
        /// <returns></returns>
        [HttpGet("getdetailes")]
        public async Task<IActionResult> GetDetailsAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");

            var model = await _pro_project_infoRepository.GetSingle(id);
            if(model==null)
                return Error("获取失败");
            var result = new
            {
                model.id,
                proname = model.project_name,
                proshortname=model.project_shortname,
                province = model.project_province,
                city = model.project_city,
                property = model.project_property,
                nature = model.project_nature,
                //membernum = model.project_membernum,
                resperson = model.project_resperson,
                starttime = model.project_starttime,
                endtime = model.project_endtime,
                //cycle = model.project_cycle,
                order = model.project_order,
                //equipmentvariety = model.project_equipmentvariety,
                //equipmentnum = model.project_equipmentnum,
                plans = model.project_plans,
                profile = model.project_profile
                //remind = model.project_remind,
            };
            return Success("获取成功！", result);
        }

        /// <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 = _pro_project_infoRepository.GetDetails(id);
            if (model != null)
            {
                return Success("获取成功！", model);
            }
            return Error("获取失败");
        }

        /// <summary>
        /// 添加项目信息
        /// </summary>
        /// <param name="input">项目参数</param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(ProjectInfoInput input)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            #region 验证判断
            if (string.IsNullOrEmpty(input.project_name))
                return Error("项目名称不能为空");
            if (string.IsNullOrEmpty(input.project_resperson))
                return Error("负责人不能为空");
            if (string.IsNullOrEmpty(input.project_property))
                return Error("项目属性不能为空");
            long n = await _pro_project_infoRepository.Count(x => x.project_name.Equals(input.project_name) && x.isdelete == 0);
            if (n > 0)
                return Error("项目名称已存在");
            #endregion
            var model = new Pro_Project_Info();
            model.project_name = input.project_name;
            model.project_shortname = input.project_shortname;
            model.project_province = input.project_province;
            model.project_city = input.project_city;
            model.project_property = input.project_property;
            model.project_nature = input.project_nature;
            //model.project_membernum = input.project_membernum;
            model.project_resperson = input.project_resperson;
            model.project_starttime = input.project_starttime;
            model.project_endtime = input.project_endtime;
            //model.project_cycle = input.project_cycle;
            model.project_order = input.project_order;
            //model.project_equipmentvariety = input.project_equipmentvariety;
            //model.project_equipmentnum = input.project_equipmentnum;
            if (input.project_plans != null)
            {
                model.project_plans = input.project_plans;
            }
            else
            {
                model.project_plans = new List<FileBaseModel>();
            }
            if (input.project_pic != null)
            {
                model.project_pic = input.project_pic;
            }
            else
            {
                model.project_pic = new List<FileBaseModel>();
            }
            model.project_profile = input.project_profile;
            //model.project_remind = input.project_remind;
            model.isend = 0;
            model.isdelete = 0;
            model.createby = usercode;
            model.createtime = DateTime.Now.ToLocalTime();

            string pid = await _pro_project_infoRepository.AddRetID(model);
            if (!string.IsNullOrEmpty(pid))
            {
                AddLog(pid, 1, "新增项目：" + model.project_name, usercode);
                return Success("添加成功");
            }
            return Error("添加失败");
        }

        /// <summary>
        /// 修改项目信息
        /// </summary>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(ProjectInfoInput input)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

            #region 验证判断
            if (string.IsNullOrEmpty(input.id))
                return Error("参数错误");
            if(string.IsNullOrEmpty(input.project_name))
                return Error("项目名称不能为空");
            if (string.IsNullOrEmpty(input.project_resperson))
                return Error("负责人不能为空");
            if (string.IsNullOrEmpty(input.project_property))
                return Error("项目属性不能为空");
            long n = await _pro_project_infoRepository.Count(x => x.project_name.Equals(input.project_name) && x.isdelete == 0 && x.id != input.id);
            if (n > 0)
                return Error("项目名称已存在");
            #endregion
            var model = new Pro_Project_Info();
            model = await _pro_project_infoRepository.GetSingle(input.id);
            if (model == null)
                return Error("操作失败");
            model.project_name = input.project_name;
            model.project_shortname = input.project_shortname;
            model.project_province = input.project_province;
            model.project_city = input.project_city;
            model.project_property = input.project_property;
            model.project_nature = input.project_nature;
            //model.project_membernum = input.project_membernum;
            model.project_resperson = input.project_resperson;
            model.project_starttime = input.project_starttime;
            model.project_endtime = input.project_endtime;
            //model.project_cycle = input.project_cycle;
            model.project_order = input.project_order;
            //model.project_equipmentvariety = input.project_equipmentvariety;
            //model.project_equipmentnum = input.project_equipmentnum;
            if (input.project_plans != null)
            {
                model.project_plans = input.project_plans;
            }
            else
            {
                model.project_plans = new List<FileBaseModel>();
            }
            if (input.project_pic != null)
            {
                model.project_pic = input.project_pic;
            }
            else
            {
                model.project_pic = new List<FileBaseModel>();
            }
            model.project_profile = input.project_profile;
            //model.project_remind = input.project_remind;
            //model.isdelete = 0;
            bool b = await _pro_project_infoRepository.UpdateOne(model);
            if (b)
            {
                AddLog(model.id, 1, "修改项目：" + model.project_name, usercode);
                return Success("保存成功");
            }

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

        /// <summary>
        /// 删除项目信息 by ids
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public IActionResult RemoveAsync(string[] ids)
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            //var res = 0;
            if (ids != null && ids.Length > 0)
            {
                //foreach (var item in ids)
                //{
                //    var ml = await _pro_project_infoRepository.GetSingle(item);
                //    ml.isdelete = 1;
                //    ml.deleteby = usercode;
                //    ml.deletetime = DateTime.Now.ToLocalTime();
                //    if (_pro_project_infoRepository.UpdateOne(ml).Result)
                //        res += 1;
                //}
                //if (res == ids.Length)
                //    return Success("删除成功");
                //else if (res > 0 && res < ids.Length)
                //    return Error("部分删除失败，请查看后重新操作");
                //else
                //    return Error("删除失败，请查看后重新操作");

                foreach (var id in ids)
                {
                    var model = _pro_project_infoRepository.GetSingle(id).Result;

                    _pro_project_infoRepository.Delete(id, userinfo);

                    AddLog(model.id, 1, "删除项目：" + model.project_name, nowusercode);
                }
                return Success("删除成功");
            }
            else
                return Error("请选择要删除的记录");
        }

        /// <summary>
        /// 终止项目 by ids
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("end")]
        public async Task<IActionResult> EndAsync(string[] ids)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    var ml = await _pro_project_infoRepository.GetSingle(item);
                    ml.isend = 1;
                    ml.endby = usercode;
                    ml.endtime = DateTime.Now;
                    if (_pro_project_infoRepository.UpdateOne(ml).Result)
                    {
                        res += 1;

                        AddLog(ml.id, 1, "终止项目：" + ml.project_name, usercode);
                    }
                }
                if (res == ids.Length)
                    return Success("终止成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分终止失败，请查看后重新操作");
                else
                    return Error("终止失败，请查看后重新操作");
            }
            else
                return Error("请选择要终止的记录");
        }

        /// <summary>
        /// 开启项目 by ids
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("start")]
        public async Task<IActionResult> StartAsync(string[] ids)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    var ml = await _pro_project_infoRepository.GetSingle(item);
                    ml.isend = 0;
                    ml.endby = "";
                    ml.endtime = null;
                    if (_pro_project_infoRepository.UpdateOne(ml).Result)
                    {
                        res += 1;
                        AddLog(ml.id, 1, "开启项目：" + ml.project_name, usercode);
                    }
                }
                if (res == ids.Length)
                    return Success("开启成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分开启失败，请查看后重新操作");
                else
                    return Error("开启失败，请查看后重新操作");
            }
            else
                return Error("请选择要开启的记录");
        }

        /// <summary>
        /// 获取用户项目
        /// </summary>
        /// <returns></returns>
        [HttpGet("getuserproject")]
        public IActionResult GetUserProject()
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());
            var result = _pro_project_infoRepository.GetUserProject(userinfo);
            return Success("获取成功", result);
        }

        /// <summary>
        /// 项目设备
        /// </summary>
        /// <param name="projectid">项目id</param>
        /// <returns></returns>
        [HttpGet("getprojectequipment")]
        public IActionResult GetProjectEquipment(string projectid)
        {
            var result = _pro_project_infoRepository.GetProjectEquipment(projectid);
            return Success("获取成功", result);
        }


        #region 项目管理(设备运维 -> 资料管理 -> 项目管理) - APP
        /// <summary>
        /// 获取所有项目列表 - App
        /// </summary>
        /// <returns></returns>
        [HttpGet("getapplist")]
        public async Task<IActionResult> GetAppList()
        {
            var list = await _pro_project_infoRepository.Get(x=>x.isdelete == 0);
            //return Success("获取全部数据成功", list);
            var obj = new
            {
                state = "success",
                message = "成功",
                data = list
            };
            return Content(obj.ToJson());
        }

        /// <summary>
        /// 获取洗涤工单列表 - 关联查询
        /// </summary>
        /// <returns></returns>
        [HttpGet("getapplists")]
        public IActionResult GetAppLists(string keyword)
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            var result = _pro_project_infoRepository.GetAppLists(keyword, userinfo);
            return Success("获取成功", result);
        }

        /// <summary>
        /// 项目详情 by id
        /// </summary>
        /// <param name="id">项目id</param>
        /// <returns></returns>
        [HttpGet("getappdetailes")]
        public async Task<IActionResult> GetAppDetailsAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");

            var model = await _pro_project_infoRepository.GetSingle(id);
            if (model == null)
                return Error("获取失败");
            var result = new
            {
                id = model.id,
                proname = model.project_name,
                province = model.project_province,
                city = model.project_city,
                property = model.project_property,
                nature = model.project_nature,
                //membernum = model.project_membernum,
                resperson = model.project_resperson,
                starttime = model.project_starttime,
                endtime = model.project_endtime,
                //cycle = model.project_cycle,
                order = model.project_order,
                //equipmentvariety = model.project_equipmentvariety,
                //equipmentnum = model.project_equipmentnum,
                plans = model.project_plans,
                profile = model.project_profile
                //remind = model.project_remind,
            };
            return Success("获取成功！", result);
        }

        #endregion


        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="projectid"></param>
        /// <param name="type"></param>
        /// <param name="details"></param>
        /// <param name="usercode"></param>
        /// <returns></returns>
        public async void AddLog(string projectid, int type,string details,string usercode)
        {
            Pro_Project_Log ppl = new Pro_Project_Log();
            ppl.projectid = projectid;
            ppl.type = type;
            ppl.details = details;
            ppl.createby = usercode;
            ppl.createtime = DateTime.Now;
            await _project_logRepository.Add(ppl);
        }
    }
}