import { getUrlInfo } from '@/webPublic/one_stop_public/DetailForAudit/utils';
import React from 'react';
import { getToken, setToken } from '@/webPublic/one_stop_public/utils/token';
import { getInfo } from '@/highOrderComponent/Service';
import { Divider } from 'antd';
import config from '@/config/config';
import {
  setSysConfig,
  getSysConfig as getSysConfigLocalStorage,
} from '@/webPublic/zyd_private/utils/basiclayout';
import { getOneStopConfig } from '@/webPublic/zyd_public/utils/utils';

function formatUploadFile(fileList) {
  if (!fileList || !Array.isArray(fileList)) return [];
  return JSON.stringify(
    fileList.map((i) => ({
      uid: i.uid,
      name: i.name,
      status: i.status,
      url: i.filePath || i.response.filePath,
    })),
  );
}

export const valueTypes = {
  0: {
    name: '文本',
    inputComponent: 'input',
  },
  1: {
    name: '文件',
    inputComponent: 'upload',
    formatToServer: formatUploadFile, // 新增或保存时候转换格式
    formatToEdit: (str) => {
      const fileArr = JSON.parse(str);
      if (!Array.isArray(fileArr)) return [];
      return fileArr;
    }, //  编辑时,转换成可以在表单回显的格式
    render: (val) => {
      //   在列表上的显示方式
      return JSON.parse(val)
        .map((item, i) => (
          <>
            {i > 0 && <Divider type="vertical"/>}
            <a
              target="_blank"
              rel="noopener noreferrer"
              key={item.uid}
              href={item.url && (item.url.startsWith('http') ? item.url : config.dfs + item.url)}>
              {item.name}
            </a>
          </>
        ));
    },
  },
  2: {
    name: '富文本',
    inputComponent: 'input',
  },
};

export function getSysConfig() {
  return getInfo({ pageSize: 10000 }, '/WebConfigApi/getPage?oauthPub=true')
    .then((res) => {
      if (res && res.rows && res.rows.length) {
        const formattered = res.rows.reduce((acc, cur) => {
          let index = cur.valueType || '0';
          const { formatToEdit } = valueTypes[index];
          let { value } = cur;
          if (formatToEdit && typeof formatToEdit === 'function') {
            value = formatToEdit(value);
          }
          return {
            ...acc,
            [cur.dictCode]: value,
          };
        }, {});
        setSysConfig(formattered);
        return formattered;
      }
    });
}
export default async function setTokenAndInitSystem() {
  let token = getUrlInfo().token;
  if (token && token.length > 10 && getToken() !== token) {
    return new Promise((resolve, reject) => {
      resolve(Promise.all([setToken(token), getSysConfig(), getOneStopConfig()]));
    });
  }
  return new Promise((resolve, reject) => {
    resolve(true);
  });

}