/* 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,
  Cascader,
  Radio,
  AutoComplete,
  InputNumber,
} from 'antd';
import {
  AddIntegratedloginSetting,
  GetIntegratedloginSetting,
} from '@/services/integratedLogin/api';
import { DownLoadFiles } from '@/services/common/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('');
  const [options, setOptions] = useState([]);
  const [radio, setRadio] = useState();
  const [flag, setFlag] = useState(0);
  const [keepSettings, setKeepSettings] = useState([]);
  const [isFromLocal, setIsFromLocal] = useState(false);

  useEffect(() => {
    if (visible) {
      // 获取城市选择器列表
      window.AMap.plugin('AMap.DistrictSearch', () => {
        let districtSearch = new AMap.DistrictSearch({
          // 关键字对应的行政区级别，country表示国家
          level: 'country',
          //  显示下级行政区级数，1表示返回下一级行政区
          subdistrict: 3,
        });

        // 搜索所有省/直辖市信息
        districtSearch.search('中国', (status, result) => {
          // 查询成功时，result即为对应的行政区信息
          console.log(result, '行政区划信息');
          result.districtList[0].districtList.push({ adcode: '100000', name: '中华人民共和国' });
          console.log(result.districtList[0].districtList);
          result.districtList[0].districtList.map(i => {
            if (i.districtList) {
              i.districtList.map(j => {
                if (j.districtList) {
                  delete j.districtList;
                }
              });
            }
          });
          console.log(result.districtList[0].districtList);
          setOptions(result.districtList[0].districtList);
        });
      });
      GetIntegratedloginSetting().then(res => {
        if (res.code === 0) {
          console.log(res.data);
          let aa = res.data.title.split('<br/>');
          let bb = res.data.qrCodeConfig.split('|');
          form.setFieldsValue({
            logo: res.data.logo,
            primaryColor: res.data.primaryColor,
            displayMode: res.data.displayMode || '卡片',
            // subtitle: res.data.subtitle,
            title: aa[0],
            titlebr: aa[1],
            loginTemplate: res.data.loginTemplate,
            loadingTime: res.data.loadingTime,
            mapSettings: res.data.mapSettings,
            qrCodename: bb[0],
            qrCodeurl: bb[1],
          });
          setKeepSettings(res.data.mapSettings);
          if (res.data.displayMode == '卡片') {
            setFlag(0);
          } else {
            setFlag(1);
          }
          let data = res.data.displayMode || '卡片';
          setRadio(data);
          setImageUrl(window.location.origin + `/${res.data.logo}`);
          setIm(res.data.logo);
        } else {
          form.setFieldsValue({
            primaryColor: '#1890FF',
          });
        }
      });
    } else {
      setImageUrl('');
      setIm('');
      setKeepImgeUrl('');
      form.resetFields();
      setFlag(0);
    }
  }, [visible]);

  // 提交
  const onSubmit = () => {
    let obj = form.getFieldsValue();
    if (obj.qrCodename && !obj.qrCodeurl) {
      notification.error({
        message: '提示',
        duration: 3,
        description: '输入二维码名称，则二维码Url必填',
      });
    } else if (!obj.qrCodename && obj.qrCodeurl) {
      notification.error({
        message: '提示',
        duration: 3,
        description: '输入二维码Url，则输入二维码名称必填',
      });
    } else {
      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}`;
        }
        console.log(obj.qrCodename || obj.qrCodeurl);
        if (validate) {
          if (!obj.logo) {
            message.error('请选择登录Logo！');
            return;
          }
          if (!isFromLocal) {
            if (obj.logo.includes('CityTemp') && obj.logo.includes('图库')) {
              obj.logo = obj.logo;
            } else {
              obj.logo = 'CityTemp\\图库\\' + obj.logo;
            }
          }
          AddIntegratedloginSetting({
            logo: obj.logo,
            primaryColor: obj.primaryColor,
            subtitle: obj.subtitle,
            loginTemplate: obj.loginTemplate || 'Default',
            title: obj.title,
            displayMode: obj.displayMode,
            loadingTime: obj.loadingTime,
            mapSettings: obj.displayMode == '卡片' ? keepSettings : obj.mapSettings,
            qrCodeConfig: obj.qrCodename && obj.qrCodeurl && `${obj.qrCodename}|${obj.qrCodeurl}`,
          })
            .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);
            });
        }
      });
    }
    console.log(obj);
  };

  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 getImg = img => {
    return `/PandaOMS/OMS/FileCenter/DownLoadFiles?module=图库&filePath=${img}`;
  };

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

    if (info.file.response.code === 0) {
      setIsFromLocal(false);
      setImageUrl(getImg(info.file.response.data));
      setLoading(false);
    } else {
      message.error(info.file.response.msg);
      setImageUrl('');
      setLoading(false);
    }

    // if (info.file.status === 'done') {
    //   DownLoadFiles({ module: '图库\\第三方图标', filePath: info.file.response.data }).then(res => {
    //     let reader = new FileReader();
    //     reader.readAsDataURL(res);
    //     reader.onload = function() {
    //       setImageUrl(reader.result);
    //     };
    //   });
    // 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}` });
      setIsFromLocal(true);
    }
  };

  const onChange = e => {
    console.log(e);
    setRadio(e.target.value);
    if (e.target.value == '地图') {
      setFlag(1);
    } else {
      setFlag(0);
    }
  };

  const renderTitle = title => <span>{title}</span>;
  const renderItem = title => ({
    value: title,
    label: (
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
        }}
      >
        {title}
      </div>
    ),
  });
  const options1 = [
    {
      label: renderTitle('产品'),
      options: [renderItem('Default')],
    },
    {
      label: renderTitle('项目'),
      options: [
        renderItem('Water'),
        renderItem('蠡县'),
        renderItem('榆林全景'),
        renderItem('张掖'),
        renderItem('确山水利局'),
      ],
    },
  ];

  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>
        <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>
        <Item label="登录模板" name="loginTemplate">
          <AutoComplete placeholder="请选择登录模板" options={options1} allowClear />
        </Item>
        <Row>
          <Col span={8}>
            <Item
              label="加载时间"
              name="loadingTime"
              labelCol={{ span: 12 }}
              rules={[
                {
                  required: true,
                  message: '加载时间必填项',
                },
              ]}
            >
              <InputNumber min={0} max={5} />
            </Item>
          </Col>
          <Col span={16}>
            <Item>
              <span>秒</span>
            </Item>
          </Col>
        </Row>
        <Item label="展示方式" name="displayMode">
          <Radio.Group onChange={onChange} value={radio}>
            <Radio value="卡片">卡片</Radio>
            <Radio value="地图">地图</Radio>
          </Radio.Group>
        </Item>
        {flag == 1 ? (
          <Item
            label="地区选择"
            name="mapSettings"
            rules={[
              {
                required: true,
                message: '地区选择为必填项',
              },
            ]}
          >
            <Cascader
              fieldNames={{
                label: 'name',
                value: 'adcode',
                children: 'districtList',
              }}
              multiple
              showSearch
              options={options}
              placeholder="请选择行政区"
              changeOnSelect
              allowClear={false}
            />
          </Item>
        ) : (
          <></>
        )}
        <Row>
          <Col span={8}>
            <Item name="qrCodename" label="二维码" labelCol={{ span: 12 }}>
              <Input placeholder="请输入名称" />
            </Item>
          </Col>
          <Col span={16}>
            <Item
              labelCol={{ span: 4 }}
              name="qrCodeurl"
              label="url"
              rules={[
                {
                  validator: (rule, value) => {
                    let aa = form.getFieldValue().qrCodeurl;
                    let regEn = /^((ht|f)tps?):\/\/([\w-]+(\.[\w-]+)*\/?)+(\?([\w\-\.,@?^=%&:\/~\+#]*)+)?$/;
                    if (aa) {
                      if (regEn.test(aa) === false) {
                        return Promise.reject('url必须以http(s)://开头');
                      }
                    }

                    return Promise.resolve();
                  },
                },
              ]}
            >
              <Input placeholder="请输入二维码url" style={{ width: '95%' }} />
            </Item>
          </Col>
        </Row>
      </Form>
      <PreviewModal
        visible={previewModal}
        onCancel={() => {
          setPreviewModal(false);
        }}
        imageUrl={im}
        keepImgeUrl={keepImgeUrl}
        callBackSubmit={onOk}
        type={type}
      />
    </Modal>
  );
};
export default Master;
