/*
 * 创客
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using MySystem.Models.KxsMain;
using Library;
using LitJson;

namespace MySystem.Service.KxsMain
{
    public class UsersService
    {
        static string _conn = ConfigurationManager.AppSettings["KxsSqlConnStr"].ToString();

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="relationData">关联表</param>
        /// <param name="condition">查询条件(sql语句)</param>
        /// <param name="count">总数（输出）</param>
        /// <param name="page">页码</param>
        /// <param name="limit">每页条数</param>
        /// <returns></returns>
        public static List<Dictionary<string, object>> List(List<RelationData> relationData, string condition, out int count, int page = 1, int limit = 30, string orderBy = "Sort desc,Id desc")
        {
            List<string> fields = new List<string>(); //要显示的列
            fields.Add("Id");
            fields.Add("CreateDate"); //注册时间
            fields.Add("Status"); //状态
            fields.Add("MakerCode"); //创客编号
            fields.Add("RealName"); //真实姓名
            fields.Add("Mobile"); //手机号
            fields.Add("CertId"); //身份证号
            fields.Add("UserLevel"); //创客等级
            fields.Add("AgentAreas"); //代理区域
            fields.Add("MerchantType"); //商户创客类型
            fields.Add("MerchantDate"); //成为商户型创客时间
            fields.Add("AuthFlag"); //实名标识
            fields.Add("AuthDate"); //实名时间
            fields.Add("RiskFlag"); //风控标识
            fields.Add("ParentUserId"); //直属创客Id
            fields.Add("ParentNav"); //父级集合
            fields.Add("SettleBankCardNo");
            fields.Add("SettleBankName");
            // fields.Add("SettleAmount"); //最低结算金额
            // fields.Add("CashFreezeAmt"); //提现冻结金额
            // fields.Add("CertValidStartDate"); //身份证有效期开始时间
            // fields.Add("CertValidEndDate"); //身份证有效期结束时间
            // fields.Add("SettleBankCardName"); //结算银行卡户名
            // fields.Add("AgentLevel"); //代理等级
            // fields.Add("CashStatus"); //代付账户状态
            // fields.Add("LeaderLevel"); //盟主等级
            // fields.Add("BusinessFlag"); //企业标记
            // fields.Add("DeviceType"); //设备类型
            // fields.Add("HelpProfitAgree"); //助利宝协议标记
            // fields.Add("HelpProfitAgreeDate"); //助利宝协议标记时间

            Dictionary<string, object> obj = new DbService(AppConfig.Base.kxsMainTables, _conn).IndexData("Users", relationData, orderBy, page, limit, condition, fields);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            count = int.Parse(obj["count"].ToString());
            return diclist;
        }
        public static List<Dictionary<string, object>> List(List<RelationData> relationData, string condition, int page = 1, int limit = 30, string orderBy = "Sort desc,Id desc")
        {
            List<string> fields = new List<string>(); //要显示的列
            fields.Add("Id");
            fields.Add("CreateDate"); //添加时间
            fields.Add("Status"); //状态
            fields.Add("RealName"); //真实姓名
            fields.Add("CertId"); //身份证号
            fields.Add("UserLevel"); //创客等级
            fields.Add("MerchantType"); //商户创客类型
            fields.Add("MerchantDate"); //成为商户型创客时间
            fields.Add("AuthFlag"); //实名标识
            fields.Add("RiskFlag"); //风控标识
            fields.Add("MakerCode"); //创客编号
            fields.Add("SettleAmount"); //最低结算金额
            fields.Add("CashFreezeAmt"); //提现冻结金额
            fields.Add("CertValidStartDate"); //身份证有效期开始时间
            fields.Add("CertValidEndDate"); //身份证有效期结束时间
            fields.Add("SettleBankCardName"); //结算银行卡户名
            fields.Add("AgentLevel"); //代理等级
            fields.Add("AgentAreas"); //代理区域
            fields.Add("CashStatus"); //代付账户状态
            fields.Add("LeaderLevel"); //盟主等级
            fields.Add("BusinessFlag"); //企业标记
            fields.Add("DeviceType"); //设备类型
            fields.Add("HelpProfitAgree"); //助利宝协议标记
            fields.Add("HelpProfitAgreeDate"); //助利宝协议标记时间

            Dictionary<string, object> obj = new DbService(AppConfig.Base.kxsMainTables, _conn).IndexData("Users", relationData, orderBy, page, limit, condition, fields);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            return diclist;
        }

        /// <summary>
        /// 查询一条记录
        /// </summary>
        /// <param name="Id">主键Id</param>
        /// <returns></returns>
        public static Users Query(int Id)
        {
            WebCMSEntities db = new WebCMSEntities();
            Users editData = db.Users.FirstOrDefault(m => m.Id == Id) ?? new Users();
            db.Dispose();
            return editData;
        }

        public static Users Query(string condition, string fields = "*")
        {
            // DataTable dt = new DbService(AppConfig.Base.kxsMainTables, _conn).QueryDetail(fields, "Users", condition);
            // if(dt.Rows.Count > 0)
            // {
            //     Dictionary<string, object> row = new Dictionary<string, object>();
            //     foreach(DataColumn dc in dt.Columns)
            //     {
            //         row.Add(dc.ColumnName, dt.Rows[0][dc.ColumnName].ToString());
            //     }
            //     return Newtonsoft.Json.JsonConvert.DeserializeObject<Users>(Newtonsoft.Json.JsonConvert.SerializeObject(row));
            // }
            var users = new DbService(AppConfig.Base.kxsMainTables, _conn).Query(fields, "Users", condition);
            if (users.Count > 0)
            {
                return Newtonsoft.Json.JsonConvert.DeserializeObject<Users>(Newtonsoft.Json.JsonConvert.SerializeObject(users));
            }
            return new Users();
        }

        /// <summary>
        /// 通过创客编号查询一条记录
        /// </summary>
        /// <param name="MakerCode">创客编号</param>
        /// <returns></returns>
        public static Users QueryByMakerCode(string MakerCode)
        {
            WebCMSEntities db = new WebCMSEntities();
            Users editData = db.Users.FirstOrDefault(m => m.MakerCode == MakerCode) ?? new Users();
            db.Dispose();
            return editData;
        }

        /// <summary>
        /// 查询记录数
        /// </summary>
        /// <param name="Id">主键Id</param>
        /// <returns></returns>
        public static int Count(string condition = "")
        {
            int result = 0;
            DataTable dt = CustomerSqlConn.dtable("select count(Id) from Users where 1=1" + condition, _conn);
            if (dt.Rows.Count > 0)
            {
                result = int.Parse(function.CheckInt(dt.Rows[0][0].ToString()));
            }
            return result;
        }

        /// <summary>
        /// 查询是否存在
        /// </summary>
        /// <param name="Id">主键Id</param>
        /// <returns></returns>
        public static bool Exist(int Id)
        {
            WebCMSEntities db = new WebCMSEntities();
            bool check = db.Users.Any(m => m.Id == Id);
            db.Dispose();
            return check;
        }

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="Fields">要设置的字段</param>
        /// <returns></returns>
        public static AppResultJson Add(Dictionary<string, object> fields, bool check = true)
        {
            int Id = new DbService(AppConfig.Base.kxsMainTables, _conn).Add("Users", fields, 0);
            return new AppResultJson() { Status = "1", Data = Id };
        }

        /// <summary>
        /// 修改数据
        /// </summary>
        /// <param name="Fields">要设置的字段</param>
        /// <param name="Id">主键Id</param>
        public static AppResultJson Edit(Dictionary<string, object> fields, int Id, bool check = true)
        {
            new DbService(AppConfig.Base.kxsMainTables, _conn).Edit("Users", fields, Id);
            return new AppResultJson() { Status = "1", Data = Id };
        }

        /// <summary>
        /// 逻辑删除
        /// </summary>
        /// <param name="Id">主键Id</param>
        public static void Remove(int Id)
        {
            Dictionary<string, object> fields = new Dictionary<string, object>();
            fields.Add("Status", -1);
            new DbService(AppConfig.Base.kxsMainTables, _conn).Edit("Users", fields, Id);
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="Id">主键Id</param>
        public static void Delete(int Id)
        {
            new DbService(AppConfig.Base.kxsMainTables, _conn).Delete("Users", Id);
        }

        /// <summary>
        /// 排序
        /// </summary>
        /// <param name="Id">主键Id</param>
        /// <param name="Sort">排序序号</param>
        public static void Sort(int Id, int Sort)
        {
            new DbService(AppConfig.Base.kxsMainTables, _conn).Sort("Users", Sort, Id);
        }

        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="ExcelData">json数据</param>
        public static void Import(string ExcelData)
        {
            WebCMSEntities db = new WebCMSEntities();
            JsonData list = JsonMapper.ToObject(ExcelData);
            for (int i = 1; i < list.Count; i++)
            {
                JsonData dr = list[i];

                db.Users.Add(new Users()
                {
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,

                });
                db.SaveChanges();
            }
            db.Dispose();
        }

        /// <summary>
        /// 导出excel表格
        /// </summary>
        /// <param name="fields">查询条件(单个字段)</param>
        /// <param name="condition">查询条件(sql语句)</param>
        /// <returns></returns>
        // public static void ExportExcel(List<RelationData> relationData, string condition)
        // {

        // }
    }
}