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

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

function EditTemplate({
  data,
  categorys,
  children,
  dispatch,
  onComplete,
}: {
  data: any;
  categorys: any;
  children: React.ReactElement;
  dispatch: any;
  onComplete: () => void;
}) {
  const [visible, setVisible] = useState(false);
  const [preview, setPreview] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [templateChange, setTemplateChange] = useState(false);

  const [form] = Form.useForm();

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

  const hideModal = () => {
    setVisible(false);
    setTemplateChange(false);
    setPreview(false);
    setUploading(false);
  };

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

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

  const handleSubmit = (e) => {
    e.preventDefault();
    form.validateFields().then(async (values) => {
      setUploading(true);

      const body: any = { id: data.id };
      function filterEqualValues(old, latest): any {
        return Object.keys(latest).reduce((acc, key) => {
          if (latest[key] === old[key]) return acc;
          acc[key] = latest[key];
          return acc;
        }, {});
      }
      if (values.name !== data.name) body.name = values.name;

      const result = await dispatch(
        updateTemplate({
          id: data.id,
          ...filterEqualValues(data, {
            name: values.name,
            info: values.info,
            category: values.category,
            screenId: values.screenId,
            thumb: values.thumb,
            previewThumb: values.previewThumb,
          }),
        }),
      );

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

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

  const validateId = (value) => {
    setPreview(false);
    if (templateChange && value) {
      return getScreenDataByPathName({ params: { screenId: value } }).then((res) => {
        if (res) {
          setPreview(true);
          return Promise.resolve();
        } else {
          return Promise.reject('大屏不存在');
        }
      });
    }
    return Promise.resolve();
  };

  const handleChangeTemplate = () => {
    setTemplateChange((prev) => !prev);
    if (templateChange) {
      form.setFieldsValue({ screenId: undefined });
    }
  };

  return (
    <span>
      <span onClick={showModal}>{children}</span>
      <ConfirmModal
        title="编辑模板"
        visible={visible}
        onCancel={hideModal}
        confirmLoading={uploading}
        onOk={handleSubmit}
        footer={true}
        destroyOnClose>
        <Form {...formItemLayout} initialValues={data} form={form} autoComplete="off">
          <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={[
              {
                pattern: /^\d+$/,
                message: '请填写合法的大屏ID',
              },
              { validator: (_, value) => validateId(value) },
            ]}>
            <div style={{ width: 358 }}>
              <Button
                onClick={handleChangeTemplate}
                style={{
                  border: '1px solid #2491F7',
                  color: '#2491F7',
                  marginBottom: 16,
                }}>
                替换模板
              </Button>
              {templateChange && (
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <Input
                    placeholder="请输入相应的大屏ID"
                    onBlur={(e) => validateId(e.target.value)}
                    style={{ flex: 1 }}
                  />
                  <Tooltip title="大屏ID为对应项目编辑页面URL末尾的ID参数，输入该ID即可一键将其生成为模板。">
                    <QuestionCircleOutlined
                      style={{
                        fontSize: 14,
                        color: '#2491F7',
                        marginLeft: 8,
                      }}
                      className="whiteHover"
                    />
                  </Tooltip>
                </div>
              )}
              {templateChange && preview && <a onClick={viewTemplate}>模板效果预览</a>}
            </div>
            {/* <ScreenTemplate onPreview={viewTemplate} /> */}
          </Form.Item>
          <Form.Item
            {...formItemLayout}
            label="缩略图"
            name="thumb"
            rules={[{ required: true, message: '缩略图必选' }]}>
            <FileWrapper>
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <UploadThumb
                  imgUrl={getAssetsUrl(`${data.thumb}`)}
                  handleImgChange={setCoverValue}
                />
                <span style={{ marginLeft: 12, color: '#999' }}>
                  建议按16:9比例上传,大小不超过200KB
                </span>
              </div>
            </FileWrapper>
          </Form.Item>
          <Form.Item
            {...formItemLayout}
            label="预览图"
            name="previewThumb"
            rules={[{ required: true, message: '预览图必选' }]}>
            <FileWrapper>
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <UploadThumb
                  imgUrl={getAssetsUrl(`${data.previewThumb}`)}
                  handleImgChange={setPreviewValue}
                />
                <span style={{ marginLeft: 12, color: '#999' }}>大小不超过2M</span>
              </div>
            </FileWrapper>
          </Form.Item>
        </Form>
      </ConfirmModal>
    </span>
  );
}

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

function mapStateToProps({ templates }) {
  return {
    categorys: templates.categorys,
  };
}

export default connect(mapStateToProps)(EditTemplate);
