/* eslint-disable prefer-template */
/* eslint-disable react/jsx-boolean-value */
import React, { useState, useEffect } from 'react';
import { Form, Modal, Input, notification, Button, message, Upload, Select, Col, Row } from 'antd';
import {
  AddIntegratedloginSetting,
  GetIntegratedloginSetting,
} from '@/services/integratedLogin/api';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';
import { get, PUBLISH_SERVICE } from '@/services';
import PreviewModal from './PreviewModal';
const { Item } = Form;
const { Option } = Select;
const colorList = [
  {
    key: '科技蓝',
    color: '#2262B2',
    // headerColor: 'linear-gradient(0deg, #0066D6 0%, #39A9FF 100%)',
  },
  {
    key: '环保绿',
    color: '#00A295',
    // headerColor: 'linear-gradient(0deg, #00845D 0%, #02BF87 100%)',
  },
  // {
  //   key: '科技蓝',
  //   color: '#1890FF',
  //   // headerColor: 'linear-gradient(0deg, #0066D6 0%, #39A9FF 100%)',
  // },
  // {
  //   key: '环保绿',
  //   color: '#00B496',
  //   // headerColor: 'linear-gradient(0deg, #00845D 0%, #02BF87 100%)',
  // },
];

const Master = props => {
  const { callBackSubmit = () => {}, visible, onCancel, type } = props;
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [imgBed, setImgBed] = useState();
  const [imageUrl, setImageUrl] = useState();
  const [im, setIm] = useState();
  const [previewModal, setPreviewModal] = useState(false);
  const [keepImgeUrl, setKeepImgeUrl] = useState('');

  useEffect(() => {
    if (visible) {
      GetIntegratedloginSetting().then(res => {
        if (res.code === 0) {
          console.log(res.data);
          let aa = res.data.title.split('<br/>');
          form.setFieldsValue({
            logo: res.data.logo,
            primaryColor: res.data.primaryColor,
            // subtitle: res.data.subtitle,
            title: aa[0],
            titlebr: aa[1],
          });
          setImageUrl(window.location.origin + `/${res.data.logo}`);
          setIm(res.data.logo);
        } else {
          form.setFieldsValue({
            primaryColor: '#1890FF',
          });
        }
      });
    } else {
      setImageUrl('');
      setIm('');
      setKeepImgeUrl('');
      form.resetFields();
    }
  }, [visible]);

  // 提交
  const onSubmit = () => {
    let obj = form.getFieldsValue();
    console.log(obj);
    form.validateFields().then(validate => {
      if (obj.logo.file) {
        obj.logo = obj.logo.file.response.data;
      }
      if (obj.titlebr) {
        obj.title = `${obj.title}<br/>${obj.titlebr}`;
      }
      if (validate) {
        AddIntegratedloginSetting({
          logo: obj.logo,
          primaryColor: obj.primaryColor,
          // subtitle: obj.subtitle,
          title: obj.title,
        })
          .then(res => {
            if (res.code === 0) {
              onCancel();
              callBackSubmit();
              notification.success({
                message: '提示',
                duration: 3,
                description: res.msg || '操作成功',
              });
            } else {
              notification.error({
                message: '提示',
                duration: 3,
                description: res.msg || '操作失败',
              });
            }
          })
          .catch(err => {
            console.log(err);
          });
      }
    });
  };

  const layout = {
    layout: 'horizontal',
    labelCol: { span: 4 },
    wrapperCol: { span: 18 },
  };

  const beforeUpload = file => {
    const isJpgOrPng =
      file.type === 'image/jpeg' ||
      file.type === 'image/png' ||
      file.type === 'image/jpg' ||
      file.type === 'image/gif';
    if (!isJpgOrPng) {
      message.error('只能上传格式为jpeg/png/gif的图片!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片必须小于2MB!');
    }
    return isJpgOrPng && isLt2M;
  };

  const handleChange = info => {
    setKeepImgeUrl('');
    setIm('');
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }

    if (info.file.status === 'done') {
      getBase64(info.file.originFileObj, url => {
        setLoading(false);
        setImageUrl(url);
      });
    }
  };

  const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        上传
      </div>
    </div>
  );

  const pictruePreview = () => {
    setPreviewModal(true);
  };

  const onOk = props => {
    if (props) {
      setImageUrl(window.location.origin + `/${props.path}`);
      setIm(props.path);
      setKeepImgeUrl(props.path);
      form.setFieldsValue({ logo: `${props.path}` });
    }
  };

  return (
    <Modal
      title="配置集成网站"
      style={{ top: '150px' }}
      width="700px"
      destroyOnClose
      maskClosable={false}
      cancelText="取消"
      okText="确认"
      {...props}
      onOk={() => onSubmit()}
      forceRender={true}
      getContainer={false}
    >
      <Form form={form} {...layout}>
        <Row>
          <Col span={14}>
            <Item
              labelCol={{ span: 7 }}
              label="标题"
              name="title"
              rules={[
                {
                  required: true,
                  message: '标题为必填项',
                },
              ]}
            >
              <Input placeholder="请输入标题" autoComplete="off" style={{ marginleft: '3px' }} />
            </Item>
          </Col>
          <Col span={8}>
            <Item name="titlebr">
              <Input
                placeholder="仅新主题适用"
                autoComplete="off"
                style={{ marginLeft: '20px', width: '123%' }}
              />
            </Item>
          </Col>
        </Row>
        <Item
          label="副标题"
          name="subtitle"
          rules={[
            {
              required: true,
              message: '标题为必填项',
            },
          ]}
        >
          <Input placeholder="请输入副标题" autoComplete="off" />
        </Item>
        <Row>
          <Col span={10}>
            <Item
              label="登录Logo"
              name="logo"
              style={{ height: '112px' }}
              labelCol={{ span: 10 }}
              rules={[
                {
                  required: true,
                  message: '请选择图标icon',
                },
              ]}
            >
              <Upload
                name="singleFile"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                beforeUpload={beforeUpload}
                action={`${window.location.origin}${PUBLISH_SERVICE}/UploadSingleFile`}
                onChange={handleChange}
              >
                {imageUrl ? (
                  <img
                    src={imageUrl}
                    alt="singleFile"
                    style={{
                      width: '90%',
                      backgroundColor: '#2881a1',
                    }}
                  />
                ) : (
                  uploadButton
                )}
              </Upload>
            </Item>
          </Col>
          <Col span={12}>
            <Item>
              <Button type="primary" onClick={pictruePreview} style={{ marginTop: '33px' }}>
                从图片库中选择
              </Button>
            </Item>
          </Col>
        </Row>
        <Item name="primaryColor" label="主题">
          <Select placeholder="请选择颜色" style={{ marginLeft: '3px' }}>
            {colorList.map(item => (
              <Option value={item.color} key={item.color}>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  {/* <div
                    style={{
                      height: '10px',
                      width: '10px',
                      background: item.color,
                      marginRight: '5px',
                    }}
                  /> */}
                  {`${item.key}`}
                </div>
              </Option>
            ))}
          </Select>
        </Item>
      </Form>
      <PreviewModal
        visible={previewModal}
        onCancel={() => {
          setPreviewModal(false);
        }}
        imageUrl={im}
        keepImgeUrl={keepImgeUrl}
        callBackSubmit={onOk}
        type={type}
      />
    </Modal>
  );
};
export default Master;
