import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import { QuestionCircleOutlined } from '@ant-design/icons';
import message from 'components/message';
import { Form, Input, Tooltip, Select } from '@easyv/antd';
import ConfirmModal from '@/components/ConfirmModal';
import UploadThumb from '../UploadThumb';
import { getScreenDataByPathName } from '@/services/screen';
import { addTemplate } from 'models/template';
import styles from '../SortModal.less';

const formItemLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 18 },
};

function NewTemplate({ children, dispatch, categorys, onComplete }) {
  const [visible, setVisible] = useState(false);
  const [uploading, setUploading] = useState(false);

  const [form] = Form.useForm();

  const showModal = () => {
    setVisible(true);
  };

  const hideModal = () => {
    setVisible(false);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    form.validateFields().then(async (values) => {
      setUploading(true);
      const result = await dispatch(
        addTemplate({
          name: values.name,
          info: values.info,
          category: values.category,
          screenId: values.screenId,
          thumb: values.cover,
          previewThumb: values.preview,
        }),
      );

      setUploading(false);
      if (result) {
        setVisible(false);
        onComplete && onComplete();
      }
    });
  };

  return (
    <span>
      <span onClick={showModal}>{children}</span>
      <ConfirmModal
        title="新建模板"
        visible={visible}
        onCancel={hideModal}
        onClose={hideModal}
        confirmLoading={uploading}
        onOk={handleSubmit}
        footer={true}
        destroyOnClose>
        <Container form={form} categorys={categorys} />
      </ConfirmModal>
    </span>
  );
}

const Container = ({ form, categorys }) => {
  const [preview, setPreview] = useState(false);

  useEffect(() => {
    return () => {
      form.resetFields();
    };
  }, []);

  const setCoverValue = (file) => {
    form.setFieldsValue({ cover: file });
  };

  const setPreviewValue = (file) => {
    form.setFieldsValue({ preview: file });
  };

  const viewTemplate = () => {
    const screenId = form.getFieldValue('screenId');
    if (screenId) {
      let otherWin: any = window.open(`${BASENAME}/bigscreen/${screenId}`, '_blank');
      otherWin.opener = null;
    } else {
      message.error('请填写大屏ID');
    }
  };

  const validateId = (e) => {
    setPreview(false);
    if (!form.getFieldError('screenId').length && e.target.value) {
      getScreenDataByPathName({ params: { screenId: e.target.value } }).then((res) => {
        if (res) {
          setPreview(true);
        } else {
          form.setFields([{ name: 'screenId', errors: ['大屏不存在'] }]);
        }
      });
    }
  };

  return (
    <Form {...formItemLayout} form={form}>
      <Form.Item
        label="模板名称"
        name="name"
        rules={[
          { required: true, message: '模板名称必填' },
          { min: 2, message: '不得少于2位字符' },
          { max: 32, message: '不得多于32位字符' },
        ]}>
        <Input placeholder="请输入模板名称，2～32个字符" />
      </Form.Item>
      <Form.Item
        label="比例/分辨率"
        name="info"
        rules={[
          { min: 2, message: '不得少于2位字符' },
          { max: 80, message: '不得多于80位字符' },
        ]}>
        <Input.TextArea rows={4} placeholder="例如：比例:16:9/分辨率1920*1080" />
      </Form.Item>
      <Form.Item
        label="模板分类"
        name="category"
        rules={[{ required: true, message: '模板分类必填' }]}>
        <Select style={{ width: '100%' }} dropdownClassName={styles.selectDrop}>
          {categorys.map((d) => (
            <Select.Option key={d.id} value={d.id}>
              {d.name}
            </Select.Option>
          ))}
        </Select>
      </Form.Item>
      <Form.Item
        label="模板链接"
        wrapperCol={{ span: 19 }}
        name="screenId"
        rules={[
          { required: true, message: '模板ID必填' },
          { pattern: /^\d+$/, message: '请填写合法的大屏ID' },
        ]}>
        <div>
          <div style={{ width: 358, display: 'flex', alignItems: 'center' }}>
            <Input placeholder="请输入相应的大屏ID" onBlur={validateId} style={{ flex: 1 }} />
            <Tooltip title="大屏ID为对应项目编辑页面URL末尾的ID参数，输入该ID即可一键将其生成为模板。">
              <QuestionCircleOutlined
                className="whiteHover"
                style={{ fontSize: 14, color: '#2491F7', marginLeft: 8 }}
              />
            </Tooltip>
          </div>
          {preview && (
            <a className="click" onClick={viewTemplate}>
              模板效果预览
            </a>
          )}
        </div>
      </Form.Item>
      <Form.Item label="缩略图" name="cover" rules={[{ required: true, message: '缩略图必选' }]}>
        <FileWrapper>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <UploadThumb maxSize={8 * 1024 * 1024} handleImgChange={setCoverValue} />
            <span style={{ marginLeft: 12, color: '#999' }}>建议按照16:9封面比例进行上传</span>
          </div>
        </FileWrapper>
      </Form.Item>
      <Form.Item
        label="预览效果"
        name="preview"
        rules={[{ required: true, message: '预览图必选' }]}>
        <FileWrapper>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <UploadThumb maxSize={8 * 1024 * 1024} handleImgChange={setPreviewValue} />
          </div>
        </FileWrapper>
      </Form.Item>
    </Form>
  );
};

function FileWrapper({ children }) {
  return children;
}

export default connect()(NewTemplate);
