using System;
using System.Collections.Generic;
using System.Text;

using Bailun.DC.Models;
using Bailun.DC.DB;
using Dapper;
using MySql.Data.MySqlClient;

namespace Bailun.DC.Services
{
    public class TaskCenterServices
    {

        #region 任务模版

        /// <summary>
        /// 获取单个模版详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public taskcenter_template GetTaskTemplate(int id)
        {
            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
            {
                if(cn.State== System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var sql = "select * from taskcenter_template where id="+id;

                return cn.QueryFirstOrDefault<taskcenter_template>(sql);
            }
        }

        /// <summary>
        /// 保存任务模版
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public string SaveTaskTemplate(taskcenter_template m)
        {
            try
            {
                using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
                {
                    if (cn.State == System.Data.ConnectionState.Closed)
                    {
                        cn.Open();
                    }

                    var obj = cn.QueryFirstOrDefault<taskcenter_template>("select * from taskcenter_template where id="+m.id);

                    if (obj == null)
                    {
                        obj = new taskcenter_template
                        {
                            download_type = m.download_type,
                            note = m.note,
                            start_frequency_day = m.start_frequency_day,
                            start_frequency_hour = m.start_frequency_hour,
                            start_frequency_month = m.start_frequency_month,
                            status = m.status,
                            cron = m.cron,

                            lastupdatetime = DateTime.Now,
                            lastupdateuserid = m.lastupdateuserid,
                            lastupdateusername = m.lastupdateusername,
                        };

                        cn.Insert(obj);
                    }
                    else
                    {
                        obj.download_type = m.download_type;
                        obj.note = m.note;
                        obj.start_frequency_day = m.start_frequency_day;
                        obj.start_frequency_hour = m.start_frequency_hour;
                        obj.start_frequency_month = m.start_frequency_month;
                        obj.status = m.status;

                        obj.cron = m.cron;
                        obj.lastupdatetime = DateTime.Now;
                        obj.lastupdateuserid = m.lastupdateuserid;
                        obj.lastupdateusername = m.lastupdateusername;

                        cn.Update(obj);
                    }
                    
                }

                return "";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        /// <summary>
        /// 更新任务的模版状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public string UpdateTaskTemplateStatus(int id, int status,int uid,string username)
        {
            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.QueryFirstOrDefault<taskcenter_template>("select * from taskcenter_template where id="+id);

                if (obj == null)
                {
                    return "找不到该模版信息";
                }
                else
                {
                    if (obj.status != status)
                    {
                        obj.status = status;
                        obj.lastupdatetime = DateTime.Now;
                        obj.lastupdateuserid = uid;
                        obj.lastupdateusername = username;
                        cn.Update(obj);
                    }
                }

                return "";
            }
        }
        
        /// <summary>
        /// 获取任务模版列表
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="status"></param>
        /// <param name="datatype"></param>
        /// <param name="total"></param>
        /// <returns></returns>
        public List<taskcenter_template> List(BtTableParameter parameter,int? status,int? datatype,ref int total)
        {
            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var sql = "select * from taskcenter_template where 1=1";

                if(datatype.HasValue)
                {
                    sql += " and download_type="+datatype.Value;
                }

                if(status.HasValue)
                {
                    sql += " and status="+status.Value;
                }

                var obj = cn.Page<taskcenter_template>(parameter.pageIndex, parameter.limit, sql, ref total).AsList();

                return obj;
            }

        }

        #endregion

        #region 任务列表

        /// <summary>
        /// 批量创建任务列表
        /// </summary>
        /// <returns></returns>
        public string CreateTaskAll()
        {
            try
            {
                var list = new List<taskcenter_template>();

                using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
                {
                    if (cn.State == System.Data.ConnectionState.Closed)
                    {
                        cn.Open();
                    }

                    list = cn.Query<taskcenter_template>("select * from taskcenter_template where status=1").AsList();

                }

                foreach (var item in list)
                {
                    CreateTask(item.id, 0, "admin00");
                }

                return "";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            
        }

        /// <summary>
        /// 根据模版规则生成任务列表
        /// </summary>
        /// <param name="templateid">模板id</param>
        /// <param name="uid">用户id</param>
        /// <param name="username">用户名称</param>
        /// <returns></returns>
        public string CreateTask(int templateid,int uid,string username)
        {
            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }


                var objTemplate = cn.QueryFirstOrDefault<taskcenter_template>("select * from taskcenter_template where id="+templateid);
                if (objTemplate == null)
                {
                    return "找不到该模版";
                }

                if (objTemplate.start_frequency_month == 0 && objTemplate.start_frequency_hour == 0 && objTemplate.start_frequency_day == 0)
                {
                    return "该模版的启动频率设置异常，请重新设置启动频率。";
                }

                if (objTemplate.start_frequency_month == 0)
                {
                    if (objTemplate.start_frequency_day == 0)
                    {
                        if (objTemplate.start_frequency_hour == DateTime.Now.Hour)
                        {
                            //启动
                            SaveTaskList(cn, objTemplate);
                        }
                    }
                    else if (objTemplate.start_frequency_day == DateTime.Now.Day && objTemplate.start_frequency_hour == DateTime.Now.Hour)
                    {
                        //启动
                        SaveTaskList(cn, objTemplate);
                    }
                }
                else if (objTemplate.start_frequency_month == DateTime.Now.Month && objTemplate.start_frequency_day == DateTime.Now.Day && objTemplate.start_frequency_hour == DateTime.Now.Hour)
                {
                    //启动
                    SaveTaskList(cn, objTemplate);
                }

                return "";
            }
        }

