import { getAccessToken } from '@/access';
import {
  addModelsVersionDetail,
  deleteModelVersion,
  getModelById,
  getModelVersionIdList,
  getModelVersionsById,
} from '@/services/dataset/index.js';
import { downLoadZip } from '@/utils/downloadfile';
import { DeleteOutlined, 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(),
              models_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('');
  const [versionList, setVersionList] = useState([]);
  const locationParams = useParams(); //新版本获取路由参数接口
  console.log(locationParams);
  const [wordList, setWordList] = useState([]);
  const getModelByDetail = () => {
    getModelById(locationParams.id).then((ret) => {
      console.log(ret);
      if (ret.code == 200) {
        setDatasetDetailObj(ret.data);
      }
    });
  };
  const getModelVersionsList = () => {
    getModelVersionsById(locationParams.id).then((ret) => {
      console.log(ret);
      if (ret.code == 200 && ret.data && ret.data.length > 0) {
        setVersionList(
          ret.data.map((item) => {
            return {
              label: item,
              value: item,
            };
          }),
        );
      }
    });
  };
  useEffect(() => {
    getModelByDetail();
    getModelVersionsList();
    return () => {};
  }, []);
  const showModal = () => {
    form.resetFields();
    form.setFieldsValue({ name: datasetDetailObj.name });

    setDialogTitle('创建新版本');
    setIsModalOpen(true);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const deleteDataset = () => {
    Modal.confirm({
      title: '删除',
      content: '确定删除模型版本？',
      okText: '确认',
      cancelText: '取消',

      onOk: () => {
        deleteModelVersion({ models_id: locationParams.id, version }).then((ret) => {
          if (ret.code == 200) {
            message.success('删除成功');
            getModelVersions({ version, models_id: locationParams.id });
          } else {
            message.error(ret.msg);
          }
        });
      },
    });
  };
  const onFinish = () => {
    addModelsVersionDetail(formList).then((ret) => {
      console.log(ret);
      getModelVersionsList();
      setIsModalOpen(false);
    });
  };
  const getModelVersions = (params) => {
    getModelVersionIdList(params).then((ret) => {
      console.log(ret);
      if (ret.code == 200) {
        setWordList(ret.data);
      }
    });
  };
  const handleExport = async () => {
    const hide = message.loading('正在下载');
    hide();
    downLoadZip(`/api/mmp/models/downloadAllFiles`, { models_id: locationParams.id, version });
  };
  const downloadAlone = (e, record) => {
    console.log(record);
    const hide = message.loading('正在下载');
    hide();
    downLoadZip(`/api/mmp/models/download_model/${record.id}`);
  };
  const handleChange = (value) => {
    console.log(value);
    if (value) {
      getModelVersions({ version: value, models_id: locationParams.id });
      setVersion(value);
    } else {
      setVersion(null);
    }
  };
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  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>,
    },
  ];
  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 defaultActiveKey="1">
          <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
                    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"
                    className={Styles.plusButton}
                    disabled={!version}
                    style={{ margin: '0 20px 0 0' }}
                    onClick={handleExport}
                    icon={<UploadOutlined style={{ color: '#1664ff' }} />}
                  >
                    下载
                  </Button>
                </div>
              </div>
              <Table columns={columns} dataSource={wordList} pagination={false} />
            </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: 'Please input your username!',
                //   },
              ]
            }
          >
            <Input disabled placeholder="请输入数据集名称" />
          </Form.Item>
          <Form.Item label="模型版本" name="version">
            <Input placeholder="请输入数据集版本" />
          </Form.Item>
          <Form.Item label="模型文件" name="dataset_version_vos">
            <Upload {...props}>
              <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;
