/* 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,
  Cascader,
} from 'antd';
import {
  AddIntegratedLogin,
  EditIntegratedLogin,
  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 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 [show, setShow] = useState(0);
  const [optionslist, setOptionsList] = useState([]);
  const [keepLength, setKeeplength] = useState('');

  const { Option } = Select;

  useEffect(() => {
    console.log(keepSystemName);
    if (visible) {
      getMap();
      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,
          mapSetting: '',
          coordinate: '',
        });
      }
    } else {
      setRadio('');
      setImageUrl('');
      setIm('');
      setKeepImgeUrl('');
      form.resetFields();
    }
  }, [visible]);

  const getMap = () => {
    GetIntegratedloginSetting().then(res => {
      if (res.data.displayMode == '地图') {
        let list = []; // 存省数据
        let listSecord = []; // 存市数据
        let aa = [];
        let fff = 0;
        res.data.mapSettings.map(i => {
          aa.push(i);
          list.push(i[0]);
          if (i[1]) {
            listSecord.push(i[1]);
          }
        });
        setKeeplength(aa);
        if (list.indexOf('100000') != -1) {
          fff = 1;
        }
        setShow(1);
        // 获取城市选择器列表
        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: '中华人民共和国',
              center: {
                pos: [11330151.428933946, 4386623.239690046],
                lat: '39.915085',
                lng: '116.3683244',
              },
            });
            console.log(result.districtList[0].districtList);
            let data = [];
            result.districtList[0].districtList.map(i => {
              let aa = `${i.center.lng},${i.center.lat}`;
              i.lastpos = aa;
              if (list.indexOf(i.adcode) != -1) {
                data.push(i);
              }
              if (i.districtList) {
                i.districtList.map(j => {
                  let bb = `${j.center.lng},${j.center.lat}`;
                  j.lastpos = bb;
                  if (list.indexOf(j.adcode) != -1) {
                    data.push(j);
                  }
                  if (j.districtList) {
                    j.districtList.map(k => {
                      let cc = `${k.center.lng},${k.center.lat}`;
                      k.lastpos = cc;
                    });
                  }
                });
              }
            });
            if (fff == 0) {
              data.map(i => {
                let aa = [];
                i.districtList.map(j => {
                  if (listSecord.indexOf(j.adcode) != -1) {
                    aa.push(j);
                    i.districtList = aa;
                  }
                });
              });
              setOptionsList(data);
            } else {
              setOptionsList(result.districtList[0].districtList);
            }

            if (type == 'edit') {
              if (pickItem.Coordinate && pickItem.Coordinate.length > 0) {
                form.setFieldsValue({
                  mapSetting: pickItem.MapSetting,
                  coordinate: pickItem.Coordinate.toString(),
                });
              }
            } else {
              form.setFieldsValue({ mapSetting: '', coordinate: '' });
            }
          });
        });
      } else {
        setShow(0);
      }
    });
  };
  // 提交
  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;
          }
          let data = [];
          if (obj.coordinate) {
            data = obj.coordinate.split(',');
          }
          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,
              mapSetting: obj.mapSetting,
              coordinate: data,
            })
              .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,
              mapSetting: obj.mapSetting,
              coordinate: data,
            })
              .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}',
    },
  ];

  const onChangeField = (value, selectedOptions) => {
    console.log(selectedOptions);
    console.log(value);
    let aa = selectedOptions[selectedOptions.length - 1].lastpos;
    form.setFieldsValue({ coordinate: aa });
  };
  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="intranetAddress"
          rules={[
            {
              validator: (rule, value) => {
                let aa = form.getFieldValue().intranetAddress;
                if (aa) {
                  let bb = aa.split('//');
                  let cc = [];
                  if (bb[1]) {
                    cc = bb[1].split(':');
                  }

                  let regEn = /^10\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])$/;
                  let regFn = /^172\.(1[6789]|2[0-9]|3[01])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])$/;
                  let regCn = /^192\.168\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])$/;
                  let ss = [];
                  let url = /^http(s)?/;
                  ss.push(regEn.test(cc[0]));
                  ss.push(regFn.test(cc[0]));
                  ss.push(regCn.test(cc[0]));
                  if (!url.test(aa)) {
                    return Promise.reject('url格式不正确');
                  } else if (ss.indexOf(true) == -1) {
                    return Promise.reject('局域网IP不正确');
                  }
                }
                return Promise.resolve();
              },
            },
          ]}
        >
          <AutoComplete placeholder="建议使用局域网IP" options={options} allowClear />
        </Item>
        <Item
          label="外网地址"
          name="internetAddress"
          rules={[
            {
              validator: (rule, value) => {
                let aa = form.getFieldValue().internetAddress;
                if (aa) {
                  let bb = aa.split('//');
                  let cc = [];
                  if (bb[1]) {
                    cc = bb[1].split(':');
                  }
                  let url = /^http(s)?/;
                  let regEn = /^10\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])$/;
                  let regFn = /^172\.(1[6789]|2[0-9]|3[01])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])$/;
                  let regCn = /^192\.168\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])$/;
                  let reg = /^(127\.0\.0\.1)|(localhost)/;
                  let ss = [];
                  ss.push(regEn.test(cc[0]));
                  ss.push(regFn.test(cc[0]));
                  ss.push(regCn.test(cc[0]));
                  ss.push(reg.test(cc[0]));
                  if (!url.test(aa)) {
                    return Promise.reject('url格式不正确');
                  } else if (ss.indexOf(true) !== -1) {
                    return Promise.reject('外网IP不正确');
                  }
                }

                return Promise.resolve();
              },
            },
          ]}
        >
          <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>
        {show == 1 ? (
          <>
            <Item
              label="地区选择"
              name="mapSetting"
              rules={[
                {
                  required: true,
                  message: '地区选择为必填项',
                },
                {
                  validator: (rule, value) => {
                    let aa = form.getFieldValue().mapSetting;
                    if (aa) {
                      let list = keepLength.find(i => i[0] == aa[0]);
                      console.log(list);
                      console.log(aa);

                      if (list) {
                        if (aa.length <= list.length) {
                          return Promise.reject('请选择下级');
                        }
                      }
                    }

                    return Promise.resolve();
                  },
                },
              ]}
            >
              <Cascader
                fieldNames={{
                  label: 'name',
                  value: 'adcode',
                  children: 'districtList',
                }}
                showSearch
                options={optionslist}
                placeholder="请选择行政区"
                changeOnSelect
                allowClear={false}
                onChange={onChangeField}
              />
            </Item>
            <Item label="经纬度" name="coordinate">
              <Input disabled />
            </Item>
          </>
        ) : (
          <></>
        )}
      </Form>
      <PreviewModal
        visible={previewModal}
        onCancel={() => {
          setPreviewModal(false);
        }}
        imageUrl={im}
        keepImgeUrl={keepImgeUrl}
        type={type}
        callBackSubmit={onOk}
      />
    </Modal>
  );
};
export default AddModal;
