import requests
import json
import pandas as pd
from api import API
from config import Config
from log_config import configure_task_logger, configure_error_task_logger
from back_ground_module import CommonModule
from datetime import datetime

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

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

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

common_module = CommonModule()


class update_ID_form:
    """更新简道云员工ID表"""

    def __init__(self):
        self.headers = {
            'Authorization': Config.JIANDAOYUN_API_TOKEN,  # 曹伟应用api测试 app_key
            'Content-Type': 'application/json'
        }
        self.url = "https://api.jiandaoyun.com/api/v5/corp/department/user/list"
        self.payload1 = {
            "api_key": "6694d3c4fcb69ca9a111a6c4",
            "entry_id": "6769204a1902c9341340a1bc",
        }
        self.delete_payload = {
            "api_key": "6694d3c4fcb69ca9a111a6c4",
            "entry_id": "6769204a1902c9341340a1bc",
        }
        self.update_payload = {
            "api_key": "6694d3c4fcb69ca9a111a6c4",
            "entry_id": "6769204a1902c9341340a1bc",
        }

    def get_department_members(self):
        """获取部门成员及ID表"""
        try:
            payload = json.dumps({
                "dept_no": 1,
                "has_child": True
            })
            response = requests.request("POST", self.url, headers=self.headers, data=payload)
            search_department_member = response.json()
            departments_members = search_department_member.get('users')
            df1 = pd.DataFrame(departments_members)
            logger.info("部门成员及ID表已成功获取")
            return df1
        except Exception as e:
            error_task_logger.error(f"获取部门成员及ID表失败：{e}")
            task_start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            common_module.send_task_error(task_start_time, "简道云员工ID表更新", str(e))
            return None

    def get_existing_id_form(self):
        """读取现有的ID表"""
        try:
            now_ID_form = api_instance.entry_data_list(self.payload1).get('data')
            df = pd.DataFrame(now_ID_form)
            logger.info("现有的ID表已成功读取")
            return df
        except Exception as e:
            error_task_logger.error(f"读取现有的ID表失败：{e}")
            task_start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            common_module.send_task_error(task_start_time, "简道云员工ID表更新", str(e))
            return None

    def delete_existing_data(self, df):
        """批量删除现有数据"""
        try:
            all_data = []
            for index, i in df.iterrows():
                all_data.append(i["_id"])
            self.delete_payload["data_ids"] = all_data
            api_instance.entry_data_batch_delete(self.delete_payload)
            logger.info("现有数据已成功删除")
        except Exception as e:
            error_task_logger.error(f"批量删除现有数据失败：{e}")
            task_start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            common_module.send_task_error(task_start_time, "简道云员工ID表更新", str(e))

    def update_data(self, df1):
        """批量写入新数据"""
        try:
            all_data1 = []
            for index, i in df1.iterrows():
                all_data1.append({
                    "_widget_1734942794144": {"value": i["name"]},
                    "_widget_1734942794145": {"value": i["username"]},
                })
            self.update_payload["data_list"] = all_data1
            api_instance.entry_data_batch_create(self.update_payload)
            logger.info("新数据已成功写入")
        except Exception as e:
            error_task_logger.error(f"批量写入新数据失败：{e}")
            task_start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            common_module.send_task_error(task_start_time, "简道云员工ID表更新", str(e))

    def main(self):
        """主函数"""
        task_start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        try:
            logger.info("每日任务开始执行")
            df1 = self.get_department_members()
            if df1 is not None:
                df = self.get_existing_id_form()
                if df is not None:
                    self.delete_existing_data(df)
                    self.update_data(df1)
            logger.info("每日任务执行完成")
            common_module.send_task_status(task_start_time, "简道云员工ID表更新")
        except Exception as e:
            error_task_logger.error(f"简道云员工ID表更新任务执行失败：{e}")
            common_module.send_task_error(task_start_time, "简道云员工ID表更新", str(e))


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