using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Sugar.Enties;
using Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Utils.Jwt;
using WxPayAPI;
using SqlSugar;

namespace PMS.NetCore.Controllers
{
  


    /// <summary>
    /// 仪表相关
    /// </summary>
    [Produces("application/json;charset=UTF-8")]
    [Route("api/Meter")]
    [ServiceFilter(typeof(Filter.TokenAuthorizeByOwner))]
    public class MeterController : BaseController
    {
        private IHttpContextAccessor _accessor;
        /// <summary>
        /// 令牌获取和验证类
        /// </summary>
        private readonly ITokenHelper tokenHelper = null;
        public MeterController(IHttpContextAccessor accessor,ITokenHelper _tokenHelper)
        {
            logger = NLog.LogManager.GetCurrentClassLogger();
            _accessor = accessor;
            tokenHelper = _tokenHelper;
        }
        /// <summary>
        /// 发送手机验证码
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        [Route("SendSms")]
        public JsonResult SendSms(string phone)
        {
            var res = new ApiResponse();
            try
            {
                if (phone.IsNullOrEmpty())
                {

                    res.ErrMsg = "请填写手机号";
                    return Json(res);

                }
                if (!phone.IsCellPhone())
                {
                    res.ErrMsg = "手机号格式不正确";
                    return Json(res);
                }
                var code = Sms.GetSMSCode();
               
                var signName = "唯友";
                var templateid = "SMS_230825153";
                var templateParam = "{\"code\":\"" + code + "\"}";
                logger.Info($"【SendSms】templateParam:{templateParam}");

                //发送验证码到手机
                AlibabaSMSSdk.SendSms(phone, signName,templateid,templateParam);
                //用session存随机验证码
                SessionHelper sessionHelp = new SessionHelper(_accessor.HttpContext);
                sessionHelp.SetSession("verifiedCode", code);
                sessionHelp.SetSession("phone", phone);
                res.IsSuccess = true;
                res.Data ="success";
                return Json(res);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                res.ErrMsg = ex.Message;
                res.Code = 500;
                return Json(res);
            }
        }

        /// <summary>
        /// 业主登录
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        [Route("LoginOwner")]
        public JsonResult LoginOwner([FromBody] LoginOwnerDTO dto)
        {
           
            var res = new ApiResponse();
            try
            {
                logger.Info($"【Getfdc_pm_unfare 输入参数】dto:{JsonConvert.SerializeObject(dto)}");
                SessionHelper sessionHelp = new SessionHelper(_accessor.HttpContext);
                if (dto.Phone != sessionHelp.GetSession("phone"))
                {
                    res.ErrMsg = "手机号不正确";
                    return Json(res);
                }
                if (dto.VeriCode != sessionHelp.GetSession("verifiedCode"))
                {
                    res.ErrMsg = "手机验证码不正确";
                    return Json(res);
                }
                var service = new fdc_pm_meterrecordManager();
                var model = service.LoginOwner(dto.Phone);

                //获取令牌，返回客户端
                Dictionary<string, string> keyValuePairs = new Dictionary<string, string>
                    {
                        { "phone", model.Tel }
                    };
                var tnToken = tokenHelper.CreateToken(keyValuePairs);

                res.IsSuccess = true;
                res.Data = model;
                res.TnToken=tnToken;
                return Json(res);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                res.ErrMsg = ex.Message;
                res.Code = 500;
                return Json(res);
            }
        }

        /// <summary>
        /// 绑定房屋信息
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        [HttpGet]        
        [Route("BindHouse")]
        public JsonResult BindHouse(string phone)
        {

            var res = new ApiResponse();
            try
            {
                logger.Info($"【BindHouse 输入参数】dto:{phone}");              
                var service = new fdc_pm_meterrecordManager();
                var list = service.BindHouse(phone);
 

                res.IsSuccess = true;
                res.Data = list;
                logger.Info($"【BindHouse 输出参数】res:{JsonConvert.SerializeObject(res)}");
                return Json(res);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                res.ErrMsg = ex.Message;
                res.Code = 500;
                return Json(res);
            }
        }



        #region 抄表单
        /// <summary>
        /// 抄表单添加
        /// </summary>
        /// <param name="chaoBiaos"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Fdc_pm_meterAdd")]
        public JsonResult Fdc_pm_meterAdd([FromBody] List<ChaobiaoDTO> chaoBiaos)
        {
            logger.Info($"【Fdc_pm_meterAdd输入参数】chaoBiaos:{JsonConvert.SerializeObject(chaoBiaos)}");
            var service = new fdc_pm_meterrecordManager();
            var res = service.Fdc_pm_meterAdd(chaoBiaos);
            logger.Info($"Fdc_pm_meterAdd输出参数】res:{res}");
            return Json(res);

        }
        #endregion

