package com.kxs.adminap.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import com.kxs.adminap.enity.RelationData;
import com.kxs.adminap.service.DbConn;

public class DbService {
    Dictionary<String, Map<String, String>> _database;
    String _url;
    String _user;
    String _pwd;

    public DbService(Dictionary<String, Map<String, String>> database, String url, String username, String password) {
        _database = database;
        _url = url;
        _user = username;
        _pwd = password;
    }

    
    // 根据条件查询列表

    public Dictionary<String, Object> IndexData(String TableName, List<RelationData> RelationDatas, String OrderBy)
    {
        return IndexData(TableName, RelationDatas, OrderBy, 1, 20, "", new ArrayList<>());
    }
    public Dictionary<String, Object> IndexData(String TableName, List<RelationData> RelationDatas, String OrderBy, int PageNum)
    {
        return IndexData(TableName, RelationDatas, OrderBy, PageNum, 20, "", new ArrayList<>());
    }
    public Dictionary<String, Object> IndexData(String TableName, List<RelationData> RelationDatas, String OrderBy, int PageNum, int PageSize)
    {
        return IndexData(TableName, RelationDatas, OrderBy, PageNum, PageSize, "", new ArrayList<>());
    }
    public Dictionary<String, Object> IndexData(String TableName, List<RelationData> RelationDatas, String OrderBy, int PageNum, int PageSize, String Condition, List<String> fields)
    {
        String field = "";
        if(fields.size() > 0)
        {
            for(String f : fields)
            {
                field += TableName + "." + f + ",";
            }
            field = field.substring(0, field.length() - 1);
        }
        else
        {
            field = TableName + ".*";
        }
        if(!OrderBy.isEmpty())
        {
            OrderBy = TableName + "." + OrderBy.replaceAll(",", "," + TableName + ".");
        }
        String condition = Condition;
        String leftJoinSql = "";
        String sqlstr = "";
        if (RelationDatas.size() > 0)
        {
            int index = 0;
            for(RelationData RelationData : RelationDatas)
            {
                index += 1;
                for(String relationField : RelationData.ReturnField)
                {
                    field += "," + RelationData.Table + index + "." + relationField + " " + RelationData.Field + "For" + relationField;
                }
                leftJoinSql += " left join " + RelationData.Table + " " + RelationData.Table + index + " on " + TableName + "." + RelationData.Field + "=" + RelationData.Table + index + ".Id";
            }
        }
        if (PageNum > 1)
        {
            int spage = (PageNum - 1) * PageSize;
            sqlstr = "select " + field + " from " + TableName + leftJoinSql + " where 1=1" + condition.replaceAll(" and ", " and " + TableName + ".") + " order by " + OrderBy + " limit " + spage + "," + PageSize;
        }
        else
        {
            sqlstr = "select " + field + " from " + TableName + leftJoinSql + " where 1=1" + condition.replaceAll(" and ", " and " + TableName + ".") + " order by " + OrderBy + " limit "+ PageSize;
        }
        List<Dictionary<String, Object>> list = DbConn.Query(sqlstr, _url, _user, _pwd);
        Integer recordcount = 0;
        Dictionary<String, Object> count = DbConn.QueryOne("select count(Id) count from " + TableName + " where 1=1" + condition.replaceAll(" and ", " and " + TableName + "."), _url, _user, _pwd);
        if (count.size() > 0)
        {
            recordcount = (Integer)count.get("count)");
        }
        Dictionary<String, Object> obj = new Hashtable<>();
        obj.put("code", 0);
        obj.put("msg", "");
        obj.put("count", recordcount);
        obj.put("data", list);
        return obj;
    }

    // 添加数据

