using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using PMS.NetCore.BusinessCore.BaseCore;
using Sugar.Enties;
using Sugar.Enties.DbModels;
using Sugar.Enties.DTO;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Utils;

namespace PMS.NetCore.Controllers
{
    /// <summary>
    /// 电子巡查
    /// </summary>
    [EnableCors("MyPolicy")]
    [Produces("application/json;charset=UTF-8")]
    [Route("api/ElectronicInspection")]
    [ServiceFilter(typeof(Filter.TokenAuthorize))]
    public class ElectronicInspectionController : BaseController
    {      

        public ElectronicInspectionController()
        {
            logger = NLog.LogManager.GetCurrentClassLogger();
            
        }      



        #region 巡更点

        /// <summary>
        /// 获取巡检点列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("GetPointList")]
        [AllowAnonymous]
        public JsonResult GetPointList()
        {
            var manager = new fdc_pm_inspection_pointManager();
            var list = manager.GetList();

            logger.Info("【GetPointList】接口输出：{JsonConvert.SerializeObject(list)}");

            return Json(list);

        }


        /// <summary>
        /// 添加巡检点
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("PointAdd")]
        [AllowAnonymous]
        public JsonResult PointAdd([FromBody] fdc_pm_inspection_point model)
        {
            var res = new ApiResponse();
            logger.Info($"【PointAdd】接口输入：{JsonConvert.SerializeObject(model)}");
            var manger = new fdc_pm_inspection_pointManager();           

            if (model.pointcode.IsNullOrEmpty())
            {
                res.IsSuccess = false;
                res.ErrMsg = "巡更点编号不能为空";
                return Json(res);
            }

            if (model.pointname.IsNullOrEmpty())
            {
                res.IsSuccess = false;
                res.ErrMsg = "巡更点名称不能为空";
                return Json(res);
            }


            if (model.pcode.IsNullOrEmpty())
            {               
                res.IsSuccess = false;
                res.ErrMsg = "项目不能为空";
                return Json(res);
            }

            if (model.bcode.IsNullOrEmpty())
            {               
                res.IsSuccess = false;
                res.ErrMsg = "楼栋不能为空";
                return Json(res);
            }

            if (model.hcode.IsNullOrEmpty())
            {
                res.IsSuccess = false;
                res.ErrMsg = "房间不能为空";
                return Json(res);               
            }


            var point = manger.GetById(model.pointcode);
            if (point != null)
            {
                res.IsSuccess = false;
                res.ErrMsg = "巡更点已经存在";
                return Json(res);
            }


            model.createtime = DateTime.Now;
            var success = manger.Insert(model);
            if (success)
            {
                res.IsSuccess = true;
                res.Msg = "添加成功";               
                return Json(res);
            }
            else
            {              
                res.IsSuccess = false;
                res.ErrMsg = "添加失败";
                return Json(res);

            }
        }


