import React, { useState, useEffect } from 'react';
import { Form, Modal, Input, Select, notification, Button } from 'antd';
import {
  AddSchema,
  AddSchemaBaseMap,
  bindSchemeBaseMap,
  GetBaseMapList,
  GetVectorDataList,
} from '@/services/webConfig/api';
import MapScope from '@/components/ThreeMapScope';
const { Item } = Form;
const { Option } = Select;
const AddModal = props => {
  const { callBackSubmit = () => {}, type, formObj, visible, serviceList } = props;
  const [loading, setLoading] = useState(false);
  const [baseMap, setBaseMap] = useState([]);
  const [pipeArr, setPipeArr] = useState([]);
  const [data, setData] = useState([]);
  const [mapSettings, setMapSettings] = useState({ areaName: '选择视角' });
  const [mapScopeVisible, setMapScopeVisible] = useState(false);
  const [baseMapData, setBaseMapData] = useState([]);
  const [form] = Form.useForm();
  const baseMapList = {
    'amap-v': '高德街道',
    'amap-i': '高德影像',
    'tianditu-v': '天地图街道',
    'tianditu-i': '天地图影像',
    baiduMapStreet: '百度街道',
    baiduMapImage: '百度影像',
    mapBoxImage: 'mapBox地图',
    arcgisImage: 'arcgis地图',
  };
  const onSubmit = () => {
    form.validateFields().then(validate => {
      if (validate) {
        setLoading(true);
        let obj = form.getFieldsValue();
        if (type === 'add') {
          AddSchemaBaseMap({
            schemename: formObj.schemename,
            type: obj.serverName,
          }).then(res => {
            setLoading(false);
            if (res.msg === '') {
              form.resetFields();
              callBackSubmit();
              prompt('success', '瓦片新增成功');
            } else {
              prompt('fail', '瓦片新增失败');
            }
          });
        } else {
          handleEdit();
        }
      }
    });
  };
  const prompt = (type, content) => {
    if (type == 'success') {
      notification.success({
        message: '提示',
        duration: 3,
        description: content,
      });
    } else {
      notification.error({
        message: '提示',
        duration: 3,
        description: content,
      });
    }
  };
  const handleEdit = () => {
    let obj = form.getFieldsValue();
    AddSchema({
      schemename: obj.schemename,
      data,
      mapSettings: mapSettings.areaName === '选择视角' ? {} : mapSettings,
      baseMap: baseMapData,
    })
      .then(res => {
        setLoading(false);
        if (res.msg === '') {
          form.resetFields();
          callBackSubmit();
          prompt('success', '方案新增成功');
        } else {
          prompt('fail', res.msg);
        }
      })
      .catch(err => {
        setLoading(false);
      });
  };

  const onFinish = value => {};
  useEffect(() => {
    switch (type) {
      case 'add':
        console.log('serviceList', serviceList);
        addTile();
        break;
      case 'schemeAdd':
        pipeNetwork();
        break;
      default:
        break;
    }
  }, [visible]);

  // 添加瓦片
  const addTile = () => {
    form.setFieldsValue({
      serverName: serviceList[0],
    });
  };
  // 获取管网及默认底图
  const pipeNetwork = () => {
    form.resetFields();
    setMapSettings({ areaName: '选择视角' });
    let req1 = GetBaseMapList();
    let req2 = GetVectorDataList();
    let pipeArr = [],
      baseMap = [];
    Promise.all([req1, req2]).then(res => {
      if (res[0].msg === 'Ok') {
        setBaseMap(res[0].data);
      }
      if (res[1].msg === 'Ok') {
        (res[1].data || []).map(item => {
          pipeArr.push(item.id);
        });
      }
      setPipeArr(pipeArr);
      form.setFieldsValue({
        baseMap: res[0].data[0].name,
      });
    });
  };
  const layout = {
    layout: 'horizontal',
    labelCol: {
      span: 4,
    },
    wrapperCol: {
      span: 18,
    },
  };

  // 选择服务名
  const handleChange = value => {};
  // 选择管网
  const handleService = value => {
    setData(value);
  };

  // 选择底图
  const handleBaseMap = (value, option) => {
    let baseMapDataArr = [];
    value.map((item, index) => {
      baseMapDataArr.push({ type: item, status: index == 0 ? 'active' : 'notActive' });
    });
    setBaseMapData(baseMapDataArr);
  };
  const submitExtent = mapSettings => {
    setMapScopeVisible(false);
    if (JSON.stringify(mapSettings) != '{}') {
      setMapSettings(mapSettings);
      form.setFieldsValue({
        camera: mapSettings.areaName,
      });
    }
  };
  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}>
            {type === 'add' ? (
              <Item label="服务名" name="serverName">
                <Select onChange={handleChange}>
                  {serviceList.length
                    ? serviceList.map((item, index) => {
                        return (
                          <Option key={index} value={item}>
                            {baseMapList[item]}
                          </Option>
                        );
                      })
                    : ''}
                </Select>
              </Item>
            ) : (
              <>
                <Item
                  label="方案名"
                  name="schemename"
                  rules={[{ required: true, message: '请输入方案名' }]}
                >
                  <Input placeholder="请输入方案名" allowClear />
                </Item>
                <Item label="数据源">
                  <Select onChange={handleService} mode="multiple">
                    {pipeArr.length
                      ? pipeArr.map((item, index) => {
                          return (
                            <Option key={index} value={item}>
                              {item}
                            </Option>
                          );
                        })
                      : ''}
                  </Select>
                </Item>
                <Item label="瓦片" name="" rules={[{ required: true, message: '请选择瓦片' }]}>
                  <Select onChange={handleBaseMap} mode="multiple">
                    {baseMap.length
                      ? baseMap.map((item, index) => {
                          return (
                            <Option key={index} value={item.type}>
                              {item.name}
                            </Option>
                          );
                        })
                      : ''}
                  </Select>
                </Item>
                <Item label="视角" name="camera">
                  <Button style={{ width: '100%' }} onClick={() => setMapScopeVisible(true)}>
                    {mapSettings.areaName}
                  </Button>
                </Item>
              </>
            )}
          </Form>
        )}
      </Modal>
      <MapScope
        visible={mapScopeVisible}
        onCancel={() => setMapScopeVisible(false)}
        baseMapData={baseMapData}
        baseMap={baseMap}
        handleType="add"
        confirmModal={submitExtent}
      />
    </>
  );
};
export default AddModal;
