import pytest
import allure
import logging
import requests
import json
import time
from dulizhan.library.BusinessKw.JoyHub.PostManage import PostManage

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')


@allure.feature("管理后台 - 岗位模块")
class TestPostManage:
    post_id = None
    token_set = False

    @classmethod
    def setup_class(cls):
        """在整个测试类开始时登录一次，所有测试用例共享token"""
        logging.info("=============================================")
        logging.info("=========== 开始登录，获取Token ============")
        logging.info("=============================================")
        
        cls.test_case = PostManage()
        username = "joytest"
        password = "Zhou1599"

        cls.test_case._clear_user_fingerprint(username)

        url = "https://joyhub-website-manager-api-test.best-envision.com/admin-api/system/auth/login-dev"
        payload = {"username": username, "password": password}
        headers = {'Content-Type': 'application/json', 'tenant-id': '126'}

        try:
            response = requests.post(url, json=payload, headers=headers, verify=False, timeout=10)
            login_response = response.json()

            if login_response and login_response.get('code') == 0:
                token = login_response.get('data', {}).get('accessToken', '')
                if token:
                    cls.test_case.set_joyhub_token(token)
                    cls.token_set = True
                    logging.info("登录成功，获取到Token: {}...".format(token[:20]))
                else:
                    logging.warning("登录成功但未获取到Token")
            else:
                logging.error("登录失败: {}".format(login_response))
        except Exception as e:
            logging.error("登录异常: {}".format(str(e)))

    def setup_method(self):
        """每个测试方法执行前检查token"""
        if not self.token_set:
            pytest.skip("Token未设置，跳过测试")

    @allure.story("验证登录接口")
    @allure.title("测试登录接口")
    def test_joyhub_login_post(self):
        """登录测试用例，验证登录接口是否正常"""
        with allure.step("1. 准备登录参数"):
            username = "joytest"
            password = "Zhou1599"
            allure.attach(f"用户名: {username}, 密码: {password}", name="登录参数", attachment_type=allure.attachment_type.TEXT)
        
        with allure.step("2. 调用登录接口"):
            url = "https://joyhub-website-manager-api-test.best-envision.com/admin-api/system/auth/login-dev"
            payload = {"username": username, "password": password}
            headers = {'Content-Type': 'application/json', 'tenant-id': '126'}
            response = requests.post(url, json=payload, headers=headers, verify=False, timeout=10)
            resp = response.json()
            allure.attach(json.dumps(resp, ensure_ascii=False, indent=2), name="登录响应", attachment_type=allure.attachment_type.JSON)
        
        with allure.step("3. 验证响应"):
            assert resp is not None, "响应为空"
            assert "code" in resp, "响应中缺少code字段"
            assert resp["code"] == 0, f"登录失败，code={resp.get('code')}"
            assert "data" in resp, "响应中缺少data字段"
            assert "accessToken" in resp["data"], "响应中缺少accessToken字段"
            logging.info("登录接口验证通过")

    @allure.story("验证获得岗位分页列表")
    @allure.title("测试获得岗位分页列表接口")
    def test_joyhub_post_page_get(self):
        """测试获得岗位分页列表接口"""
        with allure.step("1. 准备请求参数"):
            params = {"pageNo": 1, "pageSize": 10}
            allure.attach(json.dumps(params, ensure_ascii=False), name="请求参数", attachment_type=allure.attachment_type.TEXT)
        
        with allure.step("2. 调用接口"):
            resp = self.test_case.kw_joyhub_post_page_get(**params)
            allure.attach(json.dumps(resp, ensure_ascii=False, indent=2), name="响应数据", attachment_type=allure.attachment_type.JSON)
        
        with allure.step("3. 验证响应"):
            assert resp is not None, "响应为空"
            assert "code" in resp, "响应中缺少code字段"
            assert resp["code"] == 0, f"请求失败，code={resp.get('code')}"
            assert "data" in resp, "响应中缺少data字段"
            assert "list" in resp["data"], "响应中缺少list字段"
            assert isinstance(resp["data"]["list"], list), "list字段不是数组类型"
            logging.info("获得岗位分页列表接口验证通过")

    @allure.story("验证创建岗位")
    @allure.title("测试创建岗位接口")
    def test_joyhub_post_create_post(self):
        """测试创建岗位接口"""
        with allure.step("1. 准备请求参数"):
            timestamp = int(time.time())
            params = {
                "name": f"测试岗位_{timestamp}",
                "code": f"test_post_{timestamp}",
                "sort": timestamp,
                "status": 1,
                "remark": "测试岗位备注"
            }
            allure.attach(json.dumps(params, ensure_ascii=False), name="请求参数", attachment_type=allure.attachment_type.TEXT)
        
        with allure.step("2. 调用接口"):
            resp = self.test_case.kw_joyhub_post_create_post(**params)
            allure.attach(json.dumps(resp, ensure_ascii=False, indent=2), name="响应数据", attachment_type=allure.attachment_type.JSON)
        
        with allure.step("3. 验证响应"):
            assert resp is not None, "响应为空"
            assert "code" in resp, "响应中缺少code字段"
            assert resp["code"] == 0, f"请求失败，code={resp.get('code')}"
            assert "data" in resp, "响应中缺少data字段"
            assert isinstance(resp["data"], int), "data字段不是整数类型"
            TestPostManage.post_id = resp["data"]
            logging.info(f"创建岗位成功，岗位ID: {TestPostManage.post_id}")

    @allure.story("验证获得岗位信息")
    @allure.title("测试获得岗位信息接口")
    def test_joyhub_post_get_get(self):
        """测试获得岗位信息接口"""
        if not TestPostManage.post_id:
            pytest.skip("没有可用的岗位ID，跳过测试")
        
        with allure.step("1. 准备请求参数"):
            params = {"id": TestPostManage.post_id}
            allure.attach(json.dumps(params, ensure_ascii=False), name="请求参数", attachment_type=allure.attachment_type.TEXT)
        
        with allure.step("2. 调用接口"):
            resp = self.test_case.kw_joyhub_post_get_get(post_id=TestPostManage.post_id)
            allure.attach(json.dumps(resp, ensure_ascii=False, indent=2), name="响应数据", attachment_type=allure.attachment_type.JSON)
        
        with allure.step("3. 验证响应"):
            assert resp is not None, "响应为空"
            assert "code" in resp, "响应中缺少code字段"
            assert resp["code"] == 0, f"请求失败，code={resp.get('code')}"
            assert "data" in resp, "响应中缺少data字段"
            assert "id" in resp["data"], "响应中缺少id字段"
            assert resp["data"]["id"] == TestPostManage.post_id, "返回的岗位ID与请求不一致"
            logging.info("获得岗位信息接口验证通过")

    @allure.story("验证修改岗位")
    @allure.title("测试修改岗位接口")
    def test_joyhub_post_update_put(self):
        """测试修改岗位接口"""
        with allure.step("1. 先创建一个测试岗位"):
            timestamp = int(time.time())
            create_resp = self.test_case.kw_joyhub_post_create_post(
                name=f"修改测试岗位_{timestamp}",
                code=f"update_test_post_{timestamp}",
                sort=888,
                status=1
            )
            post_id = create_resp.get("data") if create_resp and create_resp.get("code") == 0 else None
            
            if not post_id:
                pytest.skip("创建测试岗位失败，跳过修改测试")
            
            allure.attach(json.dumps({"id": post_id}, ensure_ascii=False), name="待修改岗位ID", attachment_type=allure.attachment_type.TEXT)
        
        with allure.step("2. 准备修改参数"):
            params = {
                "post_id": post_id,
                "name": f"测试岗位_修改_{timestamp}",
                "code": f"test_post_updated_{timestamp}",
                "sort": 200,
                "status": 1,
                "remark": "修改后的备注"
            }
            allure.attach(json.dumps(params, ensure_ascii=False), name="请求参数", attachment_type=allure.attachment_type.TEXT)
        
        with allure.step("3. 调用修改接口"):
            resp = self.test_case.kw_joyhub_post_update_put(**params)
            allure.attach(json.dumps(resp, ensure_ascii=False, indent=2), name="响应数据", attachment_type=allure.attachment_type.JSON)
        
        with allure.step("4. 验证响应"):
            assert resp is not None, "响应为空"
            assert "code" in resp, "响应中缺少code字段"
            assert resp["code"] == 0, f"请求失败，code={resp.get('code')}"
            assert "data" in resp, "响应中缺少data字段"
            assert resp["data"] is True, "修改岗位失败"
            logging.info("修改岗位接口验证通过")

    @allure.story("验证删除岗位")
    @allure.title("测试删除岗位接口")
    def test_joyhub_post_delete_post(self):
        """测试删除岗位接口"""
        with allure.step("1. 先创建一个测试岗位"):
            timestamp = int(time.time())
            create_resp = self.test_case.kw_joyhub_post_create_post(
                name=f"删除测试岗位_{timestamp}",
                code=f"delete_test_post_{timestamp}",
                sort=999,
                status=1
            )
            post_id = create_resp.get("data") if create_resp and create_resp.get("code") == 0 else None
            
            if not post_id:
                pytest.skip("创建测试岗位失败，跳过删除测试")
            
            allure.attach(json.dumps({"id": post_id}, ensure_ascii=False), name="待删除岗位ID", attachment_type=allure.attachment_type.TEXT)
        
        with allure.step("2. 调用删除接口"):
            resp = self.test_case.kw_joyhub_post_delete_post(post_id=post_id)
            allure.attach(json.dumps(resp, ensure_ascii=False, indent=2), name="响应数据", attachment_type=allure.attachment_type.JSON)
        
        with allure.step("3. 验证响应"):
            assert resp is not None, "响应为空"
            assert "code" in resp, "响应中缺少code字段"
            # 错误码1002005004表示岗位被引用，允许这种情况通过
            if resp["code"] == 1002005004:
                logging.warning(f"岗位已被引用无法删除，code={resp.get('code')}，msg={resp.get('msg')}")
                pytest.skip("岗位已被其他数据引用，跳过删除测试")
            assert resp["code"] == 0, f"请求失败，code={resp.get('code')}"
            assert "data" in resp, "响应中缺少data字段"
            assert resp["data"] is True, "删除岗位失败"
            logging.info("删除岗位接口验证通过")

    @allure.story("验证批量删除岗位")
    @allure.title("测试批量删除岗位接口")
    def test_joyhub_post_delete_list_post(self):
        """测试批量删除岗位接口"""
        with allure.step("1. 先创建两个测试岗位"):
            timestamp = int(time.time())
            resp1 = self.test_case.kw_joyhub_post_create_post(
                name=f"批量删除测试岗位1_{timestamp}",
                code=f"batch_delete_test_1_{timestamp}",
                sort=300,
                status=1
            )
            resp2 = self.test_case.kw_joyhub_post_create_post(
                name=f"批量删除测试岗位2_{timestamp}",
                code=f"batch_delete_test_2_{timestamp}",
                sort=301,
                status=1
            )
            
            post_id_1 = resp1.get("data") if resp1 and resp1.get("code") == 0 else None
            post_id_2 = resp2.get("data") if resp2 and resp2.get("code") == 0 else None
            
            if not post_id_1 or not post_id_2:
                pytest.skip("创建测试岗位失败，跳过批量删除测试")
            
            ids = [post_id_1, post_id_2]
            allure.attach(json.dumps({"ids": ids}, ensure_ascii=False), name="待删除岗位ID", attachment_type=allure.attachment_type.TEXT)
        
        with allure.step("2. 调用批量删除接口"):
            resp = self.test_case.kw_joyhub_post_delete_list_post(ids=ids)
            allure.attach(json.dumps(resp, ensure_ascii=False, indent=2), name="响应数据", attachment_type=allure.attachment_type.JSON)
        
        with allure.step("3. 验证响应"):
            assert resp is not None, "响应为空"
            assert "code" in resp, "响应中缺少code字段"
            # 错误码1002005004表示岗位被引用，允许这种情况通过
            if resp["code"] == 1002005004:
                logging.warning(f"岗位已被引用无法删除，code={resp.get('code')}，msg={resp.get('msg')}")
                pytest.skip("岗位已被其他数据引用，跳过批量删除测试")
            assert resp["code"] == 0, f"请求失败，code={resp.get('code')}"
            assert "data" in resp, "响应中缺少data字段"
            assert resp["data"] is True, "批量删除岗位失败"
            logging.info("批量删除岗位接口验证通过")

    @allure.story("验证获取岗位全列表")
    @allure.title("测试获取岗位全列表接口")
    def test_joyhub_post_list_all_simple_get(self):
        """测试获取岗位全列表接口"""
        with allure.step("1. 调用接口"):
            resp = self.test_case.kw_joyhub_post_list_all_simple_get()
            allure.attach(json.dumps(resp, ensure_ascii=False, indent=2), name="响应数据", attachment_type=allure.attachment_type.JSON)
        
        with allure.step("2. 验证响应"):
            assert resp is not None, "响应为空"
            assert "code" in resp, "响应中缺少code字段"
            assert resp["code"] == 0, f"请求失败，code={resp.get('code')}"
            assert "data" in resp, "响应中缺少data字段"
            assert isinstance(resp["data"], list), "data字段不是数组类型"
            logging.info("获取岗位全列表接口验证通过")

    @allure.story("验证获取岗位精简列表")
    @allure.title("测试获取岗位精简列表接口")
    def test_joyhub_post_simple_list_get(self):
        """测试获取岗位精简列表接口"""
        with allure.step("1. 调用接口"):
            resp = self.test_case.kw_joyhub_post_simple_list_get()
            allure.attach(json.dumps(resp, ensure_ascii=False, indent=2), name="响应数据", attachment_type=allure.attachment_type.JSON)
        
        with allure.step("2. 验证响应"):
            assert resp is not None, "响应为空"
            assert "code" in resp, "响应中缺少code字段"
            assert resp["code"] == 0, f"请求失败，code={resp.get('code')}"
            assert "data" in resp, "响应中缺少data字段"
            assert isinstance(resp["data"], list), "data字段不是数组类型"
            logging.info("获取岗位精简列表接口验证通过")
