#!/usr/bin/env python
# -*- coding:utf-8 -*-


from whoosh.filedb.filestore import FileStorage
from whoosh.index import exists_in, open_dir
from whoosh.qparser import QueryParser
from whoosh.qparser import MultifieldParser
from common.base import Config, MyPymysql
from models.ProjectModel import SelectDataTablesInfo


def selectApp(clientContent, quesID=False, indexflag=2):
    myIndexDirFilePath = Config().get_content("indexFilePath")["filepath"]
    my_add_indexdir = myIndexDirFilePath + "/" + "indexdir"
    indexdir = my_add_indexdir
    storage = FileStorage(indexdir)

    fname = storage.list()
    indices = []

    indList = ["metaproject", "metaquestionnaire", "metavariable"]
    for ind in indList:
        indices.append(open_dir(indexdir, ind))

    ret = search(indices, indexflag, clientContent, quesID)
    seacherDatas = FilterSeacherData(ret)
    return seacherDatas


def search(indices, indexflag, clientContent, quesID=None):
    inpval = indexflag
    qparsers = []
    if inpval == 1:
        categories = []
        for ix in indices:
            cat = list(ix.schema._fields.keys())
            for val in cat:
                if val in categories:
                    val = val + " - " + ix.indexname
                categories.append(val)

        for i in range(0, len(indices)):
            # qparsers.append(QueryParser(categories[inpval], indices[i].schema))
            qparsers.append(QueryParser("VarLebel", indices[i].schema))
    else:

        categories = []
        for ix in indices:
            categories.extend(list(ix.schema._fields.keys()))
            qparsers.append(MultifieldParser(categories,
                                             ix.schema))
    inp = clientContent

    data = inp.split('<==>')
    queries = [qparsers[i].parse(data[0].strip()) for i in range(0, len(qparsers))]

    if len(data) > 1:
        limits = int(data[1].strip())
        limits = 10

    results = []
    stats = {}

    for i in range(0, len(indices)):
        searcher = indices[i].searcher()
        res = searcher.search(queries[i], limit=500)
        if len(res) != 0:
            stats[indices[i].indexname] = len(res)
        else:
            continue
        results.extend(res)

    # print(my_result)
    return results


def FilterSeacherData(results, quesID=None):
    my_result = []
    projList = []
    quesList = []
    varList = []  # 所有的变量
    varIDList = []  # 所有的变量id
    DataTableIDList = []
    subVarList = []
    for i in results:
        i = dict(i)
        if "ProjectStatus" in i:
            if i["ProjectStatus"] == "1":
                if i["ProjectPublic"] == "2":
                    projList.append(i)
        if "QuesStatus" in i:
            if i["QuesStatus"] == "1":
                if i["QuesPublic"] == "2":
                    quesList.append(i)
        if "VariableID" in i:
            if i["VarStatus"] == "1" or i["VarStatus"] == 1:
                varIDList.append(i["DataTableID"])
                # DataTableIDList.append(i["DataTableID"])
                varList.append(i)
    '''
        问题：
            1. 我怎么知道这个项目属于哪个平台
            加字段， 项目里面加字段， 指定是哪个平台
    '''

    ret = MyPymysql('metadata')
    for i in varList:
        DataTableIDList.append(i["DataTableID"])
    show_ques_questatus_dataTableID_list = []
    # for subDataTableID in set(DataTableIDList):
    for subDataTableID in set(DataTableIDList):
        var_ques_status_sql = """
        SELECT
        DISTINCT(quesTable.QuesID), quesTable.QuesStatus, varTable.DataTableID, quesTable.QuesPublic, project.ProjectID
        FROM
            meta_variable AS varTable
        LEFT JOIN meta_data_table AS dataTable ON varTable.DataTableID = dataTable.DataTableID
        LEFT JOIN meta_questionnaire quesTable ON dataTable.QuesID = quesTable.QuesID
        LEFT JOIN meta_project project ON quesTable.ProjectID=project.ProjectID
        WHERE
        varTable.DataTableID = '{}';""".format(subDataTableID)
        show_ques_questatus_dataTableID_list.append(ret.selectone_sql(var_ques_status_sql))
    ret.close()

    effectiveVarList = []
    for i in show_ques_questatus_dataTableID_list:
        if (str(i["QuesStatus"]) == "1") and (str(i["QuesPublic"]) == "2"):
            for j in varList:
                if i["DataTableID"] == j["DataTableID"]:
                    j["QuesID"] = str(i["QuesID"])
                    j["ProjectID"] = str(i["ProjectID"])
                    effectiveVarList.append(j)
                else:
                    pass

    my_result = [projList, quesList, effectiveVarList, subVarList]

    return my_result


if __name__ == '__main__':
    # indexflag = 2 # 1是分类索引2是全局索引
    clientContent = "教育"
    quesID = ""
    # selectApp(clientContent, quesID=quesID)
    res = selectApp(clientContent)
    # print(res)
