#!/usr/bin/env python3
"""
修复ERP动态API SQL模板 - 第二版
使用标准SQL WHERE条件，不依赖MyBatis动态语法
"""

import pymysql
import os

MYSQL_HOST = os.getenv('MYSQL_HOST', '192.168.120.60')
MYSQL_PORT = int(os.getenv('MYSQL_PORT', '3306'))
MYSQL_DB = os.getenv('MYSQL_DB', 'hzhub')
MYSQL_USER = os.getenv('MYSQL_USERNAME', 'root')
MYSQL_PASSWORD = os.getenv('MYSQL_PASSWORD', 'hzhub123')

print(f"连接MySQL: {MYSQL_HOST}:{MYSQL_PORT}/{MYSQL_DB}")

conn = pymysql.connect(
    host=MYSQL_HOST,
    port=MYSQL_PORT,
    database=MYSQL_DB,
    user=MYSQL_USER,
    password=MYSQL_PASSWORD,
    charset='utf8mb4'
)

cursor = conn.cursor()

# 修复后的API配置（简化SQL，不使用MyBatis条件语法）
fixed_configs = {
    1: {  # api_id = 1 (客户列表查询)
        'sql_template': '''
SELECT CLTCODE AS customerCode,
  CLTNAME AS customerName,
  COMPANY_ID AS companyCode,
  COMPANY_NAME AS companyName,
  BRAND AS brand,
  BRANDNAME AS brandName,
  LINKMAN AS contactName,
  AREAID AS salesAreaCode,
  AREANAME AS salesAreaName,
  SALESID_T AS salesPersonCode,
  SALESNAME_T AS salesPersonName,
  SALEDOCID AS saleDocCode,
  SALEDOCNAME AS saleDocName,
  CLTPRICENO AS pricePlanCode,
  CLTPRICENAME AS pricePlanName,
  CLTTYPE AS customerType,
  STREET AS address,
  TEL1 AS phone,
  EMAIL AS email,
  SDORGID AS sdOrgCode,
  SDORGNAME AS sdOrgName,
  province, city, ISSTOP AS isStop
FROM SCLTGENERAL
ORDER BY CLTCODE
        ''',
        'result_type': 'LIST',
        'support_pagination': 1,
        'api_desc': '查询客户档案列表（暂不支持筛选，后续优化）'
    },
    2: {  # api_id = 2 (客户详情查询)
        'sql_template': '''
SELECT CLTCODE AS customerCode,
  CLTNAME AS customerName,
  COMPANY_ID AS companyCode,
  COMPANY_NAME AS companyName,
  BRAND AS brand,
  BRANDNAME AS brandName,
  LINKMAN AS contactName,
  AREAID AS salesAreaCode,
  AREANAME AS salesAreaName,
  SALESID_T AS salesPersonCode,
  SALESNAME_T AS salesPersonName,
  SALEDOCID AS saleDocCode,
  SALEDOCNAME AS saleDocName,
  CLTPRICENO AS pricePlanCode,
  CLTPRICENAME AS pricePlanName,
  CLTTYPE AS customerType,
  STREET AS address,
  TEL1 AS phone,
  EMAIL AS email,
  SDORGID AS sdOrgCode,
  SDORGNAME AS sdOrgName,
  province, city, ISSTOP AS isStop
FROM SCLTGENERAL
WHERE CLTCODE = #{customerCode}
        ''',
        'result_type': 'SINGLE',
    },
    3: {  # api_id = 3 (销区列表 - OSDORG表)
        'sql_template': '''
SELECT DISTINCT ORGCODE AS salesAreaCode, ORGNAME AS salesAreaName
FROM OSDORG
WHERE ORGLEVEL = 3
  AND ORGCODE IS NOT NULL
  AND ORGNAME IS NOT NULL
  AND ISENABLE = 1
ORDER BY ORGCODE
        ''',
    },
    # api_id = 4 (品牌列表) - SQL已正确，无需修复
}

print("\n开始修复SQL模板...")

for api_id, updates in fixed_configs.items():
    print(f"\n修复API ID {api_id}:")

    if 'sql_template' in updates:
        sql_template = updates['sql_template'].strip()

        cursor.execute("""
            UPDATE erp_api_config
            SET sql_template = %s,
                update_time = NOW()
            WHERE api_id = %s
        """, (sql_template, api_id))

        print(f"  ✓ SQL模板已更新")

    if 'api_desc' in updates:
        cursor.execute("""
            UPDATE erp_api_config
            SET api_desc = %s,
                update_time = NOW()
            WHERE api_id = %s
        """, (updates['api_desc'], api_id))

        print(f"  ✓ API描述已更新")

conn.commit()

# 显示修复后的配置
print("\n验证修复结果:")
cursor.execute("""
    SELECT api_id, api_name, api_path, result_type, support_pagination
    FROM erp_api_config
    ORDER BY api_id
""")

for row in cursor.fetchall():
    api_id, name, path, result_type, pagination = row
    print(f"  [{api_id}] {name} - {path} ({result_type}, 分页={pagination})")

cursor.close()
conn.close()

print("\n✅ SQL模板修复完成！")
print("\n下一步:")
print("  1. 重启ERP服务（如果需要立即生效）")
print("  2. 测试动态API:")
print("     curl 'http://192.168.120.60:8082/erp/dynamic/v1/customer/list?pageNum=1&pageSize=10'")
print("     curl 'http://192.168.120.60:8082/erp/dynamic/v1/customer/detail?customerCode=C00001'")
print("  3. 对比旧API和动态API的结果一致性")