import React, { useCallback, useEffect, memo } from 'react';
import { Form } from '@easyv/antd';
import ConfirmModal from 'components/ConfirmModal';
import { useMousetrapPause } from 'components/easyUse';
import { Input, Select } from '@easyv/react-gui';
import { getUserCategory, setCurrent } from 'models/material-lib';
import { connect } from 'react-redux';
import styles from './FavoriteModal.less';
const { Option } = Select;

const layout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 19 }
};

function FavoriteModal({ loading, themeResource, getUserCategory, visible, confirmLoading, name, thumb, onCancel, onOk }) {
  const [form] = Form.useForm();
  const { validateFields, setFieldsValue } = form;
  const handleSubmit = useCallback(() => {
    validateFields().then((values) => {
      onOk &&
        onOk({
          ...values,
          thumb
        });
    });
  }, []);

  useMousetrapPause(visible);

  const selectLIst = themeResource.category;

  useEffect(() => {
    visible && getUserCategory();
  }, [visible]);

  useEffect(() => {
    setFieldsValue({
      userCategoryId: selectLIst.length ? selectLIst[0].id : 0,
      name
    });
  }, [selectLIst, setFieldsValue, name]);

  const SpinWrapper = useCallback(
    ({ loading }: { loading: boolean }) => {
      if (loading) {
        return <span>loading...</span>;
      }
      return (
        <Form
          {...layout}
          initialValues={{
            userCategoryId: selectLIst.length && selectLIst[0].id,
            name
          }}
          className={styles.form}
          form={form}>
          <Form.Item
            label="资源名称"
            name="name"
            rules={[
              { required: true, whitespace: true, message: '名称必填' },
              { max: 12, message: '不能超过12个字符' }
            ]}>
            <Input style={{ height: 36 }} placeholder="请输入主题名称，12字符以内" />
          </Form.Item>
          <Form.Item label="选择分组" name="userCategoryId">
            <Select>
              {selectLIst.map((d) => {
                return (
                  <Option key={d.id} value={d.id}>
                    {d.name}
                  </Option>
                );
              })}
              {/* <Option value={0}>未分组</Option> */}
            </Select>
          </Form.Item>
        </Form>
      );
    },
    [selectLIst]
  );

  return (
    <ConfirmModal
      visible={visible}
      confirmLoading={confirmLoading}
      title="收藏"
      width={410}
      theme={'black'}
      footer={true}
      okText="确定"
      wrapClassName={styles.confirmModal}
      onCancel={onCancel}
      onOk={handleSubmit}
      destroyOnClose>
      <SpinWrapper loading={loading} />
    </ConfirmModal>
  );
}
function mapStateToProps({ materialLib }) {
  const { myFavorite, loading } = materialLib;
  return {
    themeResource: myFavorite.themeResource,
    loading
  };
}
export default connect(mapStateToProps, {
  getUserCategory,
  setCurrent
})(memo(FavoriteModal));