        /// <summary>
        /// 保存任务列表
        /// </summary>
        /// <param name="cn"></param>
        /// <param name="objTemplate"></param>
        private void SaveTaskList(MySqlConnection cn,taskcenter_template objTemplate)
        {
            //找出相关帐号
            var listAccount = cn.Query<taskcenter_accounts>("select * from taskcenter_accounts where data_type=" + objTemplate.download_type).AsList();

            foreach (var item in listAccount)
            {
                var obj = new taskcenter_tasklist
                {
                    createtime = DateTime.Now,
                    account = item.account,
                    lastupdatetime = DateTime.Now,
                    platform_type = item.platform,
                    datatype = objTemplate.download_type,
                    status = 0,
                    task_template_id = objTemplate.id,
                    urlpath = item.apiurl,
                    website = item.website,

                    pwd = item.pwd,
                    token = item.token,
                    platform_index = item.platform_index,
                };
                cn.Insert(obj);
            }
        }


        /// <summary>
        /// 获取任务列表
        /// </summary>
        /// <param name="isall"></param>
        /// <returns></returns>
        public List<taskcenter_tasklist> ListTask(int? status,int isall=1)
        {
            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
            {
                if(cn.State== System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var sql = "select * from taskcenter_tasklist where status!=3 ";

                if(status.HasValue)
                {
                    sql += " and status="+status.Value;
                }

                sql += " order by status";

                if (isall == 0)
                {
                    sql += " limit 1";   
                }

                var obj = cn.Query<taskcenter_tasklist>(sql).AsList();

                return obj;
            }
        }

        /// <summary>
        /// 获取任务列表（分页）
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="status"></param>
        /// <param name="datatype"></param>
        /// <param name="total"></param>
        /// <returns></returns>
        public List<taskcenter_tasklist> ListTask(BtTableParameter parameter, int? status, int? datatype,ref int total)
        {
            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
            {
                if(cn.State== System.Data.ConnectionState.Closed)
                {
                    cn.Open();    
                }

                var sql = "select t1.* from taskcenter_tasklist t1 where 1=1 ";

                if(status.HasValue)
                {
                    sql += " and t1.status="+status.Value;
                }

                if(datatype.HasValue)
                {
                    sql += " and t1.datatype=" + datatype.Value;
                }

                sql += " order by t1.lastupdatetime desc";

                var obj = cn.Page<taskcenter_tasklist>(parameter.pageIndex, parameter.limit, sql, ref total).AsList();

                return obj;
            }
        }

        /// <summary>
        /// 更新任务状态
        /// </summary>
        /// <param name="id">任务id</param>
        /// <param name="status">任务状态 0：未认领，1：任务执行失败，2：已认领，3：执行成功</param>
        /// <param name="fileurl">可下载的文件地址</param>
        /// <returns></returns>
        public string UpdateTask(int id, int status, string fileurl)
        {
            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.QueryFirstOrDefault<taskcenter_tasklist>("select t1.* from taskcenter_tasklist t1 where id=" + id);
                if (obj == null)
                {
                    return "找不到该任务";
                }

                obj.status = status;
                obj.fileurl = fileurl;
                obj.lastupdatetime = DateTime.Now;

                cn.Update(obj);

                return "";
            }
        }

