from datetime import date, timedelta, datetime
import holidays
from config import Config
import pandas as pd
import pymysql  # 使用 pymysql 替代 mysql.connector
from back_ground_module import CommonModule
from log_config import configure_task_logger, configure_error_task_logger
from api import API

common_module = CommonModule()
api_instance = API()
global last_day_end_customer_service, is_customer_service_data_id, customer_service_data_id

class JCBEfficientCarPickup:
    def __init__(self):
        # 使用 pymysql 连接数据库
        self.field_mapping = {}
        self.staff_id_list = None
        self.customer_service_list = None

    def load_all_data(self):
        # 获取接车宝客服表单
        payload = {"api_key": "6717470a0b3975ef583c6df1",
                   "entry_id": "67b6f2462f9ac03b783d409a",
                   }
        customer_service = api_instance.entry_data_list(payload)
        self.customer_service_list = customer_service.get("data")  # api请求格式，将数据封装在data字典里

    def today_customer_service_list(self):
        # 获取今日接车宝派发客服顺序
        today_customer_service_list = []
        all_customer_service_list = []
        today_customer_service_start_list = []
        for row_items in self.customer_service_list:
            # print(row_items)
            customer_service_name_id = row_items.get("_widget_1740042824214", {}).get("username", {})
            customer_service_name = row_items.get("_widget_1740042824214", {}).get("name", {})
            customer_service_state = row_items.get("_widget_1740117343937", {})
            is_last_day_end = row_items.get("_widget_1740042824216", {})
            customer_service_data_id = row_items.get("_id", {})
            print(customer_service_name, customer_service_name_id, customer_service_state, is_last_day_end)
            all_customer_service_list.append(
                [customer_service_name, customer_service_name_id, customer_service_state, is_last_day_end,
                 customer_service_data_id])
            if is_last_day_end == "是":  # 判断是否是下次开始位置
                last_day_end_customer_service = customer_service_name_id
                is_customer_service_data_id = row_items.get("_id", {})

        split_index = None
        for index, row in enumerate(all_customer_service_list):
            print(row[3])
            if row[3] == "是":
                split_index = index
                print(f"找到索引 {index}")
                break

        if split_index is not None:
            # 根据索引切割列表
            first_part = all_customer_service_list[split_index:]  # 索引位置及之后的行
            second_part = all_customer_service_list[:split_index]  # 索引位置之前的行
            # 调换两个子列表的位置并重新组合
            today_customer_service_start_list = first_part + second_part
        else:
            # 如果没有找到“是”，保持原列表不变
            today_customer_service_start_list = all_customer_service_list
            pass

        for index, row in enumerate(today_customer_service_start_list):
            if row[2] == "开":
                today_customer_service_list.append(row[1])

        return today_customer_service_list, customer_service_data_id, all_customer_service_list

    def main(self):
        self.load_all_data()
        print(self.customer_service_list)
        today_customer_service_list, customer_service_data_id, all_customer_service_list = self.today_customer_service_list()

        print(today_customer_service_list)

        data_JCB = common_module.get_jcb_details()

        # 保存为CSV文件
        output_dir = "output"  # 设置输出目录

        # 创建输出目录（如果不存在）
        import os
        os.makedirs(output_dir, exist_ok=True)

        # data_JCB.to_csv(os.path.join(output_dir, 'JCB_all_data.csv'), index=False)
        self.fields()

        # 异常待办回访  近1个月开单为0客户
        # 当前日期
        current_date = datetime.now()
        current_date = current_date + timedelta(days=-1)
        current_date_str = current_date.strftime("%Y-%m-%d")
        # current_date = datetime.now()
        thirty_days_ago = current_date - timedelta(days=30)
        thirty_days_ago = thirty_days_ago.date()
        abnormal_data = []
        # df = pd.read_csv(os.path.join(output_dir, "JCB_异常待办.csv")) # 读取异常待办表
        # print(df)
        for index, row in data_JCB.iterrows():
            new_row = row.copy()
            new_row['开户日'] = datetime.strptime(new_row['开户日'], "%Y-%m-%d").date()
            if new_row['开户日'] < thirty_days_ago and row['近30天开单天数'] == 0 and row['客户状态'] == "留存":
                # print(row['账号'], row['开户日'], row['近30天开单天数'], row["客户状态"])
                row["日期"] = datetime.strptime(row['开户日'], "%Y-%m-%d").date()
                row['日期'] = row["日期"].strftime("%Y-%m-%d")
                abnormal_data.append(row)

                # 推送给客服

        abnormal_data = pd.DataFrame(abnormal_data)
        abnormal_data["表单类型"] = "异常待办"
        abnormal_data["派发日期"] = current_date_str

        abnormal_data.to_excel(os.path.join(output_dir, 'JCB_前一日异常待办.xlsx'), index=False)

        abnormal_data = [self.row_to_dict(row, self.field_mapping) for index, row in
                         abnormal_data.iterrows()]

        data = {'api_key': Config.EFFICIENT_CAR_PICKUP_APP_ID, 'entry_id': Config.EFFICIENT_CAR_PICKUP_ENTRY_ID,
                "data_list": abnormal_data}
        # result = api_instance.entry_data_batch_create(data)

    @staticmethod
    def row_to_dict(row, field_mapping):
        """将一行数据转换为指定格式的字典"""
        result = {}
        # print(field_mapping)
        for col_name, widget_id in field_mapping.items():
            # print(col_name, widget_id)
            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 = {"日期": "_widget_1739252804406", "产品名称": "_widget_1739252804397",
                              "账号": "_widget_1739258942667", "联系手机号": "_widget_1739252804407",
                              "使用时长": "_widget_1739252804409", "开户日": "_widget_1739252804396",
                              "到期日": "_widget_1739252804408", "续约日": "_widget_1739252804410",
                              "客户状态": "_widget_1739252804400", "近一周开单量": "_widget_1739252804413",
                              "近一周是否活跃": "_widget_1739252804414",
                              "G状态：近30天开单大于等于10天": "_widget_1739252804415",
                              "当月开单天数": "_widget_1739252804416", "近30天开单天数": "_widget_1739252804417",
                              "当月G天数": "_widget_1739252804418", "日分区": "_widget_1739252804419",
                              "表单类型": "_widget_1739951204545", "派发日期": "_widget_1740036367181",
                              "跟进人": "_widget_1740043340255",
                              }


if __name__ == "__main__":
    start = JCBEfficientCarPickup()
    start.main()
    # if result is not None:
    #     print(result.head())  # 打印前几行数据