        #region 缴费接口
        /// <summary>
        /// 获取欠费信息
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("Getfdc_pm_unfare")]
        public JsonResult Getfdc_pm_unfare(string phone)
        {
            var res = new ApiResponse();
            try
            {
                logger.Info($"【Getfdc_pm_unfare 输入参数】phone:{phone}");
                if(phone.IsNullOrEmpty())
                {
                    res.ErrMsg = "手机号不能为空";
                    return Json(res);
                }
                var service = new fdc_pm_meterrecordManager();
                var list = service.Getfdc_pm_unfare(phone);
                logger.Info($"Getfdc_pm_unfare 输出参数】list:{JsonConvert.SerializeObject(list)}");
                res.IsSuccess = true;
                res.Data = list;
                return Json(res);
            }
            catch(Exception ex)
            {
                logger.Error(ex);
                res.ErrMsg = ex.Message;
                res.Code = 500;
                return Json(res);
            }

        }
        /// <summary>
        /// 获取缴费记录
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("Getfdc_pm_revfare")]
        public JsonResult Getfdc_pm_revfare(string phone)
        {
            var res = new ApiResponse();
           
            try
            {
                logger.Info($"【Getfdc_pm_revfare 输入参数】phone:{phone}");
                if(phone.IsNullOrEmpty())
                {
                    res.ErrMsg = "参数错误";
                    return Json(res);
                }
                var service = new fdc_pm_meterrecordManager();
                var list = service.Getfdc_pm_revfare(phone);
                logger.Info($"Getfdc_pm_revfare 输出参数】list:{JsonConvert.SerializeObject(list)}");
                res.IsSuccess = true;
                res.Data = list;
                return Json(res);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                res.ErrMsg = ex.Message;
                res.Code = 500;
                return Json(res);
            }

        }

        /// <summary>
        /// 生成微信缴费单url
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("MakePayUrl")]
        public JsonResult MakePayUrl([FromBody] PayDTO dto)
        {
            var res = new ApiResponse();

            try
            {
                logger.Info($"【MakePayUrl 输入参数】dto:{JsonConvert.SerializeObject(dto)}");
                if (dto.farwarid.IsNullOrEmpty())
                {
                    res.ErrMsg = "缴费编号错误";
                    return Json(res);
                }
                if(!dto.money.IsDecimal())
                {
                    res.ErrMsg = "缴费金额不正确";
                    return Json(res);
                }
                if (dto.ownername.IsNullOrEmpty())
                {
                    res.ErrMsg = "业主名称错误";
                    return Json(res);
                }
                if (dto.hname.IsNullOrEmpty())
                {
                    res.ErrMsg = "房屋名称错误";
                    return Json(res);
                }
                var order = new Order();
                order.OrderNo = Utility.GetRandomNumber();
                order.Farerowid = dto.farwarid;
                order.Money = dto.money.ToDecimal();
                order.Ownername = dto.ownername;
                order.Hname = dto.hname;
                order.Revfarecode = "";

                //logger.Info("SqlFunc.ToDate", SqlFunc.ToDateShort(DateTime.Now));

                var service = new fdc_pm_meterrecordManager();
                var orderNew = service.Db.Queryable<Order>().First(m => m.Farerowid == order.Farerowid && m.Money == order.Money && SqlFunc.ToDateShort(m.AddTime) == SqlFunc.ToDateShort(service.Db.GetDate()));
                if(orderNew==null)
                {
                    orderNew = service.Db.Insertable(order).ExecuteReturnEntity();
                }                
                if(orderNew!=null)   //表示生成订单成功
                {
                    var pay = new NativePay();
                    var money = (int)(dto.money.ToDecimal() * 100);
                    //logger.Info("MakePayUrl 输出参数】dto.money:"+ dto.money);
                    //logger.Info("MakePayUrl 输出参数】money.ToDecimal:"+dto.money.ToDecimal() * 100);
                    //logger.Info("MakePayUrl 输出参数】money:"+ money);
                    var payurl = pay.GetPayUrl(dto.farwarid, money, orderNew.OrderNo);
                    res.IsSuccess = true;
                    res.Data = payurl;
                    logger.Info($"MakePayUrl 输出参数】res:{JsonConvert.SerializeObject(res)}");
                    return Json(res);
                }
                else
                {
                    res.IsSuccess = false;
                    res.ErrMsg = "生成订单失败，重新操作";
                    logger.Info($"MakePayUrl 输出参数】res:{JsonConvert.SerializeObject(res)}");
                    return Json(res);
                }
             
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                res.ErrMsg = ex.Message;
                res.Code = 500;
                return Json(res);
            }
        }
        #endregion

        #region 报修和投诉
        /// <summary>
        /// 获取报修记录
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetRepaireList")]
        public JsonResult GetRepaireList(string phone)
        {
            var res = new ApiResponse();

            try
            {
                logger.Info($"【GetRepaireList 输入参数】phone:{phone}");
                if (phone.IsNullOrEmpty())
                {
                    res.ErrMsg = "参数错误";
                    return Json(res);
                }
                var service = new fdc_pm_meterrecordManager();
                var list = service.GetRepaireList(phone);
                logger.Info($"GetRepaireList 输出参数】list:{JsonConvert.SerializeObject(list)}");
                res.IsSuccess = true;
                res.Data = list;
                return Json(res);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                res.ErrMsg = ex.Message;
                res.Code = 500;
                return Json(res);
            }

        }

        /// <summary>
        /// 获取投诉记录
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetComplaintList")]
        public JsonResult GetComplaintList(string phone)
        {
            var res = new ApiResponse();

            try
            {
                logger.Info($"【GetComplaintList 输入参数】phone:{phone}");
                if (phone.IsNullOrEmpty())
                {
                    res.ErrMsg = "参数错误";
                    return Json(res);
                }
                var service = new fdc_pm_meterrecordManager();
                var list = service.GetComplaintList(phone);
                logger.Info($"GetComplaintList 输出参数】list:{JsonConvert.SerializeObject(list)}");
                res.IsSuccess = true;
                res.Data = list;
                return Json(res);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                res.ErrMsg = ex.Message;
                res.Code = 500;
                return Json(res);
            }

        }


        /// <summary>
        /// 获取报修详情
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetRepairDetail")]
        public JsonResult GetRepairDetail(string code)
        {
            var res = new ApiResponse();
            logger.Info($"【GetRepairDetail 输入参数】code:{code}");
            try
            {
                var service = new fdc_pm_meterrecordManager();
                var model = service.GetRepairDetail(code);
                
                res.IsSuccess = true;
                res.Data = model;
                logger.Info($"GetRepairDetail 输出参数】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="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Insertfdc_pm_repair")]
        public JsonResult Insertfdc_pm_repair([FromBody] BaoshiDTO dto)
        {
            var res = new ApiResponse();

            try
            {
                logger.Info($"【Insertfdc_pm_repair 输入参数】dto:{JsonConvert.SerializeObject(dto)}");
                //res.ErrMsg = "输出";
                //return Json(res);
                var service = new fdc_pm_meterrecordManager();
                var resstr = service.Insertfdc_pm_repair(dto,0);
                
                if(resstr!="success")
                {
                    res.ErrMsg = resstr;
                    logger.Info($"Insertfdc_pm_repair 输出参数】res:{JsonConvert.SerializeObject(res)}");
                    return Json(res);
                }
                res.IsSuccess = true;
                res.Data = resstr;
                logger.Info($"Insertfdc_pm_repair 输出参数】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="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Insertfdc_pm_repairByTousu")]
        public JsonResult Insertfdc_pm_repairByTousu([FromBody] BaoshiDTO dto)
        {
            var res = new ApiResponse();

            try
            {
                logger.Info($"【Insertfdc_pm_repairByTousu 输入参数】dto:{JsonConvert.SerializeObject(dto)}");

                var service = new fdc_pm_meterrecordManager();
                var resstr = service.Insertfdc_pm_repair(dto, 1);
                
                if (resstr != "success")
                {
                    res.ErrMsg = resstr;
                    logger.Info($"Insertfdc_pm_repairByTousu 输出参数】res:{JsonConvert.SerializeObject(res)}");
                    return Json(res);
                }
                res.IsSuccess = true;
                res.Data = resstr;
                logger.Info($"Insertfdc_pm_repairByTousu 输出参数】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="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("InsertPay")]
        public JsonResult InsertPay([FromBody] PayDTO dto)
        {
            var res = new ApiResponse();

            try
            {
                //单独添加缴费单禁用，在订单完成支付后再进行处理
                return Json(res);
                logger.Info($"【InsertPay 输入参数】dto:{JsonConvert.SerializeObject(dto)}");

                var service = new fdc_pm_meterrecordManager();
                var revfarecode = "";
                var resstr = service.InsertPay(dto.farwarid,dto.money,dto.ownername,dto.hname,ref revfarecode);

                if (resstr != "success")
                {
                    res.ErrMsg = resstr;
                    logger.Info($"InsertPay 输出参数】res:{JsonConvert.SerializeObject(res)}");
                    return Json(res);
                }
                res.IsSuccess = true;
                res.Data = resstr;
                logger.Info($"InsertPay 输出参数】res:{JsonConvert.SerializeObject(res)}");
                return Json(res);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                res.ErrMsg = ex.Message;
                res.Code = 500;
                return Json(res);
            }
        }
        #endregion


        /// <summary>
        /// 获取房产信息
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetOwnerHouse")]
        public JsonResult GetOwnerHouse(string phone)
        {
            var res = new ApiResponse();

            try
            {
                logger.Info($"【GetOwnerHouse 输入参数】phone:{phone}");
                if (phone.IsNullOrEmpty())
                {
                    res.ErrMsg = "参数错误";
                    return Json(res);
                }
                var service = new fdc_pm_meterrecordManager();
                var list = service.GetOwnerHouse(phone);                
                res.IsSuccess = true;
                res.Data = list;
                logger.Info($"GetOwnerHouse 输出参数】res:{JsonConvert.SerializeObject(res)}");
                return Json(res);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                res.ErrMsg = ex.Message;
                res.Code = 500;
                return Json(res);
            }

        }
    }
}
