<template>
  <PageWrapper content-full-height content-class="flex" style="height: 100%; overflow: hidden">
    <WbSurveyRiskReport ref="registerWbSurveyRiskReport" :company-id="companyId" />
  </PageWrapper>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { defHttp } from '/@/utils/http/axios';
import { setAuthCache } from '/@/utils/auth';
import { TOKEN_KEY } from '/@/enums/cacheEnum';
import WbSurveyRiskReport from './WbSurveyRiskReport.vue';

const registerWbSurveyRiskReport = ref<InstanceType<typeof WbSurveyRiskReport> | null>(null);
const companyId = ref(1);
const isLoading = ref(false);
const errorMessage = ref('');

// 从URL获取参数
const getUrlParams = () => {
  try {
    const url = new URL(window.location.href);
    const params = new URLSearchParams(url.search);
    
    return {
      cctoken: params.get('Token') || '',
      WorkID: params.get('WorkID') || '',
    };
  } catch (error) {
    console.error('解析URL参数失败:', error);
    return { cctoken: '', WorkID: '' };
  }
};

// 获取token的函数
const fetchToken = async () => {
  isLoading.value = true;
  errorMessage.value = '';
  
  try {
    const { cctoken, WorkID } = getUrlParams();
    console.log('URL参数 - cctoken:', cctoken, 'WorkID:', WorkID);
    
    if (!cctoken || !WorkID) {
      throw new Error('缺少必要的URL参数: Token 或 WorkID');
    }
    
    const timestamp = Date.now();
    const gettokeyUrl = '/api/jflow/getCCWorkTokenAndTid';
    
    const response = await defHttp.get({
      url: gettokeyUrl,
      params: {
        targetKey: "targetKey",
        flowToken: cctoken,
        WorkID: WorkID,
        _t: timestamp
      },
    });
    
    const { tid, token } = response;
    
    if (!token) {
      throw new Error('获取到的token为空');
    }
    
    setAuthCache(TOKEN_KEY, token);
    console.log('Token设置成功');
    
  } catch (error: any) {
    console.error('获取token失败:', error);
    errorMessage.value = error.message || '获取token失败';
  } finally {
    isLoading.value = false;
  }
};

// 点击左侧列表，显示公司信息
const showSurveyReport = (data: { key: number } | null) => {
  if (data?.key) {
    companyId.value = data.key;
  }
};

// 添加类型定义（如果需要）
interface SurveyData {
  key: number;
  // 其他属性...
}

// 组件挂载时获取token
onMounted(() => {
  fetchToken();
});

// 暴露方法给父组件（如果需要）
defineExpose({
  showSurveyReport
});
</script>