using QM.KJGH.CGGL.IRepository;
using QM.KJGH.Gis.PyServer;
using QM.KJGH.Model.KJGH;
using QM.OrmSqlSugar;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using WS;
using WS.Helper;
using WS.Log;

namespace QM.KJGH.CgglService.Managers
{
    /// <summary>
    /// 成果机器审查
    /// </summary>
    public class CgscManager : SqlSugarRepository<CgzjZjrw>, ICgscManager
    {
        public string PyExe;
        public string RootPath;
        public string PythonFile;
        public CgscManager()
        {
            PyExe = ConfigHelper.Configuration["Path:PyExe"];
            PythonFile = ConfigHelper.Configuration["Path:PythonFile"];
            RootPath = ConfigHelper.Configuration["Path:Root"];
        }
        #region 任务
        /// <summary>
        /// 获取新任务
        /// </summary>
        /// <returns></returns>
        public CgzjZjrw NewTask()
        {
            try
            {
                Db.BeginTran();
                var model = First(t => t.RWZT == KJGH.Model.Enums.EnumRwzt.Create, new List<WS.Orm.OrderByModel<CgzjZjrw>>() {
                    new WS.Orm.OrderByModel<CgzjZjrw> (){  order = t=>t.CJSJ , type = WS.Orm.DbOrderEnum.Asc}
                });
                if (model == null)
                    return model;
                RunLog.Debug("任务:" + model.ToJson());
                CgglCg cgglCg = Db.Queryable<CgglCg>().Where(t => t.BSM == model.CG_BSM).First();
                RunLog.Debug($"成果:{cgglCg == null}");

                model.RWZT = KJGH.Model.Enums.EnumRwzt.Run;
                model.ZJSJ = DateTime.Now;
                Db.Updateable(model).ExecuteCommand();
                if(cgglCg != null)
                {
                    RunLog.Debug($"成果111:{ cgglCg.ToJson() }");
                    cgglCg.ZT_JQSC = KJGH.Model.Enums.EnumCgscZT.审查中;
                    Db.Updateable(cgglCg).ExecuteCommand();
                }
                Db.CommitTran();
                return model;
            }
            catch (Exception ex)
            {
                WS.Log.RunLog.Error(ex);
                Db.RollbackTran();
            }
            return null;
        }

        /// <summary>
        /// 任务完成
        /// </summary>
        /// <returns></returns>
        public void TaskComplete(string bsm)
        {
            try
            {
                Db.BeginTran();
                var model = Get(t => t.BSM == bsm);
                CgglCg cgglCg = Db.Queryable<CgglCg>().Where(t => t.BSM == model.CG_BSM).First();

                model.RWZT = KJGH.Model.Enums.EnumRwzt.Complete;
                model.WCSJ = DateTime.Now;
                Db.Updateable(model).ExecuteCommand();
                if (cgglCg != null)
                {
                    cgglCg.ZT_JQSC = KJGH.Model.Enums.EnumCgscZT.审查通过;
                    Db.Updateable(cgglCg).ExecuteCommand();
                }
                Db.CommitTran();
            }
            catch (Exception ex)
            {
                WS.Log.RunLog.Error(ex);
                Db.RollbackTran();
            }
        }

        /// <summary>
        /// 任务错误
        /// </summary>
        /// <param name="msg">错误信息</param>
        /// <returns></returns>
        public void TaskError(string bsm, string msg)
        {
            try
            {
                Db.BeginTran();
                var model = Get(t => t.BSM == bsm);
                CgglCg cgglCg = Db.Queryable<CgglCg>().Where(t => t.BSM == model.CG_BSM).First();

                model.RWZT = KJGH.Model.Enums.EnumRwzt.Error;
                cgglCg.ZT_JQSC = KJGH.Model.Enums.EnumCgscZT.退回;
                model.WCSJ = DateTime.Now;
                Db.Updateable(model).ExecuteCommand();
                Db.Updateable(cgglCg).ExecuteCommand();
                Db.CommitTran();
            }
            catch (Exception ex)
            {
                WS.Log.RunLog.Error(ex);
                Db.RollbackTran();
            }
        }
        #endregion

        /// <summary>
        /// 任务解析
        /// </summary>
        public void Monitor() {
            var task = NewTask();
            if (task != null)
            {
                try
                {
                    Thread.Sleep(1000 * 30);
                    TaskComplete(task.BSM);
                    //PyManager pyManager = new PyManager()
                    //{
                    //    PyExe = PyExe,
                    //    PythonFile = PythonFile,
                    //};
                    //var res = pyManager.Run(EnumFunction.Cgsjzj, new { bsm = task.BSM, root = RootPath });
                    //RunLog.Info("执行结果:" + res);
                    //res = res.Replace("\r\n", "");
                    //if (!res.Contains("####OK####"))
                    //    throw new Exception(res.Replace("####ERROR####", ""));
                    //var file = res.Replace("####OK####", "");

                    //TaskComplete(task.BSM);
                }
                catch (Exception ex)
                {
                    RunLog.Error(ex, $"{ServiceConsts.ServiceName}执行任务异常!");
                    TaskError(task.BSM, ex.Message);
                }
            }
        }
    }
}