/*
 * Copyright (C) 2023, KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
#include "searchmarch.h"
#include <QDebug>
#include <QFile>

SearchThread::SearchThread(SearchMarch *parent) : QThread(parent) {}

void SearchThread::run()
{
    SearchMarch *m_worker = qobject_cast<SearchMarch *>(parent());
    if (!m_worker) {
        return;
    }
    // CN101250101,changsha,长沙,CN,China,中国,hunan,湖南,changsha,长沙,28.19409,112.98228,"430101,430100,430000",
    //本地词表--存储各地区的中英文名称，对应的cityId，经纬度等信息
    //在开始时，将本地词表中的所有的地区的信息m_locatonList列表中，元素为LocationData结构体
    QFile file(":/data/data/china-city-list.csv");
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        //读取行
        QString line = file.readLine();
        line = line.replace("\n", "");
        //去掉首行，没有数据的，遍历整个词表csv，将其存储在m_locatonList列表中
        while (!line.isEmpty()) {
            QStringList resultList = line.split(",");
            if (resultList.length() < 10) {
                line = file.readLine();
                line = line.replace("\n", "");
                continue;
            }

            QString id = resultList.at(0);
            if (!id.startsWith("CN")) {
                line = file.readLine();
                line = line.replace("\n", "");
                continue;
            }

            LocationData data;
            data.id = id.remove(0, 2); // remove "CN"
            data.city_en = resultList.at(1).toLower().remove(QRegExp("\\s")).remove("'");
            data.city = resultList.at(2).toLower().remove(QRegExp("\\s")).remove("'");
            data.country_en = resultList.at(4);
            data.country = resultList.at(5);
            data.province_en = resultList.at(6).toLower().remove(QRegExp("\\s")).remove("'");
            data.province = resultList.at(7).toLower().remove(QRegExp("\\s")).remove("'");
            data.admin_district_en = resultList.at(8);
            data.admin_district = resultList.at(9);
            data.shorthand = resultList.last().toLower().remove(QRegExp("\\s")).remove("'");

            m_worker->m_locatonList << data; //将数据存入m_locatonList中

            line = file.readLine();
            line = line.replace("\n", "");
        }
        file.close();
    }
}


SearchMarch::SearchMarch(QObject *parent) : QObject(parent)
{
    m_workerThread = new SearchThread(this);
    m_workerThread->start();
}

SearchMarch::~SearchMarch()
{
    m_workerThread->deleteLater();
}
//返回搜索结果
QList<LocationData> SearchMarch::exactMatchCity(const QString &inputText) const
{
    QList<LocationData> searchedList;
    if (m_locatonList.isEmpty()) {
        m_workerThread->start();
    }
    //搜索匹配-遍历m_locatonList
    for (const LocationData line : m_locatonList) {
        if (line.shorthand == inputText || line.id == inputText ||            //拼音和ID
            // line.province == inputText || line.province_en == inputText ||    //省
            // line.city.contains(inputText) || line.city_en.contains(inputText) //县
            line.city.startsWith(inputText) || line.city_en.startsWith(inputText) //县
        ) {
            //保证完全匹配的字符串放在显示的第一个
            if (inputText == line.city_en) {
                searchedList.insert(0, line);
            } else {
                searchedList.append(line); //将数据加入列表
            }
        }
    }
    return searchedList;
}
//自动定位-查找当前地区id
QString SearchMarch::setAutomaticCity(const QString &cityName)
{
    QString cityId;

    if (cityName.isEmpty()) {
        return cityId;
    }
    QFile file(":/data/data/china-city-list.csv");
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QString line = file.readLine();

        line = line.replace("\n", "");
        while (!line.isEmpty()) {
            QStringList resultList = line.split(",");
            if (resultList.length() < 10) {
                line = file.readLine();
                line = line.replace("\n", "");
                continue;
            }
            //("CN101340406", "yunlin", "云林", "CN", "China", "中国", "taiwan", "台湾", "taizhong", "台中", "yl",
            //"23.718", "120.538", "710000")
            QString id = resultList.at(0);
            if (!id.startsWith("CN")) {
                line = file.readLine();
                line = line.replace("\n", "");
                continue;
            }
            //对比cityname和词表的city，拿id，去CN
            if (resultList.at(1).compare(cityName, Qt::CaseInsensitive) == 0
                || resultList.at(2).compare(cityName, Qt::CaseInsensitive) == 0
                || QString(resultList.at(2) + "市").compare(cityName, Qt::CaseInsensitive) == 0
                || QString(resultList.at(2) + "区").compare(cityName, Qt::CaseInsensitive) == 0
                || QString(resultList.at(2) + "县").compare(cityName, Qt::CaseInsensitive) == 0) {
                id.remove(0, 2); // remove "CN"
                cityId = id;
                break;
            }

            line = file.readLine();
            line = line.replace("\n", "");
        }
        file.close();
    }
    return cityId;
}

//自动定位-查找当前地区id
QString SearchMarch::matchCityName(const QString &ID)
{
    QString cityId = QString("CN%1").arg(ID);
    QString cityName;

    if (cityId.isEmpty()) {
        return cityName;
    }
    QFile file(":/data/data/china-city-list.csv");
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QString line = file.readLine();

        line = line.replace("\n", "");
        while (!line.isEmpty()) {
            QStringList resultList = line.split(",");
            if (resultList.length() < 10) {
                line = file.readLine();
                line = line.replace("\n", "");
                continue;
            }
            //("CN101340406", "yunlin", "云林", "CN", "China", "中国", "taiwan", "台湾", "taizhong", "台中", "yl",
            //"23.718", "120.538", "710000")
            QString id = resultList.at(0);
            if (!id.startsWith("CN")) {
                line = file.readLine();
                line = line.replace("\n", "");
                continue;
            }
            //对比cityID和词表的city，拿name
            if (resultList.at(0).compare(cityId, Qt::CaseInsensitive) == 0) {
                cityName = resultList.at(2);
                break;
            }

            line = file.readLine();
            line = line.replace("\n", "");
        }
        file.close();
    }
    return cityName;
}