        #endregion

        #region 任务帐号

        /// <summary>
        /// 获取任务帐号列表
        /// </summary>
        /// <param name="templateid"></param>
        /// <returns></returns>
        public List<taskcenter_accounts> ListAccount(int data_type)
        {
            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if(cn.State== System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var sql = "select * from taskcenter_accounts where data_type="+ data_type;

                return cn.Query<taskcenter_accounts>(sql).AsList();
            }
        }

        /// <summary>
        /// 获取帐号详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public taskcenter_accounts GetAccountInfo(int id)
        {
            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if(cn.State== System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                return cn.QueryFirstOrDefault<taskcenter_accounts>("select * from taskcenter_accounts where id=" + id);
            }
        }

        /// <summary>
        /// 保存帐号信息
        /// </summary>
        /// <param name="m"></param>
        /// <param name="uid">当前用户id</param>
        /// <param name="username">当前用户名称</param>
        /// <returns></returns>
        public string SaveAccount(taskcenter_accounts m,int uid,string username)
        {
            try
            {
                using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
                {
                    if (cn.State == System.Data.ConnectionState.Closed)
                    {
                        cn.Open();
                    }

                    var countPlatform = cn.QueryFirstOrDefault<int>($"select count(*) from taskcenter_accounts where platform_index={m.platform_index} and platform!='{m.platform}'");

                    if(countPlatform>0)
                    {
                        return "平台索引值冲突，请重新设置。";
                    }

                    var obj = cn.QueryFirstOrDefault<taskcenter_accounts>("select * from taskcenter_accounts where id=" + m.id);
                    if (obj == null)
                    {
                        obj = new taskcenter_accounts
                        {
                            status = m.status,
                            account = m.account,
                            apiurl = m.apiurl,
                            data_type = m.data_type,
                            frequency = m.frequency??"",
                            note = m.note??"",
                            platform = m.platform,
                            platform_index = m.platform_index,
                            pwd = m.pwd??"",
                            token = m.token??"",
                            website = m.website??"",
                        };

                        cn.Insert(obj);

                    }
                    else
                    {
                        obj.account = m.account;
                        obj.apiurl = m.apiurl;
                        obj.data_type = m.data_type;
                        obj.frequency = m.frequency??"";
                        obj.note = m.note??"";
                        obj.platform = m.platform;
                        obj.platform_index = m.platform_index;
                        obj.pwd = m.pwd??"";
                        obj.token = m.token??"";
                        obj.website = m.website??"";

                        obj.status = m.status;

                        cn.Update(obj);
                    }
                }

                return "";

            }
            catch (Exception ex)
            {

                return ex.Message;
            }
        }

        #endregion

        #region 数据类型

        public List<taskcenter_datatype> ListDataType()
        {
            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if(cn.State== System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                return cn.Query<taskcenter_datatype>("select * from taskcenter_datatype").AsList();
            }

        }

        #endregion
    }
}
