<?php

namespace app\controller\api\v1;

use app\service\DataIsolation;
use app\service\MssqlQuery;
use app\model\ApiLog;
use think\facade\Log;
use think\Request;

class Chuku
{
    /**
     * 销售数据拉取接口
     */
    public function index(Request $request)
    {
        $startTime = microtime(true);

        $authContext = $request->authContext;
        $permission = $authContext['permission'];

        // 1. 数据隔离
        try {
            $supplierName = $request->param('supplier_name', '');
            $isolation = DataIsolation::buildIsolationClause($permission, 'chuku', $supplierName);
        } catch (\Exception $e) {
            $durationMs = (int)((microtime(true) - $startTime) * 1000);
            $logEntry = new ApiLog();
            $logEntry->api_key_id = $authContext['api_key_id'];
            $logEntry->client_id = $authContext['client_id'];
            $logEntry->endpoint = '/api/v1/chuku';
            $logEntry->request_params = $request->param();
            $logEntry->response_code = 403;
            $logEntry->response_body = ['code' => 403, 'msg' => $e->getMessage()];
            $logEntry->record_count = 0;
            $logEntry->duration_ms = $durationMs;
            $logEntry->ip_address = $request->ip();
            $logEntry->error_message = substr($e->getMessage(), 0, 500);
            $logEntry->save();

            return json([
                'code' => 403,
                'msg' => $e->getMessage()
            ], 403);
        }

        // 2. 获取请求参数
        $startDate = $request->param('start_date');
        $endDate = $request->param('end_date');
        $page = (int)$request->param('page', 1);
        $limit = min((int)$request->param('limit', 50), env('rate_limit.max_page_size', 500));

        // 3. 查询数据
        $errorMsg = null;
        $sqlQuery = '';
        try {
            $result = MssqlQuery::queryChuku(
                $startDate,
                $endDate,
                $page,
                $limit,
                $isolation['sql'],
                $isolation['params']
            );

            $records = $result['records'];
            $total = $result['total'];
            $sqlQuery = $result['sql'];
        } catch (\Exception $e) {
            Log::error('销售查询失败: ' . $e->getMessage());
            $errorMsg = $e->getMessage();
            $durationMs = (int)((microtime(true) - $startTime) * 1000);
            $logEntry = new ApiLog();
            $logEntry->api_key_id = $authContext['api_key_id'];
            $logEntry->client_id = $authContext['client_id'];
            $logEntry->endpoint = '/api/v1/chuku';
            $logEntry->request_params = [
                'start_date' => $startDate,
                'end_date' => $endDate,
                'supplier_name' => $supplierName,
                'page' => $page,
                'limit' => $limit,
            ];
            $logEntry->response_code = 500;
            $logEntry->response_body = ['code' => 500, 'msg' => '数据查询失败: ' . $e->getMessage()];
            $logEntry->record_count = 0;
            $logEntry->sql_query = $sqlQuery;
            $logEntry->duration_ms = $durationMs;
            $logEntry->ip_address = $request->ip();
            $logEntry->error_message = substr($e->getMessage(), 0, 500);
            $logEntry->save();

            return json([
                'code' => 500,
                'msg' => '数据查询失败: ' . $e->getMessage()
            ], 500);
        }

        // 4. 记录日志
        $durationMs = (int)((microtime(true) - $startTime) * 1000);

        $logEntry = new ApiLog();
        $logEntry->api_key_id = $authContext['api_key_id'];
        $logEntry->client_id = $authContext['client_id'];
        $logEntry->endpoint = '/api/v1/chuku';
        $logEntry->request_params = [
            'start_date' => $startDate,
            'end_date' => $endDate,
            'supplier_name' => $supplierName,
            'page' => $page,
            'limit' => $limit,
        ];
        $logEntry->response_code = 200;
        $logEntry->response_body = [
            'total' => $total,
            'count' => count($records)
        ];
        $logEntry->record_count = count($records);
        $logEntry->sql_query = $sqlQuery;
        $logEntry->duration_ms = $durationMs;
        $logEntry->ip_address = $request->ip();
        $logEntry->error_message = $errorMsg ? substr($errorMsg, 0, 500) : null;
        $logEntry->save();

        return json([
            'code' => 200,
            'msg' => 'success',
            'total' => $total,
            'data' => $records
        ]);
    }
}