import { CopyOutlined } from '@ant-design/icons';
import { Input, Button, message, Divider } from 'antd';
import copy from 'copy-to-clipboard';
import { useState } from 'react';

const ColumnsTrans = () => {
  const [requestMsg, setrequestMsg] = useState('');
  const [newRequest, setnewRequest] = useState('');
  const [borderColor, setborderColor] = useState(null);

  const translateHandler = () => {
    try {
      let newString = JSON.parse(requestMsg);
      // let newString = eval('('+requestMsg+')');
      const newRequestArr = formatPrettier(newString);
      setnewRequest(newRequestArr);
      setborderColor('green');
    } catch (error) {
      message.error('“request”内容的格式不符合JSON字符串格式！');
      setborderColor('red');
    }
  };

  const formatPrettier = (jsonObj) => {
    // debugger
    // {
    //   title: '文本',
    //   key: 'text',
    //   dataIndex: 'id',
    // },
    let arr = [];
    for (let key in jsonObj) {
      if (key.toLowerCase() == 'id') continue;
      const newObj = {
        title: jsonObj[key],
        key: key,
        dataIndex: key,
      };
      arr = [...arr, newObj];
    }
    const newRequestString = JSON.stringify(arr)
      .replace(/\[/g, '[\n\t')
      .replace(/\]/g, ']')
      .replace(/\,/g, ',\n\t')
      .replace(/\{/g, '{\n\t')
      .replace(/\}\,/g, '\n\t},')
      .replace(/\}\]/g, '\n\t}\n]');
    return newRequestString;
  };

  return (
    <div>
      <Divider orientation="left">Request</Divider>
      <Input.TextArea
        name="text"
        placeholder="请输入Request内容，须符合JSON字符串格式"
        allowClear={true}
        value={requestMsg}
        autoSize={{ minRows: 10 }}
        onChange={(value) => {
          let newValue = value?.target?.value;
          setrequestMsg(newValue);
        }}
        style={{ borderColor: borderColor }}
      />
      <Button type="primary" onClick={translateHandler} style={{ margin: 6 }}>
        转换
      </Button>
      <Input.TextArea name="beautify" autoSize={{ minRows: 8, maxRows: 16 }} value={newRequest} />
      <Button
        style={{ margin: 6 }}
        onClick={() => {
          copy(newRequest);
          message.success('已成功复制到剪切板！');
        }}
      >
        复制
      </Button>
    </div>
  );
};

export default ColumnsTrans;
