using DapperORM;
using DapperORM.Common.Models;
using DapperORM.Enums;
using MySql.Data.MySqlClient;
using PushInfo.Core.IDAL;
using PushInfo.Core.Models.Tables;
using PushPlatform.Common.Enumerate;
using PushPlatform.Common.Util;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PushInfo.Core.BLL
{
    public class PushDataBLL
    {
        /// <summary>
        /// 项目任务配置表数据访问接口
        /// </summary>
        private ISelectItemDetailDAL mapSelItemDetailDal;
        /// <summary>
        /// 项目任务配置表数据访问接口
        /// </summary>
        private IMappushUserRoleDAL mapUserRoleDal;
        /// <summary>
        /// 构造函数
        /// </summary>
        public PushDataBLL()
        {
            this.mapSelItemDetailDal = DALFactory.CreateSelectItemDetailDAL();
            this.mapUserRoleDal = DALFactory.CreateMappushUserRoleDAL();
        }

        #region 查询需要推送数据Dapper方法
        /// <summary>
        /// 查询需要推送数据
        /// </summary>
        /// <param name="task">推送数据配置</param>
        /// <returns></returns>
        public DataTable GetPushData(Map_Project_Push task)
        {
            Dictionary<string, object> param = new Dictionary<string, object>();
            DataTable table = new DataTable();
            ResultModelDataSet dsModel = null;
            var result = mapSelItemDetailDal.GetModel(x => x.Id == task.Db_ConnectId && x.Is_Deleted == 0);
            string dbConnectStr = "";
            DbProviderType providerType = DbProviderType.MySql;
            if (result.IsSuccess())
            {
                dbConnectStr = result.Data.Value;
                if(result.Data.Select_Type == (int)SelectType.Sql连接)
                {
                    providerType = DbProviderType.SqlServer;
                }
            }
            else
            {
                throw new Exception(result.Msg);
            }
            BaseRepository<DataTable> DataBLL = new BaseRepository<DataTable>(dbConnectStr, dbConnectStr, providerType);
            if (task.Push_ActionType == (int)PushActionType.存储过程)
            {
                if (!string.IsNullOrEmpty(task.Push_Target))
                {
                    param.Add("@roleId", task.Push_Target);
                }
                if (!string.IsNullOrEmpty(task.Project_Id))
                {
                    param.Add("@projectId", task.Project_Id);
                }
                dsModel = DataBLL.QueryDataSetAysnc(task.Push_Action, param, null,CommandType.StoredProcedure).Result;
            }
            else if(task.Push_ActionType == (int)PushActionType.SQL)
            {
                if (task.Push_Action.IndexOf("@roleId") > -1)
                {
                    param.Add("@roleId", task.Push_Target);
                }
                if (task.Push_Action.IndexOf("@projectId") > -1)
                {
                    param.Add("@projectId", task.Project_Id);
                }
                if(task.Push_Action.IndexOf("@userId") > -1)
                {
                    param.Add("@userId", task.User_Id);
                }
                dsModel = DataBLL.QueryDataSetAysnc(task.Push_Action, param,null, CommandType.Text).Result;
            }
            if (dsModel.IsSuccess())
            {
                table = dsModel.Data.Tables[0];
            }
            else
            {
                throw new Exception(result.Msg);
            }
            return table;
        }
        #endregion

        #region 查询需要推送数据ADO方法
        /// <summary>
        /// 查询需要推送数据
        /// </summary>
        /// <param name="task">推送数据配置</param>
        /// <returns></returns>
        public DataTable GetPushDataAdo(Map_Project_Push task)
        {
            if(task.Push_ActionType == (int)PushActionType.SQL && !string.IsNullOrEmpty(task.Push_Action) && task.Push_Action.IndexOf("@userId")>-1 && string.IsNullOrEmpty(task.User_Id))
            {
                var userResult = mapUserRoleDal.Fetch(x => x.Project_Id == task.Project_Id && x.Map_Project_Push_Id == task.Id && x.Is_Deleted == 0);
                if (userResult.IsSuccess())
                {
                    var dataInfo = userResult.Data.ToList();
                    if(dataInfo.Count>0)
                    {
                        if(dataInfo.FirstOrDefault().User_Id == "allUserId")
                        {
                            task.User_Id = "allUserId";
                        }
                        else
                        {
                            task.User_Id = string.Join(",", dataInfo.Select(x=>x.User_Id));
                        }
                    }
                }
            }
            DataTable table = new DataTable();
            var result = mapSelItemDetailDal.GetModel(x => x.Id == task.Db_ConnectId && x.Is_Deleted == 0);
            string dbConnectStr = "";
            if (result.IsSuccess())
            {
                dbConnectStr = result.Data.Value;
            }
            else
            {
                throw new Exception(result.Msg);
            }
            table = GetTableValue(task.Push_ActionType, result.Data.Select_Type, dbConnectStr, task.Push_Action, task.Push_Target, task.Project_Id, task.User_Id,task.valMap);
            if(!string.IsNullOrEmpty(task.Push_User_Action) && !string.IsNullOrEmpty(task.Db_User_ConnectId))  //权限系统独立出来使用，用户取自其它数据库
            {
                result = mapSelItemDetailDal.GetModel(x => x.Id == task.Db_User_ConnectId && x.Is_Deleted == 0);
                if (result.IsSuccess())
                {
                    dbConnectStr = result.Data.Value;
                }
                else
                {
                    throw new Exception(result.Msg);
                }
                DataTable table2 = GetTableValue(task.Push_User_ActionType, result.Data.Select_Type, dbConnectStr, task.Push_User_Action, task.Push_Target, task.Project_Id, task.User_Id,null);
                if(table2.Rows.Count>0)
                {
                    table = DataTableHelp.UniteDataTableOfLinq(table, table2);
                }
                else
                {
                    table = new DataTable();
                }
            }
            return table;
        }

        #region 获取推送datatable
        /// <summary>
        /// 获取推送datatable
        /// </summary>
        /// <param name="pushActionType">数据查询访视</param>
        /// <param name="selectType">链接方式mysql，sqlservice</param>
        /// <param name="dbStr">数据库连接</param>
        /// <param name="sqlStr">查询语句</param>
        /// <param name="pushTarget">推送对象</param>
        /// <param name="projectId">项目Id</param>
        /// <param name="userId">用户Id</param>
        /// <param name="valMap">传过来的字段值</param>
        /// <returns></returns>

        public DataTable GetTableValue(int? pushActionType,int selectType,string dbStr,string sqlStr,string pushTarget,string projectId,string userId,Dictionary<string,string> valMap)
        {
            Dictionary<string, object> param = new Dictionary<string, object>();
            if(valMap!=null && valMap.Count>0)
            {
                foreach(var item in valMap)
                {
                    param.Add(item.Key,item.Value);
                }
            }
            DataTable table = new DataTable();
            if (pushActionType == (int)PushActionType.存储过程)
            {
                if (!string.IsNullOrEmpty(pushTarget))
                {
                    param.Add("@roleId", pushTarget);
                }
                if (!string.IsNullOrEmpty(projectId))
                {
                    param.Add("@projectId", projectId);
                }
                if (selectType == (int)SelectType.Mysql连接)
                {
                    MySqlParameter[] msp = {
                    };
                    if (param.Count > 0)
                    {
                        List<MySqlParameter> linList = new List<MySqlParameter>();
                        foreach (var item in param)
                        {
                            linList.Add(new MySqlParameter(item.Key, item.Value));
                        }
                        msp = linList.ToArray();
                    }
                    MySQLHelper mysqlHelper = new MySQLHelper(dbStr);
                    return mysqlHelper.ExecuteDataTable(CommandType.StoredProcedure, sqlStr, msp);
                }
                else
                {
                    SqlParameter[] msp = {
                    };
                    if (param.Count > 0)
                    {
                        List<SqlParameter> linList = new List<SqlParameter>();
                        foreach (var item in param)
                        {
                            linList.Add(new SqlParameter(item.Key, item.Value));
                        }
                        msp = linList.ToArray();
                    }
                    SQLServerDbHelper sqlHelper = new SQLServerDbHelper(dbStr);
                    return sqlHelper.ExecuteDataTable(CommandType.StoredProcedure, sqlStr, msp);
                }
            }
            else if (pushActionType == (int)PushActionType.SQL)
            {
                if (sqlStr.IndexOf("@roleId") > -1)
                {
                    param.Add("@roleId", pushTarget);
                }
                if (sqlStr.IndexOf("@projectId") > -1)
                {
                    param.Add("@projectId", projectId);
                }
                if (sqlStr.IndexOf("@userId") > -1)
                {
                    if (userId == "allUserId")
                        param.Add("@userId", DBNull.Value);
                    else
                        param.Add("@userId", userId);
                }
                if (selectType == (int)SelectType.Mysql连接)
                {
                    MySqlParameter[] msp = {
                    };
                    if (param.Count > 0)
                    {
                        List<MySqlParameter> linList = new List<MySqlParameter>();
                        foreach (var item in param)
                        {
                            linList.Add(new MySqlParameter(item.Key, item.Value));
                        }
                        msp = linList.ToArray();
                    }
                    MySQLHelper mysqlHelper = new MySQLHelper(dbStr);
                    return mysqlHelper.ExecuteDataTable(CommandType.Text, sqlStr, msp);
                }
                else
                {
                    SqlParameter[] msp = {
                    };
                    if (param.Count > 0)
                    {
                        List<SqlParameter> linList = new List<SqlParameter>();
                        foreach (var item in param)
                        {
                            linList.Add(new SqlParameter(item.Key, item.Value));
                        }
                        msp = linList.ToArray();
                    }
                    SQLServerDbHelper sqlHelper = new SQLServerDbHelper(dbStr);
                    return sqlHelper.ExecuteDataTable(CommandType.Text, sqlStr, msp);
                }
            }
            return table;
        }
        #endregion
        #endregion
    }
}