        /// <summary>
        /// 修改巡检点
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("PointUpdate")]
        [AllowAnonymous]
        public JsonResult PointUpdate([FromBody] fdc_pm_inspection_point model)
        {

            logger.Info($"【PointUpdate】接口输入：{JsonConvert.SerializeObject(model)}");

            if (model.pcode.IsNullOrEmpty())
            {
                return Json("项目不能为空");
            }

            if (model.bcode.IsNullOrEmpty())
            {
                return Json("楼栋不能为空");
            }

            if (model.hcode.IsNullOrEmpty())
            {
                return Json("房间不能为空");
            }

            var manger = new fdc_pm_inspection_pointManager();

            var point = manger.GetById(model.pointcode);
            if (point != null &&  point.pcode != model.pcode)
            {
                return Json("巡更点已经存在");
            }

            point.pointname = model.pointname;
            point.pcode = model.pcode;
            point.bcode = model.bcode;
            point.hcode = model.hcode;

            var success = manger.Update(point);

            if (success)
            {
                return Json("修改成功");
            }
            else
            {
                return Json("修改失败");

            }
        }


        /// <summary>
        /// 删除巡检点
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("PointDelete")]
        [AllowAnonymous]
        public JsonResult PointDelete([FromBody] SingleParamDTO dto)
        {
            var manager = new fdc_pm_inspection_pointManager();
            var model = manager.GetById(dto.value);
            if (model == null)
            {
                return Json("该巡检点不存在，不能删除");
            }            
            var success = manager.Update(model);

            if (success)
            {
                return Json("删除成功");
            }
            else
            {
                return Json("删除失败");
            }

        }


        #endregion


        #region 巡检路线


        #region 路线

        /// <summary>
        /// 获取项目巡检路线
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("GetRouteList")]
        [AllowAnonymous]
        public JsonResult GetRouteList([FromBody] SingleParamDTO dto)
        {
            logger.Info($"【GetRouteList】dto:{JsonConvert.SerializeObject(dto)}");
            if (dto == null || dto.value.IsNullOrEmpty())
            {
                return Json("参数错误");
            }

            var manager = new fdc_pm_inspection_routeManager();
            var list = manager.GetList(i => i.pcode == dto.value && !i.isdel).ToList();

            logger.Info("【GetRouteList】接口输出：{JsonConvert.SerializeObject(list)}");

            return Json(list);

        }

        /// <summary>
        /// 添加巡检路线
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("RouteAdd")]
        [AllowAnonymous]
        public JsonResult RouteAdd([FromBody] fdc_pm_inspection_route model)
        {

            logger.Info($"【RouteAdd】接口输入：{JsonConvert.SerializeObject(model)}");

            if (model.routename.IsNullOrEmpty())
            {
                return Json("路线名称不能为空");
            }

            if (model.pcode.IsNullOrEmpty())
            {
                return Json("项目不能为空");
            }

            var manger = new fdc_pm_inspection_routeManager();

            var mod = manger.GetList(m => m.routename == model.routename && !m.isdel).FirstOrDefault();

            if (mod != null && mod.pcode == model.pcode)
            {
                return Json("巡更路线已经存在");
            }

            model.createtime = DateTime.Now;
            var success = manger.Insert(model);
            if (success)
            {
                return Json("添加成功");
            }
            else
            {
                return Json("添加失败");

            }
        }


        /// <summary>
        /// 修改巡检路线
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("RouteUpdate")]
        [AllowAnonymous]
        public JsonResult RouteUpdate([FromBody] fdc_pm_inspection_route model)
        {

            logger.Info($"【RouteUpdate】接口输入：{JsonConvert.SerializeObject(model)}");

            if (model.routename.IsNullOrEmpty())
            {
                return Json("路线名称不能为空");
            }

            if (model.pcode.IsNullOrEmpty())
            {
                return Json("项目不能为空");
            }

            var manger = new fdc_pm_inspection_routeManager();

            var mod = manger.GetList(m => m.routename == model.routename && m.pcode == model.pcode && !m.isdel).FirstOrDefault();

            if (mod != null && mod.routecode != model.routecode)
            {
                return Json("巡更路线已经存在");
            }
            model.createtime = DateTime.Now;
            var success = manger.Update(model);
            if (success)
            {
                return Json("修改成功");
            }
            else
            {
                return Json("修改失败");

            }
        }



        /// <summary>
        /// 删除巡检路线
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("RouteDelete")]
        [AllowAnonymous]
        public JsonResult RouteDelete([FromBody] SingleParamDTO dto)
        {
            logger.Info($"RouteDelete 输入参数】res:{JsonConvert.SerializeObject(dto)}");
            var manager = new fdc_pm_inspection_routeManager();
            var model = manager.GetById(dto.value);
            if (model == null)
            {
                return Json("该巡检路线不存在，不能删除");
            }

            var resstr = manager.RouteDelete(Convert.ToInt32(dto.value));

            logger.Info($"RouteDelete 输出参数】res:{JsonConvert.SerializeObject(resstr)}");
            if (resstr != "success")
            {
                return Json("删除失败");
            }
            else
            {
                return Json("删除成功");
            }

        }

        #endregion



        #region 路线详情

        /// <summary>
        /// 获取巡更路线详情
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("GetRouteDetail")]
        [AllowAnonymous]
        public JsonResult GetRouteDetail(InspectionDTO input)
        {
            logger.Info($"【GetRouteDetail】输入参数：{JsonConvert.SerializeObject(input)}");

            if (input.routeCode == 0)
            {
                return Json("线路ID不能为空");
            }

            var manager = new fdc_pm_inspection_routeManager();
            var list = manager.GetRouteDetail(input);
            logger.Info($"【GetRouteDetail】输出参数：{JsonConvert.SerializeObject(list)}");
            return Json(list);
        }

        /// <summary>
        ///  设置巡检路线详情
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("RouteDetailAdd")]
        [AllowAnonymous]
        public JsonResult RouteDetailAdd([FromBody] fdc_pm_inspection_routedetail model)
        {

            logger.Info($"【RouteDetailAdd】接口输入：{JsonConvert.SerializeObject(model)}");

            if (model.routecode == 0)
            {
                return Json("路线不能为空");
            }

            if (model.pointcode.IsNullOrEmpty())
            {
                return Json("巡更点不能为空");
            }

            if (model.sort == 0)
            {
                return Json("请设置巡更顺序");
            }

            var manger = new fdc_pm_inspection_routedetailManager();

            var mod = manger.GetList(m => m.routecode == model.routecode && m.pointcode == model.pointcode && !m.isdel).FirstOrDefault();

            if (mod != null)
            {
                return Json("巡更路线已经存在");
            }

            model.createtime = DateTime.Now;
            var success = manger.Insert(model);
            if (success)
            {
                return Json("添加成功");
            }
            else
            {
                return Json("添加失败");

            }
        }


        /// <summary>
        ///  更新巡检路线详情
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("RouteDetailUpdate")]
        [AllowAnonymous]
        public JsonResult RouteDetailUpdate([FromBody] fdc_pm_inspection_routedetail model)
        {

            logger.Info($"【RouteDetailUpdate】接口输入：{JsonConvert.SerializeObject(model)}");

            if (model.routecode == 0)
            {
                return Json("路线不能为空");
            }

            if (model.pointcode.IsNullOrEmpty())
            {
                return Json("巡更点不能为空");
            }

            if (model.sort == 0)
            {
                return Json("请设置巡更顺序");
            }

            var manger = new fdc_pm_inspection_routedetailManager();

            var mod = manger.GetList(m => m.routecode == model.routecode && m.pointcode == model.pointcode && !m.isdel).FirstOrDefault();

            if (mod != null && mod.autoid != model.autoid)
            {
                return Json("巡更路线已经存在");
            }
            model.createtime = DateTime.Now;
            var success = manger.Update(model);
            if (success)
            {
                return Json("修改成功");
            }
            else
            {
                return Json("修改失败");

            }
        }




        #endregion




        #endregion


        #region 巡更计划

        /// <summary>
        /// 添加巡更计划
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("PlanAdd")]
        [AllowAnonymous]
        public JsonResult PlanAdd([FromBody] fdc_pm_inspection_plan model)
        {

            logger.Info($"【PlanAdd】接口输入：{JsonConvert.SerializeObject(model)}");

            if (model.planname.IsNullOrEmpty())
            {
                return Json("计划名称不能为空");
            }

            if (model.routecode == 0)
            {
                return Json("请选择线路");
            }


            if (model.startdate.ToString() == DateTime.MinValue.ToString())
            {
                return Json("请输入开始日期");
            }

            if (model.enddate.ToString() == DateTime.MinValue.ToString())
            {
                return Json("请输入结束日期");
            }

            if (DateTime.Compare(model.startdate, model.enddate) > 0)
            {
                return Json("结束日期小于开始日期，请重新选择");
            }

            if (model.maker.IsNullOrEmpty())
            {
                return Json("请填写计划制定人");
            }
            model.startdate = Convert.ToDateTime(model.startdate.ToShortDateString());
            model.enddate = Convert.ToDateTime(model.enddate.ToShortDateString());
            var manger = new fdc_pm_inspection_planManager();

            var resstr = manger.PlanAdd(model);

            logger.Info($"PlanAdd 输出参数】res:{JsonConvert.SerializeObject(resstr)}");

            return Json(resstr);
        }


        /// <summary>
        /// 修改巡更计划
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("PlanUpdate")]
        [AllowAnonymous]
        public JsonResult PlanUpdate([FromBody] fdc_pm_inspection_plan model)
        {

            logger.Info($"【PlanUpdate】接口输入：{JsonConvert.SerializeObject(model)}");

            if (model.planname.IsNullOrEmpty())
            {
                return Json("计划名称不能为空");
            }

            if (model.routecode == 0)
            {
                return Json("请选择线路");
            }


            if (model.startdate.ToString() == DateTime.MinValue.ToString())
            {
                return Json("请输入开始日期");
            }

            if (model.enddate.ToString() == DateTime.MinValue.ToString())
            {
                return Json("请输入结束日期");
            }

            if (DateTime.Compare(model.startdate, model.enddate) > 0)
            {
                return Json("结束日期小于开始日期，请重新选择");
            }

            if (model.maker.IsNullOrEmpty())
            {
                return Json("请填写计划制定人");
            }

            model.startdate = Convert.ToDateTime(model.startdate.ToShortDateString());
            model.enddate = Convert.ToDateTime(model.enddate.ToShortDateString());

            var manger = new fdc_pm_inspection_planManager();

            var resstr = manger.PlanUpdate(model);

            logger.Info($"PlanUpdate 输出参数】res:{JsonConvert.SerializeObject(resstr)}");

            return Json(resstr);
        }



        /// <summary>
        /// 删除巡更计划
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("PlanDelete")]
        [AllowAnonymous]
        public JsonResult PlanDelete([FromBody] SingleParamDTO dto)
        {

            logger.Info($"PlanDelete 输入参数】res:{JsonConvert.SerializeObject(dto)}");

            var manger = new fdc_pm_inspection_planManager();
            var resstr = manger.PlanDelete(Convert.ToInt32(dto.value));

            logger.Info($"PlanDelete 输出参数】res:{JsonConvert.SerializeObject(resstr)}");
            return Json(resstr);
        }


        /// <summary>
        /// 设置巡检计划
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("PlandetailAdd")]
        [AllowAnonymous]
        public JsonResult PlandetailAdd(InspectionPlanDTO input)
        {
            logger.Info($"PlandetailAdd 输入参数】res:{JsonConvert.SerializeObject(input)}");

            if (input.userStr.IsNullOrEmpty())
            {
                return Json("请选择巡检人员");
            }

            var manager = new fdc_pm_inspection_plandetailManager();
            var resstr = manager.PlandetailAdd(input);
            logger.Info($"PlandetailAdd 输出参数】res:{JsonConvert.SerializeObject(resstr)}");

            if (resstr == "success")
            {
                return Json("巡查计划生成成功");
            }
            else
            {
                return Json("巡检计划生成失败");
            }
        }


        /// <summary>
        /// 删除指定巡更记录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("PlandetailDelete")]
        [AllowAnonymous]
        public JsonResult PlandetailDelete([FromBody] SingleParamDTO dto)
        {
            logger.Info($"PlandetailDelete 输入参数】res:{JsonConvert.SerializeObject(dto)}");

            var manger = new fdc_pm_inspection_plandetailManager();
            var success = manger.Delete(dto.value);

            logger.Info($"PlandetailDelete 输出参数】res:" + success);
            if (success)
            {
                return Json("删除成功");
            }
            else
            {
                return Json("删除失败");

            }

        }




        #endregion



        #region 移动端调用

        /// <summary>
        /// 更新巡更备注、附件
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("PlandetailUpdate")]
        public JsonResult PlandetailUpdate([FromBody] InspectionParamDTO model)
        {
            var res = new ApiResponse();
            logger.Info($"PlandetailUpdate 输入参数】res:{JsonConvert.SerializeObject(model)}");

            try
            {
                var manger = new fdc_pm_inspection_plandetailManager();
                var resstr = manger.UpdateDetailPlan(model);

                if (resstr != "success")
                {
                    res.IsSuccess = false;
                    res.ErrMsg = resstr;
                    logger.Info($"PlandetailUpdate 输出参数】res:{JsonConvert.SerializeObject(res)}");
                    return Json(res);
                }
                res.IsSuccess = true;
                logger.Info($"PlandetailUpdate 输出参数】res:{JsonConvert.SerializeObject(res)}");
                return Json(res);

            }
            catch (Exception ex)
            {
                logger.Error(ex);
                res.ErrMsg = ex.Message;
                res.Code = 500;
                return Json(res);
            }
        }


        /// <summary>
        /// 获取员工巡更计划
        /// </summary>
        /// <param name="staffcode"></param>
        /// <param name="dateStr"></param>
        /// <param name="pageNumber"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetEmployeePlanList")]
        [AllowAnonymous]
        public JsonResult GetEmployeePlanList(string staffcode, string dateStr, int pageNumber, int pageSize)
        {
            logger.Info($"【Getfdc_pm_housemeterList】dto:{JsonConvert.SerializeObject(staffcode + "-" + dateStr)}");
            var res = new ApiResponse();
            try
            {
                if (dateStr.IsNullOrEmpty())
                {
                    dateStr = DateTime.Now.ToString("yyyy-MM-dd");
                }

                var manager = new fdc_pm_inspection_plandetailManager();
                var data = manager.GetEmployeePlanList(staffcode, dateStr, pageNumber, pageSize);
                res.IsSuccess = true;
                logger.Info($"GetEmployeePlanList 输出参数】res:{JsonConvert.SerializeObject(data)}");
                res.Data = data;

                return Json(res);
            }
            catch (Exception ex)
            {
                res.ErrMsg = ex.Message;
                res.Code = 500;
                return Json(res);
            }
        }



        /// <summary>
        /// 获取巡更路线
        /// </summary>
        /// <param name="planCode"></param>
        /// <param name="planDate"></param>
        /// <param name="planTime"></param>        
        /// <returns></returns>
        [HttpGet]
        [Route("GetPlanDetailList")]
        public JsonResult GetPlanDetailList(string planCode, string planDate, string planTime)
        {
            logger.Info($"【GetPlanDetailList】dto:{JsonConvert.SerializeObject(planCode + "-" + planDate + "-" + planTime)}");
            var res = new ApiResponse();
            try
            {
                var manager = new fdc_pm_inspection_plandetailManager();

                var data = manager.GetPlanDetailList(planCode, planDate, planTime);
                res.IsSuccess = true;
                logger.Info($"GetPlanDetailList 输出参数】res:{JsonConvert.SerializeObject(data)}");
                res.Data = data;

                return Json(res);
            }
            catch (Exception ex)
            {
                res.ErrMsg = ex.Message;
                res.Code = 500;
                return Json(res);
            }
        }


        /// <summary>
        /// 获取巡更点详情
        /// </summary>
        /// <param name="pkCode"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetPointDetail")]

        public JsonResult GetPointDetail(int pkCode)
        {
            logger.Info($"【GetPointDetail】dto:{JsonConvert.SerializeObject(pkCode)}");
            var res = new ApiResponse();
            try
            {
                var manager = new fdc_pm_inspection_plandetailManager();

                var data = manager.GetPointDetail(pkCode);
                res.IsSuccess = true;
                logger.Info($"GetPointDetail 输出参数】res:{JsonConvert.SerializeObject(data)}");
                res.Data = data;

                return Json(res);
            }
            catch (Exception ex)
            {
                res.ErrMsg = ex.Message;
                res.Code = 500;
                return Json(res);
            }
        }



        /// <summary>
        /// NFC巡更
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("NfcScan")]       
        public JsonResult NfcScan([FromBody] NfcScanDTO model)
        {
            var res = new ApiResponse();
            logger.Info($"NfcScan 输入参数】res:{JsonConvert.SerializeObject(model)}");

            try
            {
                var manger = new fdc_pm_inspection_plandetailManager();
                var resstr = manger.NfcScan(model);

                if (resstr != "success")
                {
                    res.IsSuccess = false;
                    res.ErrMsg = resstr;
                    logger.Info($"NfcScan 输出参数】res:{JsonConvert.SerializeObject(res)}");
                    return Json(res);
                }
                res.IsSuccess = true;               
                logger.Info($"NfcScan 输出参数】res:{JsonConvert.SerializeObject(res)}");
                return Json(res);

            }
            catch (Exception ex)
            {
                logger.Error(ex);
                res.ErrMsg = ex.Message;
                res.Code = 500;
                return Json(res);
            }
        }

        #endregion
    } 

}
