# -*- coding: utf-8 -*-
import pandas as pd
import datetime
from config import Config
from api import API
import pymysql  # 使用 pymysql 替代 mysql.connector
from back_ground_module import CommonModule
from log_config import configure_task_logger, configure_error_task_logger

# 获取已经配置好的常规日志记录器
logger = configure_task_logger()
error_task_logger = configure_error_task_logger()
start_time = datetime.datetime.now()
api_instance = API()
common_module = CommonModule()


class importSYXCXData:
    """私域小程序数据支撑"""
    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.SYXCX_form_ID,
                       }
            abnormal_service = api_instance.entry_data_list(payload)
            abnormal_list = abnormal_service.get("data")  # api请求格式，将数据封装在data字典里

            delete_id_list = []
            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.SYXCX_form_ID,
                                "data_ids": delete_id_list}
                api_instance.entry_data_batch_delete(delete_payload)
            except Exception as e:
                error_task_logger.error(f"删除私域小程序数据时出错: {e}")
                common_module.send_task_error(task_start_time, "私域小程序数据支撑", str(e))



            data_SY = common_module.get_syxcx_details()

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

            api_instance.entry_data_batch_create(data_SY)
            common_module.send_task_status(task_start_time, "私域小程序数据支撑")
        except Exception as e:
            error_task_logger.error(f"私域小程序数据支撑执行时出错: {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_1742795002375",
                                "公众号名称": "_widget_1742795002376",
                                "小程序模板类型": "_widget_1742795002377",
                                "是否开通微信商城": "_widget_1742795002378",
                                "上架商品数": "_widget_1742795002379",
                                "上架套餐卡数": "_widget_1742795002380",
                                "上架实体商品数": "_widget_1742795002381",
                                "上架项目数": "_widget_1742795002382",
                                "上架套餐数": "_widget_1742795002383",
                                "微信公众号粉丝数": "_widget_1742795002384",
                                "微信公众号绑定手机粉丝数": "_widget_1742795002385",
                                "是否开通微信小程序": "_widget_1742795002386",
                                "微信小程序绑定用户数": "_widget_1742795002387",
                                "微信小程序绑定手机用户量": "_widget_1742795002388",
                                "微信订单数": "_widget_1742795002389",
                                "微信支付订单量": "_widget_1742795002390",
                                "线下订单数": "_widget_1742795002391"
                            }


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