import { getAccessToken } from '@/access';
import {
  addDatasetVersionDetail,
  deleteDatasetVersion,
  getDatasetById,
  getDatasetVersionIdList,
  getDatasetVersionsById,
} from '@/services/dataset/index.js';
import { downLoadZip } from '@/utils/downloadfile';
import {
  DeleteOutlined,
  DownloadOutlined,
  PlusCircleOutlined,
  UploadOutlined,
} from '@ant-design/icons';
import { Button, Form, Input, Modal, Select, Table, Tabs, Upload, message } from 'antd';
import moment from 'moment';
import { useEffect, useRef, useState } from 'react';
import { useParams } from 'react-router-dom';
import Styles from './index.less';
const { Search } = Input;
const { TabPane } = Tabs;

const Dataset = () => {
  const props = {
    action: '/api/mmp/dataset/upload',
    // headers: {
    // 'X-Requested-With': null
    // },
    headers: {
      Authorization: getAccessToken(),
      'X-Requested-With': null,
    },
    onChange({ file, fileList }) {
      if (file.status !== 'uploading') {
        console.log(file, fileList);
        setFormList(
          fileList.map((item) => {
            return {
              ...form.getFieldsValue(),
              dataset_id: locationParams.id,
              file_name: item.response.data[0].fileName,
              file_size: item.response.data[0].fileSize,
              url: item.response.data[0].url,
            };
          }),
        );
      }
    },
    defaultFileList: [],
  };
  const [form] = Form.useForm();
  const [formList, setFormList] = useState([]);
  const [dialogTitle, setDialogTitle] = useState('新建版本');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [datasetDetailObj, setDatasetDetailObj] = useState({});
  const [version, setVersion] = useState(null);
  const [versionList, setVersionList] = useState([]);
  const locationParams = useParams(); //新版本获取路由参数接口
  const [wordList, setWordList] = useState([]);
  const [activeTabKey, setActiveTabKey] = useState('1');
  const [uuid, setUuid] = useState(Date.now());
  const getDatasetByDetail = () => {
    getDatasetById(locationParams.id).then((ret) => {
      console.log(ret);
      setDatasetDetailObj(ret.data);
    });
  };
  // 获取数据集版本
  const getDatasetVersionList = () => {
    getDatasetVersionsById(locationParams.id).then((ret) => {
      console.log(ret);
      if (ret && ret.data && ret.data.length > 0) {
        setVersionList(
          ret.data.map((item) => {
            return {
              label: item,
              value: item,
            };
          }),
        );
        setVersion(ret.data[0]);
        getDatasetVersions({ version: ret.data[0], dataset_id: locationParams.id });
      }
    });
  };
  useEffect(() => {
    getDatasetByDetail();
    getDatasetVersionList();
    return () => {};
  }, []);
  const showModal = () => {
    form.resetFields();
    form.setFieldsValue({ name: datasetDetailObj.name });

    setDialogTitle('创建新版本');
    setUuid(Date.now());
    setIsModalOpen(true);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const handleExport = async () => {
    const hide = message.loading('正在下载');
    hide();
    downLoadZip(`/api/mmp/dataset/downloadAllFiles`, { dataset_id: locationParams.id, version });
  };
  const deleteDataset = () => {
    Modal.confirm({
      title: '删除',
      content: '确定删除数据集版本？',
      okText: '确认',
      cancelText: '取消',

      onOk: () => {
        deleteDatasetVersion({ dataset_id: locationParams.id, version }).then((ret) => {
          getDatasetVersionList();
          message.success('删除成功');
        });
      },
    });
  };
  const onFinish = (values) => {
    addDatasetVersionDetail(formList).then((ret) => {
      getDatasetVersionList();
      setIsModalOpen(false);
      message.success('创建成功');
    });
  };
  // 获取版本下的文件列表
  const getDatasetVersions = (params) => {
    getDatasetVersionIdList(params).then((res) => {
      setWordList(res?.data?.content ?? []);
    });
  };
  const handleChange = (value) => {
    console.log(value);
    if (value) {
      getDatasetVersions({ version: value, dataset_id: locationParams.id });
      setVersion(value);
    } else {
      setVersion(null);
    }
  };
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  const downloadAlone = (e, record) => {
    console.log(record);
    const hide = message.loading('正在下载');
    hide();
    downLoadZip(`/api/mmp/dataset/download/${record.id}`);
  };
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 80,
      render(text, record, index) {
        return <span>{(pageOption.current.page - 1) * 10 + index + 1}</span>;
      },
      // render: (text, record, index) =>  `${((curPage-1)*10)+(index+1)}`,
    },
    {
      title: '文件名称',
      dataIndex: 'file_name',
      key: 'file_name',
      render: (text, record) => <a onClick={(e) => downloadAlone(e, record)}>{text}</a>,
    },
    {
      title: '版本号',
      dataIndex: 'version',
      key: 'version',
    },
    {
      title: '文件大小',
      dataIndex: 'file_size',
      key: 'file_size',
    },
    {
      title: '更新时间',
      dataIndex: 'update_time',
      key: 'update_time',
      render: (text) => <span>{moment(text).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: '操作',
      dataIndex: 'option',
      width: '100px',
      key: 'option',
      render: (_, record) => [
        <Button
          type="link"
          size="small"
          key="download"
          icon={<DownloadOutlined />}
          onClick={(e) => downloadAlone(e, record)}
        >
          下载
        </Button>,
      ],
    },
  ];
  const pageOption = useRef({ page: 1, size: 10 });

  // 当前页面切换
  const paginationChange = async (current, size) => {
    console.log('page', current, size);
    pageOption.current = {
      page: current,
      size: size,
    };
    // getList()
  };
  return (
    <div className={Styles.datasetBox}>
      <div className={Styles.datasetIntroTopBox}>
        <span style={{ color: '#1d1d20', fontSize: '20px' }}>{datasetDetailObj.name}</span>
        <div className={Styles.smallTagBox}>
          <div className={Styles.tagItem}>{datasetDetailObj.data_tag || '...'}</div>
          <div className={Styles.tagItem}>{datasetDetailObj.data_type}</div>
          {/* <div className={Styles.tagItem}>English</div> */}
        </div>
      </div>
      <div className={Styles.datasetIntroCneterBox}>
        <Tabs activeKey={activeTabKey} onChange={(key) => setActiveTabKey(key)}>
          <TabPane tab="数据集简介" key="1">
            <div className={Styles.datasetIntroTitle}>简介</div>
            <div className={Styles.datasetIntroText}>{datasetDetailObj.description}</div>
          </TabPane>
          <TabPane tab="数据集文件/版本" key="2">
            <div className={Styles.dataListBox}>
              <div>数据集文件列表</div>
              <div className={Styles.dataButtonList}>
                <div
                  style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}
                >
                  <span style={{ marginRight: '10px' }}>版本号：</span>
                  <Select
                    placeholder="请选择版本号"
                    style={{
                      width: 160,
                    }}
                    allowClear
                    value={version}
                    onChange={handleChange}
                    options={versionList}
                  />
                  <Button
                    type="primary"
                    className={Styles.plusButton}
                    onClick={showModal}
                    icon={<PlusCircleOutlined style={{ color: '#1664ff' }} />}
                  >
                    创建新版本
                  </Button>
                </div>
                <div
                  style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}
                >
                  <Button
                    type="primary"
                    className={Styles.plusButton}
                    style={{ margin: '0 20px 0 0' }}
                    onClick={deleteDataset}
                    icon={<DeleteOutlined style={{ color: '#1664ff' }} />}
                  >
                    删除
                  </Button>
                  <Button
                    type="primary"
                    disabled={!version}
                    className={Styles.plusButton}
                    style={{ margin: '0 20px 0 0' }}
                    onClick={handleExport}
                    icon={<DownloadOutlined style={{ color: '#1664ff' }} />}
                  >
                    下载
                  </Button>
                </div>
              </div>
              <div style={{ marginBottom: '10px', fontSize: '14px' }}>
                {wordList.length > 0 && wordList[0].description
                  ? '版本描述：' + wordList[0].description
                  : null}
              </div>
              <Table columns={columns} dataSource={wordList} pagination={false} rowKey="id" />
            </div>
          </TabPane>
        </Tabs>
      </div>
      <Modal
        title={
          <div style={{ display: 'flex', alignItems: 'center', fontWeight: 500 }}>
            <img
              style={{ width: '20px', marginRight: '10px' }}
              src={`/assets/images/pipeline-edit-icon.png`}
              alt=""
            />
            {dialogTitle}
          </div>
        }
        open={isModalOpen}
        className={Styles.modal}
        okButtonProps={{
          htmlType: 'submit',
          form: 'form',
        }}
        onCancel={handleCancel}
      >
        <Form
          name="form"
          form={form}
          layout="vertical"
          initialValues={{
            remember: true,
          }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="数据集名称"
            name="name"
            rules={[
              {
                required: true,
                message: '请输入数据集名称',
              },
            ]}
          >
            <Input disabled placeholder="请输入数据集名称" />
          </Form.Item>
          <Form.Item
            label="数据集版本"
            name="version"
            rules={[
              {
                required: true,
                message: '请输入数据集版本',
              },
            ]}
          >
            <Input placeholder="请输入数据集版本" maxLength={64} showCount allowClear />
          </Form.Item>
          <Form.Item
            label="版本描述"
            name="description"
            rules={[
              {
                required: true,
                message: '请输入版本描述',
              },
            ]}
          >
            <Input.TextArea
              placeholder="请输入版本描述"
              autoSize={{ minRows: 2, maxRows: 6 }}
              maxLength={256}
              showCount
              allowClear
            />
          </Form.Item>
          <Form.Item
            label="数据集文件"
            name="dataset_version_vos"
            rules={[
              {
                required: true,
                message: '请上传数据集文件',
              },
            ]}
          >
            <Upload {...props} data={{ uuid: uuid }}>
              <Button
                style={{
                  fontSize: '14px',
                  border: '1px solid',
                  borderColor: '#1664ff',
                  background: '#fff',
                }}
                icon={<UploadOutlined style={{ color: '#1664ff' }} />}
              >
                上传文件
              </Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};
export default Dataset;
