using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Utils;
using Sugar.Enties;
using WxPayAPI;

namespace PMS.NetCore.Service
{
    /// <summary>
    /// 物业缴费订单定时处理任务
    /// </summary>
    public class WyOrderJob : IJob
    {
        public Task Execute(IJobExecutionContext context)
        {
            return Task.Run(() =>
            {
                try
                {
                    NlogHelper.quartzLogger.Info("开始物业缴费订单定时处理任务");
                    var manager = new fdc_pm_meterrecordManager();
                    //遍历最近5天未支付的订单
                    var list = manager.Db.Queryable<Order>().Where(m => m.Status == 0 && m.AddTime > DateTime.Now.AddDays(-5)).ToList();
                    foreach (var order in list)
                    {
                        orderQuery(order.OrderNo);
                    }


                }
                catch (Exception ero)
                {
                    NlogHelper.quartzLogger.Error(ero, "物业缴费订单定时处理任务执行出错");
                    throw;
                }

            });

        }
        /// <summary>
        /// 向微信支付发起订单查询请求，根据查询结果，插入缴费记录，及更新order订单表的状态
        /// </summary>
        /// <param name="out_trade_no">订单号</param>
        /// <returns></returns>
        private string orderQuery(string out_trade_no)
        {
            WxPayData data = new WxPayData();

            data.SetValue("out_trade_no", out_trade_no);


            WxPayData result = WxPayApi.OrderQuery(data);//提交订单查询请求给API，接收返回数据

            if (result.GetValue("return_code") == null || result.GetValue("result_code") == null || result.GetValue("trade_state") == null)
            {

                NlogHelper.quartzLogger.Debug("return_code...null");
                return "";
            }
            if (result.GetValue("return_code").ToString() != "SUCCESS" || result.GetValue("result_code").ToString() != "SUCCESS" || result.GetValue("trade_state").ToString() != "SUCCESS")
            {

                NlogHelper.quartzLogger.Debug("return_code...不成功");
                return "";
            }
            var manager = new fdc_pm_meterrecordManager();
            manager.Db.BeginTran();
            var order = manager.Db.Queryable<Order>().First(m => m.OrderNo == out_trade_no); 
 
           
            #region  扫码支付订单处理   
            
            if (order == null)
            {
                manager.Db.RollbackTran();
                return "";
            }
            try
            {
               
                string revfarecode="";
                var res = manager.InsertPayWithNoTran(order.Farerowid, order.Money.ToString(), order.Ownername, order.Hname, ref revfarecode);
                if(res!="success")
                {
                    manager.Db.RollbackTran();
                    return "";
                }
                else
                {
                    order.Status = 1;
                    order.Revfarecode = revfarecode;
                    //更新订单状态为已支付 更新生成的已缴费主键到order表
                    manager.Db.Updateable<Order>().UpdateColumns(it => new { it.Status, it.Revfarecode }).ExecuteCommand();   
                }
                manager.Db.CommitTran();
                return "SUCCESS";
            }
            catch (Exception ex)
            {
                manager.Db.RollbackTran();
                NlogHelper.quartzLogger.Error(ex,$"{out_trade_no}订单缴费和更新订单状态出错");
                //throw;
            }


            #endregion
            return "";

        }
    }
}
