import { getAccessToken } from '@/access';
import { addModel, getAssetIcon, getModelList } from '@/services/dataset/index.js';
import { PlusCircleOutlined, UploadOutlined } from '@ant-design/icons';
import { Button, Form, Input, Modal, Pagination, Radio, Select, Upload } from 'antd';
import moment from 'moment';
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import Styles from './index.less';
const { Search } = Input;

const leftdataList = [1, 2, 3];

const PublicData = () => {
  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);
        form.setFieldsValue({ dataset_version_vos: fileList.map((item) => item.response.data[0]) });
      }
    },
    defaultFileList: [],
  };
  const [queryFlow, setQueryFlow] = useState({
    page: 0,
    size: 10,
    name: null,
    available_range: 0,
  });
  const navgite = useNavigate();
  const [iconParams, setIconParams] = useState({
    name: null,
    page: 0,
    size: 10000,
  });
  const [activeType, setActiveType] = useState(null);
  const [activeTag, setActiveTag] = useState(null);
  const [datasetTypeList, setDatasetTypeList] = useState([]);
  const [datasetDirectionList, setDatasetDirectionList] = useState([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [datasetList, setDatasetList] = useState([]);
  const [total, setTotal] = useState(0);
  const [form] = Form.useForm();
  const [dialogTitle, setDialogTitle] = useState('新建模型');
  const getModelLists = (queryFlow) => {
    getModelList(queryFlow).then((ret) => {
      console.log(ret);
      if (ret.code == 200) {
        setDatasetList(ret.data.content);
        setTotal(ret.data.totalElements);
      }
    });
  };

  const showModal = () => {
    form.resetFields();
    setDialogTitle('新建模型');
    setIsModalOpen(true);
  };
  const getAssetIconList = (params) => {
    getAssetIcon(params).then((ret) => {
      console.log(ret);
      if (ret.code == 200 && ret.data.content && ret.data.content.length > 0) {
        setDatasetTypeList(ret.data.content.filter((item) => item.category_id == 3));
        setDatasetDirectionList(ret.data.content.filter((item) => item.category_id == 4));
      } else {
        setDatasetTypeList([]);
        setDatasetDirectionList([]);
      }
    });
  };
  const onSearch = (values) => {
    console.log(values);
    getAssetIconList({ ...iconParams, name: values });
  };
  const nameSearch = (values) => {
    console.log(values);
    getModelLists({ ...queryFlow, name: values });
  };
  const handleOk = () => {
    console.log(1111);
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const onFinish = (values) => {
    addModel(values).then((ret) => {
      console.log(ret);
      getModelLists(queryFlow);
      setIsModalOpen(false);
    });
  };

  const chooseModelType = (val, item) => {
    console.log(val, item);
    if (item.path == queryFlow.model_type) {
      setActiveType('');
      setQueryFlow({ ...queryFlow, model_type: null });
      getModelLists({ ...queryFlow, model_type: null });
    } else {
      setActiveType(item.path);
      setQueryFlow({ ...queryFlow, model_type: item.path });
      getModelLists({ ...queryFlow, model_type: item.path });
    }

    // setQueryFlow({...queryFlow,data_type:item.path},()=>{
    //   getDatasetlist()
    // })
  };
  const chooseModelTag = (val, item) => {
    if (item.path == queryFlow.model_tag) {
      setActiveTag('');
      setQueryFlow({ ...queryFlow, model_tag: null });
      getModelLists({ ...queryFlow, model_tag: null });
    } else {
      setActiveTag(item.path);
      setQueryFlow({ ...queryFlow, model_tag: item.path });
      getModelLists({ ...queryFlow, model_tag: item.path });
    }
    // setQueryFlow({...queryFlow,data_type:item.path},()=>{
    //   getDatasetlist()
    // })
  };
  const routeToIntro = (e, record) => {
    e.stopPropagation();
    console.log(record);
    navgite({ pathname: `/dataset/modelIntro/${record.id}` });
  };
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  useEffect(() => {
    getAssetIconList(iconParams);
    getModelLists(queryFlow);
    return () => {};
  }, []);
  return (
    <>
      <div className={Styles.datasetCneterBox}>
        <div className={Styles.datasetCneterLeftBox}>
          <div className={Styles.leftContentBox}>
            <Search
              placeholder="搜索"
              allowClear
              onSearch={onSearch}
              style={{
                width: 300,
                marginBottom: '15px',
              }}
            />
            <div className={Styles.itemTitle}>模型框架</div>
            <div className={Styles.itemBox}>
              {datasetTypeList && datasetTypeList.length > 0
                ? datasetTypeList.map((item) => {
                    return (
                      <div>
                        <div
                          className={[
                            Styles.messageBox,
                            item.path === activeType ? Styles.active : null,
                          ].join(' ')}
                          onClick={(e) => {
                            chooseModelType(e, item);
                          }}
                        >
                          <img
                            className={Styles.ptIcon}
                            style={{ width: '22px' }}
                            src={`/assets/images/model/${item.path}.png`}
                            alt=""
                          />
                          <img
                            className={Styles.hoverIcon}
                            style={{ width: '22px' }}
                            src={`/assets/images/model/${item.path}-hover.png`}
                            alt=""
                          />
                          <span
                            className={Styles.messageText}
                            onClick={(e) => {
                              chooseModelTag(e, item);
                            }}
                          >
                            {item.name}
                          </span>
                        </div>
                      </div>
                    );
                  })
                : ''}
            </div>
            <div className={Styles.itemTitle}>模型能力</div>
            <div className={Styles.itemBox}>
              {datasetDirectionList && datasetDirectionList.length > 0
                ? datasetDirectionList.map((item) => {
                    return (
                      <div>
                        <div
                          className={[
                            Styles.messageBox,
                            item.path === activeTag ? Styles.active : null,
                          ].join(' ')}
                          onClick={(e) => {
                            chooseModelTag(e, item);
                          }}
                        >
                          <img
                            className={Styles.ptIcon}
                            style={{ width: '22px' }}
                            src={`/assets/images/model/${item.path}.png`}
                            alt=""
                          />
                          <img
                            className={Styles.hoverIcon}
                            style={{ width: '22px' }}
                            src={`/assets/images/model/${item.path}-hover.png`}
                            alt=""
                          />
                          <span className={Styles.messageText}>{item.name}</span>
                        </div>
                      </div>
                    );
                  })
                : ''}
            </div>
          </div>
        </div>
        <div className={Styles.datasetCneterRightBox}>
          <div className={Styles.dataSource}>
            <span>数据总数：{total}个</span>
            <div>
              <Search
                placeholder="按模型名称筛选"
                allowClear
                onSearch={nameSearch}
                style={{
                  width: 300,
                }}
              />
              <Button
                type="primary"
                className={Styles.plusButton}
                onClick={showModal}
                icon={<PlusCircleOutlined style={{ color: '#1664ff' }} />}
              >
                模型注册
              </Button>
            </div>
          </div>
          <div className={Styles.dataContent}>
            {datasetList && datasetList.length > 0
              ? datasetList.map((item) => {
                  return (
                    <div className={Styles.dataItem} onClick={(e) => routeToIntro(e, item)}>
                      <div className={Styles.itemText}>{item.name}</div>
                      <div className={Styles.itemTime}>
                        <span>最近更新: {moment(item.update_time).format('YYYY-MM-DD')}</span>
                      </div>
                      <div className={Styles.itemIcon}>
                        <img
                          style={{ width: '17px', marginRight: '3px' }}
                          src={`/assets/images/upload-icon.png`}
                          alt=""
                        />
                        <span>1582</span>
                      </div>
                    </div>
                  );
                })
              : ''}
            {/* <Select.Option value="demo">Demo</Select.Option> */}
          </div>
          <Pagination size="small" total={total} showSizeChanger showQuickJumper />
        </div>
      </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 placeholder="请输入模型名称" />
          </Form.Item>

          <Form.Item
            label="模型描述"
            name="description"
            rules={
              [
                //   {
                //     required: true,
                //     message: 'Please input your username!',
                //   },
              ]
            }
          >
            <Input placeholder="请输入模型描述" />
          </Form.Item>
          <Form.Item label="可见范围" name="available_range">
            <Radio.Group>
              <Radio value="0">仅自己可见</Radio>
              <Radio value="1">工作空间可见</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            label="模型框架"
            name="model_type"
            rules={
              [
                //   {
                //     required: true,
                //     message: 'Please input your username!',
                //   },
              ]
            }
          >
            <Select allowClear placeholder="请选择模型类型" options={[]} />
          </Form.Item>
          <Form.Item
            label="模型能力"
            name="model_tag"
            rules={
              [
                //   {
                //     required: true,
                //     message: 'Please input your username!',
                //   },
              ]
            }
          >
            <Select allowClear placeholder="请选择模型标签" options={[]} />
          </Form.Item>
          <Form.Item label="模型文件" name="dataset_version_vos">
            <Upload {...props}>
              <Button icon={<UploadOutlined style={{ color: '#1664ff' }} />}>上传文件</Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};
export default PublicData;
