# -*- coding:utf-8 -*-
"""
Author: qiaoxinjiu
Email: qiaoxinjiu@sparkedu.com
Create Date: 2022/08/20 5:58 下午
"""
import logging
import os
import sys

# 添加项目根目录到 Python 路径，以便导入 base_framework 模块
current_file_path = os.path.abspath(__file__)
project_root = os.path.abspath(os.path.join(os.path.dirname(current_file_path), '../../../../'))
if project_root not in sys.path:
    sys.path.insert(0, project_root)

from base_framework.public_tools import log
from base_framework.public_tools.my_faker import MyFaker
from base_framework.public_tools.runner import Runner
from base_framework.public_tools.pgsqlhelper import PgSqlHelper
from base_framework.public_tools import read_config
from base_framework.public_tools import utils
from base_framework.public_tools import mg_keyword
from zhyy.library.ZZYY_interface import ZhyyInterface

obj_get_log = log.get_logger()
obj_my_faker = MyFaker()
obj_runner = Runner()
obj_pgsql_helper = PgSqlHelper()
obj_get_way = utils.Tools()
obj_mg_keyword = mg_keyword.ManageKeyWord()


class PurchaseIndex(ZhyyInterface):
    def __init__(self):
        '''
        这个是针对于读取配置文件的初始化函数，用于读取默认参数
        '''
        super().__init__()
        self.config_index_path = os.path.dirname(os.path.abspath(__file__))
        self.config_index_filePath = os.path.join(self.config_index_path, "purchase.ini")
        self.config_index_content = read_config.ReadConfig(filename=self.config_index_filePath)

    def kw_zhyy_get_todo(self, note, user):
        """
            | 功能说明： |  返回采购工作台首页待办任务的PO与在办任务PO |
            | 输入参数： | note | 注释 |
                        |user | 用户信息，传入 'purchase' 默认读取配置文件里面  'purchase' 对应的默认账号信息|
            | 返回参数： |  {"success":true,"message":"success","code":200,"data":
            {'todoTask':['PO260116003','PO260115010'],'inProcessTask':['PO260116003','PO260115010']}} |  |
            | 作者信息： |  谯新久     |  修改时间  | 2022-8-20 |
        """
        logging.info("==========={0}===========".format(note))
        get_todo_info = self.kw_in_zhyy_purchase_todo_get(user=user)
        if get_todo_info['code'] != 0:
            raise Exception("查询采购待办任务失败: {}".format(get_todo_info))
        get_todo_info["message"] = "查询采购待办任务成功"
        data = get_todo_info.get("data")
        if data is None:
            raise Exception("返回数据为空，data字段不存在")
        list_get_todo_task = data.get("todoTask") or []
        list_get_process_task = data.get("inProcessTask") or []
        list_todo_task_po = []
        list_process_task_po = []
        for todoTask in list_get_todo_task:
            if isinstance(todoTask, dict):
                list_todo_task_po.append(todoTask.get("businessSn"))
        for processTask in list_get_process_task:
            if isinstance(processTask, dict):
                list_process_task_po.append(processTask.get("businessSn"))
        get_todo_info["data"]["todoTask"] = list_todo_task_po
        get_todo_info["data"]["inProcessTask"] = list_process_task_po
        if list_todo_task_po:
            test_purchase = list_todo_task_po[0]
            # 表在public schema中，使用public.erp_purchase_order格式
            sql = "SELECT * FROM public.erp_purchase_order WHERE order_sn = '{}'".format(test_purchase)
            try:
                obj_pgsql_helper.select_one(sql)
            except Exception as e:
                # 如果查询失败，记录日志但不影响主流程
                obj_get_log.warning("查询采购订单表失败，订单号：{}，错误：{}".format(test_purchase, str(e)))
        return get_todo_info


if __name__ == '__main__':
    test = PurchaseIndex()
    a = test.kw_zhyy_get_todo(user='purchase',note="测试")
    print(a)
