/* eslint-disable no-else-return */
/* eslint-disable prefer-promise-reject-errors */
/* eslint-disable prefer-template */
/* eslint-disable react/jsx-boolean-value */
import React, { useState, useEffect } from 'react';
import {
  Form,
  Modal,
  Input,
  notification,
  Radio,
  Button,
  message,
  Upload,
  Row,
  Col,
  Image,
  Select,
  AutoComplete,
} from 'antd';
import { AddIntegratedLogin, EditIntegratedLogin } 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 AddModal = props => {
  const { callBackSubmit = () => {}, type, pickItem, visible, onCancel, keepSystemName } = props;
  const [loading, setLoading] = useState(false);
  const [radio, setRadio] = useState();
  const [flag, setFlag] = useState(1);
  const [form] = Form.useForm();
  const [imageUrl, setImageUrl] = useState();
  const [im, setIm] = useState();
  const [previewModal, setPreviewModal] = useState(false);
  const [keepImgeUrl, setKeepImgeUrl] = useState('');

  const { Option } = Select;

  useEffect(() => {
    console.log(keepSystemName);
    if (visible) {
      if (type === 'edit') {
        console.log(pickItem);
        console.log(pickItem.AccountParam[0]);
        setRadio(pickItem.target);
        form.setFieldsValue({
          accountParamKey: pickItem.AccountParamKey,
          accountParamValue: pickItem.AccountParamValue === 1 ? '熊猫ticket' : '熊猫token',
          internetAddress: pickItem.InternetAddress,
          intranetAddress: pickItem.IntranetAddress,
          systemClient: pickItem.SystemClient,
          systemName: pickItem.SystemName,
          iconUrl: pickItem.iconUrl,
          subtitle: pickItem.Subtitle,
          target: pickItem.target,
        });
        if (pickItem.iconUrl) {
          // if (
          //   pickItem.iconUrl.startsWith('CityTemp') ||
          //   pickItem.iconUrl.startsWith('civ_integratedlogin')
          // ) {
          //   setImageUrl(`http://192.168.12.116:8017/${pickItem.iconUrl}`);
          // } else {
          setImageUrl(window.location.origin + `/${pickItem.iconUrl}`);
          setIm(pickItem.iconUrl);
          // }
        } else {
          form.setFieldsValue({ iconUrl: '' });
          setImageUrl('');
          setIm('');
        }
      } else {
        setRadio(0);
        form.setFieldsValue({ accountParamValue: '熊猫ticket', target: 0 });
      }
    } else {
      setRadio('');
      setImageUrl('');
      setIm('');
      setKeepImgeUrl('');
      form.resetFields();
    }
  }, [visible]);
  // 提交
  const onSubmit = () => {
    form.validateFields().then(validate => {
      if (validate) {
        setLoading(true);
        let obj = form.getFieldsValue();
        console.log(obj);
        if (obj.internetAddress || obj.intranetAddress) {
          if (obj.accountParamValue == '熊猫ticket') {
            obj.accountParamValue = 1;
          } else if (obj.accountParamValue == '熊猫token') {
            obj.accountParamValue = 2;
          }
          let aa = { key: obj.accountParamKey, value: obj.accountParamValue };
          console.log(aa);
          let bb = [];
          bb.push(aa);
          if (obj.iconUrl.file) {
            obj.iconUrl = obj.iconUrl.file.response.data;
          }
          if (type === 'add') {
            AddIntegratedLogin({
              systemName: obj.systemName,
              subtitle: obj.subtitle,
              internetAddress: obj.internetAddress,
              intranetAddress: obj.intranetAddress,
              accountParam: bb,
              iconUrl: obj.iconUrl,
              accountType: 'Panda',
              target: obj.target,
            })
              .then(res => {
                if (res.code === 0) {
                  onCancel();
                  setLoading(false);
                  callBackSubmit();
                  notification.success({
                    message: '提示',
                    duration: 3,
                    description: res.msg || '新增成功',
                  });
                } else {
                  setLoading(false);
                  notification.error({
                    message: '提示',
                    duration: 3,
                    description: res.msg || '新增失败',
                  });
                }
              })
              .catch(err => {
                setLoading(false);
              });
          } else {
            EditIntegratedLogin({
              systemName: obj.systemName,
              subtitle: obj.subtitle,
              internetAddress: obj.internetAddress,
              intranetAddress: obj.intranetAddress,
              accountParam: bb,
              iconUrl: obj.iconUrl,
              accountType: 'Panda',
              target: obj.target,
              clients: pickItem.clients,
            })
              .then(res => {
                if (res.code === 0) {
                  onCancel();
                  setLoading(false);
                  callBackSubmit();
                  notification.success({
                    message: '提示',
                    duration: 3,
                    description: res.msg || '编辑成功',
                  });
                } else {
                  setLoading(false);
                  notification.error({
                    message: '提示',
                    duration: 3,
                    description: res.msg || '编辑失败',
                  });
                }
              })
              .catch(err => {
                setLoading(false);
              });
          }
        } else {
          notification.warning({
            message: '提示',
            duration: 3,
            description: '内网地址或外网地址必须填写一项',
          });
        }
      }
    });
  };

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

  const onChange = e => {
    console.log(e);
    setRadio(e.target.value);
  };

  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) {
      console.log(props.path);
      console.log(process.env.PROXY);
      setImageUrl(window.location.origin + `/${props.path}`);
      setIm(props.path);
      setKeepImgeUrl(props.path);
      form.setFieldsValue({ iconUrl: `${props.path}` });
    }
  };

  const inputType = value => {
    console.log(value);
    if (value) {
      form.setFieldsValue({ internetAddress: value });
    }
  };
  const options = [
    {
      value: 'http://{IP:端口}/civbase/user/noscret/?client={client}',
    },
    {
      value: 'http://{IP:端口}/web4/?client={client}',
    },
  ];
  return (
    <Modal
      title={type === 'add' ? '新增集成网站' : '编辑集成网站'}
      style={{ top: '150px' }}
      width="700px"
      destroyOnClose
      maskClosable={false}
      cancelText="取消"
      okText="确认"
      {...props}
      onOk={() => onSubmit()}
      forceRender={true}
      getContainer={false}
    >
      <Form form={form} {...layout}>
        {type === 'edit' ? (
          <Item
            label="名称"
            name="systemName"
            rules={[
              { required: true, message: '请输入名称' },
              {
                validator: (rule, value) => {
                  let aa = form.getFieldValue().systemName;
                  let regEn = /[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/im;
                  let regCn = /[·！#￥（——）：；“”‘、，|《。》？、【】[\]]/im;
                  if (keepSystemName.indexOf(aa) != -1 && pickItem.SystemName != aa) {
                    return Promise.reject('名称已存在');
                  } else if (regEn.test(aa) || regCn.test(aa)) {
                    return Promise.reject('名称不能包含特殊字符');
                  }
                  return Promise.resolve();
                },
              },
            ]}
          >
            <Input allowClear style={{ width: '100%' }} placeholder="请输入名称" />
          </Item>
        ) : (
          <Item
            label="名称"
            name="systemName"
            rules={[
              { required: true, message: '请输入名称' },
              {
                validator: (rule, value) => {
                  let aa = form.getFieldValue().systemName;
                  let regEn = /[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/im;
                  let regCn = /[·！#￥（——）：；“”‘、，|《。》？、【】[\]]/im;
                  if (keepSystemName.indexOf(aa) != -1) {
                    return Promise.reject('名称已存在');
                  } else if (regEn.test(aa) || regCn.test(aa)) {
                    return Promise.reject('名称不能包含特殊字符');
                  }
                  return Promise.resolve();
                },
              },
            ]}
          >
            <Input allowClear style={{ width: '100%' }} placeholder="请输入名称" />
          </Item>
        )}

        <Item label="副标题" name="subtitle" rules={[{ required: true, message: '请输入副标题' }]}>
          <Input allowClear placeholder="建议使用英文" />
        </Item>
        <Item label="外网地址" name="internetAddress">
          <AutoComplete placeholder="建议使用公网IP或域名" options={options} allowClear />
        </Item>
        <Item label="内网地址" name="intranetAddress">
          <AutoComplete placeholder="建议使用局域网IP" options={options} allowClear />
        </Item>
        <Row>
          <Col span={12}>
            <Item
              labelCol={{ span: 8 }}
              label="账号参数"
              name="accountParamKey"
              rules={[{ required: true, message: '请输入参数' }]}
            >
              <Input allowClear placeholder="请填写账号参数" />
            </Item>
          </Col>
          <Col span={10}>
            <Item label="账号值" labelCol={{ span: 7 }} name="accountParamValue">
              <Select placeholder="请选择值">
                <Option value="1">熊猫ticket</Option>
                <Option value="2">熊猫token</Option>
              </Select>
            </Item>
          </Col>
        </Row>
        <Item label="新标签" name="target">
          <Radio.Group onChange={onChange} value={radio}>
            <Radio value={0}>否</Radio>
            <Radio value={1}>是</Radio>
          </Radio.Group>
        </Item>
        <Row>
          <Col span={10}>
            <Item
              label="图标"
              name="iconUrl"
              style={{ height: '112px' }}
              labelCol={{ span: 10 }}
              rules={[
                {
                  required: true,
                  message: '请选择图标',
                },
              ]}
            >
              <Upload
                name="singleFile"
                listType="picture-card"
                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>
      </Form>
      <PreviewModal
        visible={previewModal}
        onCancel={() => {
          setPreviewModal(false);
        }}
        imageUrl={im}
        keepImgeUrl={keepImgeUrl}
        type={type}
        callBackSubmit={onOk}
      />
    </Modal>
  );
};
export default AddModal;
