# -*- coding: utf-8 -*-
import pandas as pd
import datetime
from config import Config
from api import API
import pymysql
from log_config import configure_task_logger, configure_error_task_logger
from back_ground_module import CommonModule

# 获取已经配置好的常规日志记录器
logger = configure_task_logger()

# 获取已经配置好的错误任务日志记录器
error_task_logger = configure_error_task_logger()

start_time = datetime.datetime.now()
api_instance = API()
common_module = CommonModule()


class importCommissionData:
    """
    小六提成数据支撑
    """

    def __init__(self):
        self.field_mapping = {}
        self.fields()

    def main(self):
        task_start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        try:
            payload = {"api_key": Config.SaaS_Tasks_APP_ID,
                       "entry_id": Config.Commission_form_ID}
            abnormal_service = api_instance.entry_data_list(payload)
            abnormal_list = abnormal_service.get("data")
            delete_id_list = []

            # 先获取提成数据，确保变量可用
            data_commission = common_module.get_commission_details()

            try:
                for i in range(0, len(abnormal_list)):  # 删除历史数据
                    delete_id_list.append(abnormal_list[i]['_id'])
                delete_payload = {"api_key": Config.SaaS_Tasks_APP_ID,
                                  "entry_id": Config.Commission_form_ID,
                                  "data_ids": delete_id_list}
                api_instance.entry_data_batch_delete(delete_payload)
            except Exception as e:
                error_task_logger.error(f"小六提成数据支撑任务执行出错：{str(e)}")
                common_module.send_task_error(task_start_time, "小六提成数据支撑", str(e))
                return

            try:
                # 生成包含所有行转换后的字典列表
                data_commission_list = [self.row_to_dict(row, self.field_mapping)
                                        for index, row in data_commission.iterrows()]
                data_commission_payload = {
                    'api_key': Config.SaaS_Tasks_APP_ID,
                    'entry_id': Config.Commission_form_ID,
                    "data_list": data_commission_list
                }

                api_instance.entry_data_batch_create(data_commission_payload)
                common_module.send_task_status(task_start_time, "小六提成数据支撑")
            except Exception as e:
                error_task_logger.error(f"小六提成数据支撑任务执行出错：{str(e)}")
                common_module.send_task_error(task_start_time, "小六提成数据支撑", str(e))

        except Exception as e:
            error_task_logger.error(f"小六提成数据支撑任务执行出错：{str(e)}")
            common_module.send_task_error(task_start_time, "小六提成数据支撑", str(e))

    @staticmethod
    def row_to_dict(row, field_mapping):
        """将一行数据转换为指定格式的字典"""
        result = {}
        for col_name, widget_id in field_mapping.items():
            if col_name in row:
                value = row[col_name]
                clean_value = None if pd.isna(value) else value
                result[widget_id] = {"value": clean_value}
        return result

    def fields(self):
        self.field_mapping = {
            "门店id": "_widget_1742884710674",
            "提成类型_二级分类": "_widget_1742884710675",
            "提成基数（本月）": "_widget_1742884710676",
            "提成基数（上月）": "_widget_1742884710677",
            "公司id": "_widget_1748930441629",
            "门店编码": "_widget_1748931089356",
            "门店名称": "_widget_1748931089357"
        }


if __name__ == '__main__':
    start = importCommissionData()
    start.main()