// ViewReviewPage.tsx
import React, { useState, useEffect } from 'react';
import ResultModal from './components/ResultModal';
import ViewModal from './components/ViewModal';
import { refreshDictCache } from '@/servers/api/login';
import { encryptWithRsa } from '@/utils/encryptWithRsa';

const ViewReviewPage: React.FC = () => {
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [modalRecord, setModalRecord] = useState<{ id: string } | null>(null);
  const [type, setType] = useState<string>(''); // 空串即可

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const base64 = params.get('code');
    if (!base64) return;

    try {
      // 解码
      const decodedStr = atob(base64);
      const p2 = new URLSearchParams(decodedStr);

      const id = p2.get('id') ?? '';
      const code = p2.get('code') ?? '';
      const userId = p2.get('userId') ?? '';

      if (!id) return;

      setType(code); // code 现在一定是 string

      // 初始化字典
      if (!sessionStorage.getItem('dict')) {
        refreshDictCache().then((res) => {
          if (res?.code === 200) {
            sessionStorage.setItem('dict', JSON.stringify(res.data));
          }
        });
      }

      // 只有在 userId 存在时再加密保存
      if (userId) {
        sessionStorage.setItem('userId', encryptWithRsa(userId));
      }

      setModalRecord({ id });
      setModalVisible(true);
    } catch (err) {
      // atob 或者 URLSearchParams 解析失败
      console.error('解析 code 失败：', err);
    }
  }, []);

  /**
   * SUPPLIER_ACCESS_APPROVAL("supplierAccessApproval", "供应商准入审批"),
   * SUPPLIER_CATEGORY_ACCESS_APPROVAL("supplierCategoryAccessApproval", "供应商品类准入审批"),
   * SUPPLIER_INFO_CHANGE_APPROVAL("supplierInfoChangeApproval", "供应商信息变更审批"),
   * BLACKLIST_APPROVAL("blacklistApproval", "黑名单审批"),
   * EXIT_APPROVAL("exitApproval", "退出审批"),
   * CATEGORY_LIBRARY_APPROVAL("categoryLibraryApproval", "品类库审批"),
   * CATEGORY_LIBRARY_SUPPLIER_APPROVAL("categoryLibrarySupplierApproval","品类库供应商入库审批"),
   * EVALUATION_APPROVAL("evaluationApproval", "评价审批");
   */

  return (
    <div style={{ padding: '20px' }}>
      {/* 供应商准入审批, 供应商品类准入审批 */}
      {['supplierAccessApproval', 'supplierCategoryAccessApproval'].includes(type) && (
        <>
          <ViewModal
            visible={modalVisible}
            record={modalRecord ?? undefined}
            onCancel={() => setModalVisible(false)}
          />
          <ResultModal
            visible={modalVisible}
            record={modalRecord ?? undefined}
            onCancel={() => setModalVisible(false)}
          />
        </>
      )}
    </div>
  );
};

export default ViewReviewPage;
