import React, { useState, useEffect } from 'react';
import { Form, Modal, Input, Select, notification, Slider, InputNumber, Row, Col, Image, Radio, Button } from 'antd';
import styles from '../dimensionsConfig.less'
import thumbnail_1 from '@/assets/images/thumbnail/thumbnail_1.jpg';
import thumbnail_2 from '@/assets/images/thumbnail/thumbnail_2.jpg';
import thumbnail_3 from '@/assets/images/thumbnail/thumbnail_3.jpg';
import thumbnail_4 from '@/assets/images/thumbnail/thumbnail_4.jpg';
import {
  AddBaseMap, EditBaseMap
} from '@/services/webConfig/api';
import { number } from 'prop-types';
const { Item } = Form;
const { Option } = Select;
const AddModal = props => {
  const { callBackSubmit = () => { }, type, formObj, visible, baseMap } = props;
  const [loading, setLoading] = useState(false);
  const [radio, setRadio] = useState();
  const [alpha, setAlpha] = useState(1);
  const [mapType, setMapType] = useState(0);
  const [form] = Form.useForm();
  const arr = ['assets/images/thumbnail/thumbnail_1.jpg', 'assets/images/thumbnail/thumbnail_2.jpg', 'assets/images/thumbnail/thumbnail_3.jpg', 'assets/images/thumbnail/thumbnail_4.jpg']

  // 提交
  const onSubmit = () => {
    form.validateFields().then(validate => {
      if (validate) {
        let str = type === 'add' ? AddBaseMap : EditBaseMap
        let obj = form.getFieldsValue();
        let arr = {
          name: obj.name,
          type: obj.type,
          opacity: Number(alpha),
          icon: obj.icon,
          url: obj.url
        }
        str(arr)
          .then(res => {
            setLoading(false);
            if (res.msg === "Ok" || res.msg === "") {
              form.resetFields();
              callBackSubmit();
              notification.success({
                message: '提示',
                duration: 3,
                description: res.message || type == 'add' ? '新增成功' : '编辑成功'
              });
            } else {
              notification.error({
                message: '提示',
                duration: 3,
                description: res.message || type == 'add' ? '新增失败' : '编辑失败'
              });
            }
          })
          .catch(err => { setLoading(false); });
      }
    });
  };


  const onFinish = value => { };
  useEffect(() => {
    switch (type) {
      case 'add':
        setRadio('')
        setAlpha(1)
        form.resetFields();
        form.setFieldsValue({
          name: baseMap[0],
          type: servicenameToType(baseMap[0])
        })

        break;
      case 'edit':
        form.setFieldsValue({ ...formObj });
        setAlpha(formObj.opacity)
        let index = formObj.icon.lastIndexOf("/")
        let str = formObj.icon.substring(index + 1, formObj.icon.length);
        let flag = ''
        let defaultIndex = arr.filter((item, index1) => {
          if (item.indexOf(str) !== -1) {
            flag = index1
          }
        });
        setRadio(arr[flag])
        break;
      default:
        break;
    }
    // if (form.getFieldsValue('').servicename && baseMap.indexOf(form.getFieldsValue('').servicename) == 2 || baseMap.indexOf(form.getFieldsValue('').servicename) == 3) {
    //   setMapType(1)
    // }
    // else {
    //   setMapType(0)
    // }
  }, [visible]);


  const layout = {
    layout: 'horizontal',
    labelCol: {
      span: 4,
    },
    wrapperCol: {
      span: 16,
    },
  };
  const onChange = (value) => {
    let silderData = value == 100 ? 1 : (value / 100).toFixed(1)
    setAlpha(silderData)
  }
  const tipFormatter = (value) => {
    return (value / 100).toFixed(1)
  }

  const imgURL = [
    {
      url: thumbnail_1
    },
    {
      url: thumbnail_2
    },
    {
      url: thumbnail_3
    },
    {
      url: thumbnail_4
    },
  ]

  const radioChange = (e) => {
    setRadio(e.target.value)
  }
  const handleChange = (value) => {
    form.setFieldsValue({
      type: servicenameToType(value)
    })
    // if (baseMap.indexOf(value) == 2 || baseMap.indexOf(value) == 3) {
    //   setMapType(1)
    // }
    // else {
    //   setMapType(0)
    // }
  }
  //添加地图类型
  const servicenameToType = (servicename) => {
    // if (servicename.indexOf('地形图') > -1)
    //   servicename = '地形图'
    // if (servicename.indexOf('自定义底图') > -1)
    //   servicename = '自定义底图'
    switch (servicename) {
      case "高德街道":
        return 'amap-v';
      case "高德影像":
        return 'amap-i';
      case "天地图街道":
        return 'tianditu-v';
      case "天地图影像":
        return 'tianditu-i';
      case "百度街道":
        return 'baiduMapStreet';
      case "百度影像":
        return 'baiduMapImage';
      case "mapBox地图" :
        return 'mapBoxImage';
      case "arcgis地图" :
        return "arcgisImage"
      default:
        return 'amap-v';
    }
  }
  //选择坐标系
  const handleCoordinate = () => { }
  //选择图层
  const handleLayer = () => { }
  //选择工作空间
  const handleWorkSpance = () => { }

  return (
    <Modal
      title={`${type === 'add' ? '添加' : '编辑'}底图`}
      bodyStyle={{ width: '100%', minHeight: '100px' }}
      style={{ top: '150px' }}
      width="700px"
      destroyOnClose
      maskClosable={false}
      cancelText="取消"
      okText="确认"
      {...props}
      onOk={() => onSubmit()}
      confirmLoading={loading}
      forceRender={true}
      getContainer={false}
    >
      {visible && (
        <Form form={form} {...layout} onFinish={onFinish}>
          <Item
            label="名称"
            name="name"
            rules={[{ required: true, message: '请选择服务名' }]}
          >
            <Select onChange={handleChange}>
              {type === 'add' ? baseMap.map((item, index) => { return <Option value={item} key={index}>{item}</Option> }) : ''}
            </Select>
          </Item>
          <Item
            label="类型"
            name="type"
          >
            <Input placeholder="请输入类型" allowClear disabled />
          </Item>
          <Item
            label="URL"
            name="url"
          >
            <Input placeholder="请输入URL" allowClear />
          </Item>
          <Item
            label="透明度"
          >
            <Row>
              <Col span={12}>
                <Slider
                  min={0}
                  max={100}
                  onChange={onChange}
                  step={0.1}
                  tipFormatter={tipFormatter}
                  defaultValue={type === 'add' ? 100 : formObj.opacity * 100}
                />
              </Col>
              <Col span={4}>
                <InputNumber
                  min={0}
                  max={1}
                  disabled
                  style={{ margin: '0 16px' }}
                  defaultValue={type === 'add' ? 1 : formObj.opacity}
                  value={alpha}
                  onChange={onChange}
                />
              </Col>
            </Row>
          </Item>
          <Item
            label="选择缩略图"
            name="icon"
          >
            <div className={styles.imgList}>
              {imgURL.map((item, index) => {
                return <div key={index} className={styles.imgItem}>
                  <Image
                    width={100}
                    height={63}
                    src={item.url}
                  />
                  <Radio.Group options={item} onChange={radioChange} value={radio}>
                    <Radio value={arr[index]}></Radio>
                  </Radio.Group>
                </div>
              })}
            </div>
          </Item>
          <Item
            label="缩略图"
            name="icon"
            rules={[{ required: true, message: '请选择缩略图' }]}
          >
            <Input placeholder="请输入URL" allowClear />
          </Item>
          {mapType === 1 ?
            <>
              <Item
                label="ip地址"
                name="IP"
                rules={[{ required: true, message: '请输入ip地址' }]}
              >
                <Input placeholder="请输入ip地址" allowClear />
              </Item>
              <Item
                label="geoserver名"
                name="gis"
                rules={[{ required: true, message: '请选择缩略图' }]}
              >
                <div className={styles.imgList}>
                  <Input placeholder="请输入gis服务器名" allowClear />
                  <Button style={{ marginLeft: '0.5rem' }}>选择工作空间</Button>
                </div>
              </Item>

              <Item
                label="工作空间"
                name="workSpance"
                rules={[{ required: true, message: '请选择工作空间' }]}
              >
                <Select onChange={handleWorkSpance}>

                </Select>
              </Item>
              <Item
                label="图层名"
                name="layer"
                rules={[{ required: true, message: '请选择图层名' }]}
              >
                <Select onChange={handleLayer}>

                </Select>
              </Item>
              <Item
                label="坐标系名"
                name="coordinate"
                rules={[{ required: true, message: '请选择坐标系名' }]}
              >
                <Select onChange={handleCoordinate}>

                </Select>
              </Item>

              <Item
                label="底图范围"
                name="range"
                rules={[{ required: true, message: '请选择底图范围' }]}
              >
                <Input placeholder="xmin,ymin,xmax,ymax" allowClear />
              </Item>
              <Item
                label="起始级别"
                name="initLevel"
                rules={[{ required: true, message: '请选择起始级别' }]}
              >
                <Input placeholder="最初显示级别" allowClear />
              </Item>
              <Item
                label="最大级别"
                name="maxLevel"
                rules={[{ required: true, message: '请选择最大级别' }]}
              >
                <Input placeholder="最大显示级别" allowClear />
              </Item>
              <Item
                label="代理url"
                name="proxy"
                rules={[{ required: true, message: '请选择缩略图' }]}
              >
                <Input placeholder="请输入URL" allowClear />
              </Item>
            </>
            : ''}
        </Form>
      )}
    </Modal>
  );
};
export default AddModal;