from api import API
from config import Config
import pandas as pd
from log_config import configure_task_logger, configure_error_task_logger
from tqdm import tqdm

# 初始化API实例
api_instance = API()

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

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


class update_member:
    def __init__(self):
        # 初始化一些必要的变量
        self.target_columns = ["_widget_1734062123102", "_widget_1734062123103", "_widget_1734062123105",
                               "_widget_1734062123204"]

    def get_ngv_data(self):
        """获取NGV数据"""
        try:
            payload1 = {"api_key": "675b900991ad2491c69389ca", "entry_id": "675bb02bd2d53c2034c665e4"}
            NGV_data_list = api_instance.entry_data_list(payload1).get("data")
            NGV_data = pd.DataFrame(NGV_data_list)
            logger.info("NGV数据已成功获取")
            return NGV_data
        except Exception as e:
            error_task_logger.error(f"获取NGV数据失败：{e}")
            return None

    def get_staff_id(self):
        """获取简道云员工id"""
        try:
            payload2 = {"api_key": "6694d3c4fcb69ca9a111a6c4", "entry_id": "6769204a1902c9341340a1bc"}
            staff_id_list = api_instance.entry_data_list(payload2).get("data")
            name_to_id = {}
            for item in staff_id_list:
                name = item.get('_widget_1734942794144')
                number = item.get('_widget_1734942794145')
                if name and number:  # 确保两个字段都存在
                    name_to_id[name] = number
            logger.info("员工id映射已生成")
            return name_to_id
        except Exception as e:
            error_task_logger.error(f"获取简道云员工id失败：{e}")
            return None

    def update_ngv_data(self, NGV_data, name_to_id):
        """更新NGV数据"""
        try:
            for col in self.target_columns:
                NGV_data[f"{col}_ID"] = NGV_data[col].map(lambda name: name_to_id.get(name, ""))
            logger.info("NGV数据已更新")
            return NGV_data
        except Exception as e:
            error_task_logger.error(f"更新NGV数据失败：{e}")
            return None

    def write_back_data(self, NGV_data):
        """写回数据"""
        try:
            for index, row in tqdm(NGV_data.iterrows()):
                data1 = {"api_key": Config.SaaS_Tasks_APP_ID,
                         "entry_id": Config.NGV_TASKS_ENTRY_ID,
                         "data_id": row['_id'],
                         "data": {"_widget_1748496855778": {"value": row["_widget_1734062123103_ID"]},  # 续约顾问
                                  "_widget_1748496855779": {"value": row["_widget_1734062123102_ID"]},  # 区域经理
                                  "_widget_1748496855780": {"value": row["_widget_1734062123105_ID"]},  # 运营负责人
                                  "_widget_1751877712235": {"value": row["_widget_1734062123204_ID"]},  # 运营专家
                                  }
                         }
                api_instance.entry_data_update(data1)
            logger.info("数据写回完成")
        except Exception as e:
            error_task_logger.error(f"数据写回失败：{e}")

    def main(self):
        """主函数"""
        logger.info("每日任务开始执行")
        NGV_data = self.get_ngv_data()
        if NGV_data is not None:
            name_to_id = self.get_staff_id()
            if name_to_id is not None:
                updated_NGV_data = self.update_ngv_data(NGV_data, name_to_id)
                if updated_NGV_data is not None:
                    self.write_back_data(updated_NGV_data)
        logger.info("每日任务执行完成")


if __name__ == '__main__':
    daily_task = update_member()
    daily_task.main()
