import React, { useState } from 'react';
import { connect } from 'react-redux';
import { Form, Input } from '@easyv/antd';
import ConfirmModal from 'components/ConfirmModal';
import UploadThumb from 'containers/admin-panel/components/UploadThumb';
import defaultThumb from 'images/default.png';
import { updateConstant } from 'models/tenant-constant';
import {getAssetsUrl} from 'utils/utils';

function UpdateConstantModal({
  data = {},
  children,
  updateConstant
}: {
  data: { id?: number; thumb?: string; version?: string };
  children: React.ReactNode;
  updateConstant: Function;
}) {
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [thumb, setThumb] = useState(null);

  const [form] = Form.useForm();

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

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

  const setThumbValue = (file) => {
    setThumb(file);
    form.setFieldsValue({ thumb: file });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    form.validateFields().then(async (values) => {
      setLoading(true);
      const { id } = data;

      const result = await updateConstant({ ...values, thumb, id });
      setLoading(false);

      if (result) {
        setVisible(false);
      }
    });
  };

  const thumbValue = data.thumb ? getAssetsUrl(data.thumb) : defaultThumb;

  return (
    <span>
      <span onClick={showModal}>{children}</span>
      <ConfirmModal
        title="编辑组件"
        theme="black"
        visible={visible}
        onCancel={hideModal}
        onOk={handleSubmit}
        footer={true}
        confirmLoading={loading}
        destroyOnClose>
        <Form form={form} labelCol={{ span: 4 }} wrapperCol={{ span: 19 }} initialValues={data}>
          <Form.Item
            label="组件名称"
            name="name"
            rules={[
              { required: true, message: '组件名称必填' },
              { min: 2, message: '不得少于2位字符' },
              { max: 16, message: '不得多于16位字符' }
            ]}>
            <Input placeholder="请输入组件名称，2～16个字符" autoComplete="off" />
          </Form.Item>

          <Form.Item wrapperCol={{ span: 20 }} label="组件版本" name="thumb">
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <span style={{ color: 'rgba(180, 183, 193, 1)' }}>v{data.version}</span>
            </div>
          </Form.Item>
          <Form.Item wrapperCol={{ span: 20 }} label="缩略图" name="thumb">
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <UploadThumb imgUrl={thumbValue} handleImgChange={setThumbValue} />
              <span style={{ marginLeft: 12, color: 'rgba(180, 183, 193, 1)' }}>单击图片重新上传，200KB以内100*60px图片</span>
            </div>
          </Form.Item>
        </Form>
      </ConfirmModal>
    </span>
  );
}

const mapDispatchToProps = {
  updateConstant
};

export default connect(null, mapDispatchToProps)(UpdateConstantModal);
