#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import csv
import os
import re
import tempfile
from datetime import datetime

import openpyxl
from django.conf import settings

from django_base_ai.utils.validator import CustomValidationError


def import_to_data(file_url, field_data, m2m_fields=None):
    """
    读取导入的excel文件
    :param file_url:
    :param field_data: 首行数据源
    :param m2m_fields: 多对多字段
    :return:
    """
    # 读取excel 文件
    file_path_dir = f"{settings.BASE_DIR}{file_url}"
    print("file_path_dir=", file_path_dir)

    # 检查文件扩展名，判断是否为 CSV 文件
    file_ext = os.path.splitext(file_path_dir)[1].lower()
    is_csv = file_ext == ".csv"
    temp_excel_path = None  # 初始化临时文件路径变量

    # 如果是 CSV 文件，需要转换为 Excel 格式
    if is_csv:
        # 获取原始文件名（去掉扩展名）作为 sheet 名称
        original_filename = os.path.splitext(os.path.basename(file_path_dir))[0]
        # Excel sheet 名称限制为 31 个字符
        sheet_name = original_filename[:31] if len(original_filename) <= 31 else original_filename[:28] + "..."

        # 创建临时 Excel 文件
        temp_excel = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
        temp_excel_path = temp_excel.name
        temp_excel.close()

        # 读取 CSV 文件并转换为 Excel
        workbook = openpyxl.Workbook()
        # 删除默认的 sheet
        if "Sheet" in workbook.sheetnames:
            workbook.remove(workbook["Sheet"])
        # 创建新的 sheet，使用原始文件名作为名称
        ws = workbook.create_sheet(sheet_name)

        # 读取 CSV 文件内容
        try:
            with open(file_path_dir, encoding="utf-8-sig") as csvfile:
                # 尝试检测编码
                csv_reader = csv.reader(csvfile)
                for row in csv_reader:
                    ws.append(row)
        except UnicodeDecodeError:
            # 如果 UTF-8 失败，尝试 GBK 编码
            with open(file_path_dir, encoding="gbk") as csvfile:
                csv_reader = csv.reader(csvfile)
                for row in csv_reader:
                    ws.append(row)

        # 保存临时 Excel 文件
        workbook.save(temp_excel_path)
        workbook.close()

        # 使用临时 Excel 文件路径
        file_path_dir = temp_excel_path

    # 加载 Excel 文件
    workbook = openpyxl.load_workbook(file_path_dir)
    table = workbook[workbook.sheetnames[0]]
    theader = tuple(table.values)[0]  # Excel的表头
    is_update = "更新主键(勿改)" in theader  # 是否导入更新
    if is_update is False:  # 不是更新时,删除id列
        field_data.pop("id")
    # 获取参数映射
    validation_data_dict = {}
    for key, value in field_data.items():
        if isinstance(value, dict):
            choices = value.get("choices", {})
            data_dict = {}
            if choices.get("data"):
                for k, v in choices.get("data").items():
                    data_dict[k] = v
            elif choices.get("queryset") and choices.get("values_name"):
                data_list = choices.get("queryset").values(
                    choices.get("values_name"), choices.get("values_value", "id")
                )
                for ele in data_list:
                    data_dict[ele.get(choices.get("values_name"))] = ele.get(choices.get("values_value", "id"))
            else:
                continue
            validation_data_dict[key] = data_dict
    # 创建一个空列表，存储Excel的数据
    tables = []
    for i, row in enumerate(range(table.max_row)):
        if i == 0:
            continue
        array = {}
        for index, item in enumerate(field_data.items()):
            items = list(item)
            key = items[0]
            values = items[1]
            value_type = "str"
            if isinstance(values, dict):
                value_type = values.get("type", "str")
            cell_value = table.cell(row=row + 1, column=index + 2).value
            if cell_value is None or cell_value == "":
                continue
            elif value_type == "date":
                try:
                    cell_value = datetime.strptime(str(cell_value), "%Y-%m-%d %H:%M:%S").date()
                except (ValueError, TypeError):
                    raise CustomValidationError("日期格式不正确")
            elif value_type == "datetime":
                cell_value = datetime.strptime(str(cell_value), "%Y-%m-%d %H:%M:%S")
            else:
                # 由于excel导入数字类型后，会出现数字加 .0 的，进行处理
                if type(cell_value) is float and str(cell_value).split(".")[1] == "0":
                    cell_value = int(str(cell_value).split(".")[0])
                elif type(cell_value) is str:
                    cell_value = cell_value.strip(" \t\n\r")
            if key in validation_data_dict:
                array[key] = validation_data_dict.get(key, {}).get(cell_value, None)
                if key in m2m_fields:
                    array[key] = list(
                        filter(
                            lambda x: x,
                            [
                                validation_data_dict.get(key, {}).get(value, None)
                                for value in re.split(r"[，；：|.,;:\s]\s*", cell_value)
                            ],
                        )
                    )
            else:
                array[key] = cell_value
        tables.append(array)

    # 关闭工作簿
    workbook.close()

    # 如果是 CSV 文件，删除临时 Excel 文件
    if is_csv and os.path.exists(temp_excel_path):
        try:
            os.unlink(temp_excel_path)
        except Exception as e:
            print(f"删除临时文件失败: {e}")

    return tables