    public int Add(String TableName, Map<String, Object> Fields, int Count, Boolean SycnUpdateDate)
    {
        List<Object> pc = new ArrayList<>();
        Map<String, String> Columns = _database.get(TableName);
        if (!Columns.containsKey("Status"))
        {
            Columns.put("Status", "int");
        }
        if (!Columns.containsKey("Sort"))
        {
            Columns.put("Sort", "int");
        }
        if (!Columns.containsKey("SeoTitle"))
        {
            Columns.put("SeoTitle", "nvarchar");
        }
        if (!Columns.containsKey("SeoKeyword"))
        {
            Columns.put("SeoKeyword", "nvarchar");
        }
        if (!Columns.containsKey("SeoDescription"))
        {
            Columns.put("SeoDescription", "nvarchar");
        }
        if (!Columns.containsKey("CreateDate"))
        {
            Columns.put("CreateDate", "datetime");
        }
        String FieldList = "", FieldValues = "";
        for (var item : Fields.entrySet())
        {
            String FieldName = item.getKey();
            if (Fields.get(FieldName) != null)
            {
                FieldList += FieldName + ",";
                FieldValues += "?,";
                pc.add(Fields.get(FieldName));
            }
        }
        if (SycnUpdateDate)
        {
            FieldList += "CreateDate,UpdateDate";
            FieldValues += "?,?";
        }
        else
        {
            FieldList += "CreateDate";
            FieldValues += "?";
        }
        pc.add(new Date());
        if (SycnUpdateDate)
        {
            pc.add(new Date());
        }
        String sqlstr = "insert into " + TableName + " (" + FieldList + ") values (" + FieldValues + ");select @@IDENTITY";
        Integer Id = 0;
        Dictionary<String, Object> dt = DbConn.QueryOne(sqlstr, _url, _user, _pwd);
        if (dt.size() > 0)
        {
            Id = (Integer)dt.get(0);
        }
        return Id;
    }

    // 修改数据

    public void Edit(String TableName, Map<String, Object> Fields, int Id)
    {
        List<Object> pc = new ArrayList<>();
        Map<String, String> Columns = _database.get(TableName);
        if (!Columns.containsKey("Status"))
        {
            Columns.put("Status", "int");
        }
        if (!Columns.containsKey("Sort"))
        {
            Columns.put("Sort", "int");
        }
        if (!Columns.containsKey("SeoTitle"))
        {
            Columns.put("SeoTitle", "nvarchar");
        }
        if (!Columns.containsKey("SeoKeyword"))
        {
            Columns.put("SeoKeyword", "nvarchar");
        }
        if (!Columns.containsKey("SeoDescription"))
        {
            Columns.put("SeoDescription", "nvarchar");
        }
        if (!Columns.containsKey("CreateDate"))
        {
            Columns.put("CreateDate", "datetime");
        }
        String FieldList = "";
        for (var item : Fields.entrySet())
        {
            String FieldName = item.getKey();
            if (Fields.get(FieldName) != null)
            {
                FieldList += FieldName + "=?,";
                pc.add(Fields.get(FieldName));
            }
        }
        FieldList += "UpdateDate=?";
        pc.add(new Date());
        String sqlstr = "update " + TableName + " set " + FieldList + " where Id=" + Id;
        DbConn.Op(sqlstr, _url, _user, _pwd);
    }

    // 删除数据

    public void Delete(String TableName, int Id)
    {
        List<Object> pc = new ArrayList<>();
        pc.add(Id);
        DbConn.Op("delete from " + TableName + " where Id=?", pc, _url, _user, _pwd);
    }

    // 排序

    public void Sort(String TableName, int Sort, int Id)
    {
        List<Object> pc = new ArrayList<>();
        pc.add(Sort);
        pc.add(Id);
        DbConn.Op("update " + TableName + " set Sort=? where Id=?", pc, _url, _user, _pwd);
    }


    // 获取单条信息

    public Dictionary<String, Object> Query(String Fields, String TableName, String Condition)
    {
        String sqlstr = "select " + Fields + " from " + TableName + " where " + Condition + " limit 1";
        Dictionary<String, Object> result = DbConn.QueryOne(sqlstr, _url, _user, _pwd);
        return result;
    }
    public Dictionary<String, Object> Query(String Fields, String TableName, Integer Id)
    {
        String sqlstr = "select " + Fields + " from " + TableName + " where Id=" + Id;
        Dictionary<String, Object> result = DbConn.QueryOne(sqlstr, _url, _user, _pwd);
        return result;
    }

}