import { getAccessToken } from '@/access';
import clock from '@/assets/img/clock.png';
import creatByImg from '@/assets/img/creatBy.png';
import deleteIcon from '@/assets/img/delete-icon.png';
import KFIcon from '@/components/KFIcon';
import { addModel, deleteModel, getAssetIcon, getModelList } from '@/services/dataset/index.js';
import { modalConfirm } from '@/utils/ui';
import { UploadOutlined } from '@ant-design/icons';
import { Button, Form, Input, Modal, Pagination, Select, Upload, message } 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({
          models_version_vos: fileList.map((item) => {
            const data = item.response.data[0];
            return {
              file_name: data.fileName,
              file_size: data.fileSize,
              url: data.url,
            };
          }),
        });
      }
    },
    defaultFileList: [],
  };
  const [queryFlow, setQueryFlow] = useState({
    page: 0,
    size: 20,
    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 [modelTypeList, setmodelTypeList] = useState([]);
  const [modelDirectionList, setmodelDirectionList] = useState([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [datasetList, setDatasetList] = useState([]);
  const [total, setTotal] = useState(0);
  const [form] = Form.useForm();
  const [dialogTitle, setDialogTitle] = useState('新建模型');
  const [uuid, setUuid] = useState(Date.now());
  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('新建模型');
    setUuid(Date.now());
    setIsModalOpen(true);
  };
  const getAssetIconList = (params) => {
    getAssetIcon(params).then((ret) => {
      console.log(ret);
      if (ret.code == 200 && ret.data.content && ret.data.content.length > 0) {
        setmodelTypeList(ret.data.content.filter((item) => item.category_id == 3));
        setmodelDirectionList(ret.data.content.filter((item) => item.category_id == 4));
      } else {
        setmodelTypeList([]);
        setmodelDirectionList([]);
      }
    });
  };
  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) => {
    const params = {
      ...values,
      available_range: 0,
    };
    addModel(values).then((ret) => {
      console.log(ret);
      getModelLists(queryFlow);
      setIsModalOpen(false);
    });
  };

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

    // setQueryFlow({...queryFlow,data_type:item.path},()=>{
    //   getDatasetlist()
    // })
  };
  const chooseModelTag = (val, item) => {
    if (item.id == queryFlow.model_tag) {
      setActiveTag('');
      setQueryFlow({ ...queryFlow, model_tag: null });
      getModelLists({ ...queryFlow, model_tag: null });
    } else {
      setActiveTag(item.id);
      setQueryFlow({ ...queryFlow, model_tag: item.id });
      getModelLists({ ...queryFlow, model_tag: item.id });
    }
    // 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);
  };
  const onPageChange = (pageNum, pageSize) => {
    console.log(pageNum, pageSize);
    setQueryFlow({ ...queryFlow, page: pageNum - 1, size: pageSize });
    getModelLists({ ...queryFlow, page: pageNum - 1, size: pageSize });
  };
  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}>
              {modelTypeList && modelTypeList.length > 0
                ? modelTypeList.map((item) => {
                    return (
                      <div>
                        <div
                          className={[
                            Styles.messageBox,
                            item.id === 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}>
              {modelDirectionList && modelDirectionList.length > 0
                ? modelDirectionList.map((item) => {
                    return (
                      <div>
                        <div
                          className={[
                            Styles.messageBox,
                            item.id === 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="default"
                style={{ marginLeft: '20px' }}
                onClick={showModal}
                icon={<KFIcon type="icon-xinjian2" />}
              >
                模型注册
              </Button>
            </div>
          </div>
          <div className={Styles.dataContent}>
            {datasetList && datasetList.length > 0
              ? datasetList.map((item) => {
                  return (
                    <div
                      className={Styles.dataItem}
                      onClick={(e) => {
                        routeToIntro(e, item);
                      }}
                    >
                      <span className={Styles.itemText}>{item.name}</span>
                      <img
                        onClick={(e) => {
                          e.stopPropagation();
                          modalConfirm({
                            title: '确定删除该条模型实例吗？',
                            onOk: () => {
                              deleteModel(item.id).then((ret) => {
                                if (ret.code === 200) {
                                  message.success('删除成功');
                                  getModelLists(queryFlow);
                                } else {
                                  message.error(ret.msg);
                                }
                              });
                            },
                          });
                        }}
                        className={Styles.dropdown}
                        style={{ width: '17px', marginRight: '6px' }}
                        src={deleteIcon}
                        alt=""
                      />
                      {/* <Dropdown
                        className={Styles.dropdown}
                        key={item.name}
                        menu={{
                          items: [
                            {
                              label: '详情',
                              key: 'detail',
                            },
                            {
                              label: '删除',
                              key: 'delete',
                            },
                          ],
                          onClick: (e) => {
                            console.log(e);
                            if (e.key === 'detail') {
                              routeToIntro(e, item);
                            } else if (e.key === 'delete') {
                              modalConfirm({
                                title: '确定删除该条模型实例吗？',
                                onOk: () => {
                                  deleteModel(item.id).then((ret) => {
                                    if (ret.code === 200) {
                                      message.success('删除成功');
                                      getModelLists(queryFlow);
                                    } else {
                                      message.error(ret.msg);
                                    }
                                  });
                                },
                              });
                            }
                          },
                        }}
                      >
                        <div>
                          <img
                            style={{ width: '17px', marginRight: '6px' }}
                            src={moreBack}
                            alt=""
                          />
                        </div>
                      </Dropdown> */}
                      ,<div className={Styles.itemDescripition}>{item.description}</div>
                      <div className={Styles.itemTime}>
                        <img
                          style={{ width: '17px', marginRight: '6px' }}
                          src={creatByImg}
                          alt=""
                        />
                        <span>{item.create_by}</span>
                      </div>
                      <div className={Styles.itemIcon}>
                        <img style={{ width: '12px', marginRight: '5px' }} src={clock} alt="" />
                        <span>最近更新: {moment(item.update_time).format('YYYY-MM-DD')}</span>
                      </div>
                    </div>
                  );
                })
              : ''}
            {/* <Select.Option value="demo">Demo</Select.Option> */}
          </div>
          <Pagination
            total={total}
            showSizeChanger
            defaultPageSize={20}
            pageSizeOptions={[20, 40, 60, 80, 100]}
            showQuickJumper
            onChange={onPageChange}
          />
        </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: '请输入模型名称!',
              },
            ]}
          >
            <Input placeholder="请输入模型名称" showCount maxLength={64} />
          </Form.Item>

          <Form.Item
            label="模型版本"
            name="version"
            rules={
              [
                //   {
                //     required: true,
                //     message: 'Please input your username!',
                //   },
              ]
            }
          >
            <Input placeholder="请输入模型版本" />
          </Form.Item>

          <Form.Item
            label="模型描述"
            name="description"
            rules={[
              {
                required: true,
                message: '请输入模型描述!',
              },
            ]}
          >
            <Input placeholder="请输入模型描述" showCount maxLength={256} />
          </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={modelTypeList.map((item) => {
                return { value: item.id, label: item.name };
              })}
            />
          </Form.Item>
          <Form.Item
            label="模型能力"
            name="model_tag"
            rules={
              [
                //   {
                //     required: true,
                //     message: 'Please input your username!',
                //   },
              ]
            }
          >
            <Select
              allowClear
              placeholder="请选择模型标签"
              options={modelDirectionList.map((item) => {
                return { value: item.id, label: item.name };
              })}
            />
          </Form.Item>
          <Form.Item label="模型文件" name="models_version_vos">
            <Upload {...props} data={{ uuid: uuid }}>
              <Button
                style={{
                  fontSize: '14px',
                  border: '1px solid',
                  borderColor: '#1664ff',
                  background: '#fff',
                }}
                icon={<UploadOutlined style={{ color: '#1664ff', fontSize: '14px' }} />}
              >
                上传文件
              </Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};
export default PublicData;
