import React, { useState, useEffect } from 'react';
import { Form, Modal, Input, Select, notification } from 'antd';
import {
  GettMaplayer,
  GetVectorService,
  SetServiceConfig,
  bindSchemeBaseMap,
} from '@/services/webConfig/api';
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 [form] = Form.useForm();
  // 提交
  const onSubmit = () => {
    form.validateFields().then(validate => {
      if (validate) {
        setLoading(true);
        let obj = form.getFieldsValue();
        if (type === 'add') {
          bindSchemeBaseMap({
            schemename: formObj.schemename,
            basemapName: obj.serverName,
          }).then(res => {
            setLoading(false);
            if (res.code === 0) {
              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();
    let query = {
      schemename: obj.schemename,
      terminalType: 'scheme',
      isBaseMap: 'false',
      jsonCfg: JSON.stringify({
        baseMap: [obj.baseMap],
        servicename: obj.servicename,
        label: obj.label,
        url: obj.url,
        alpha: 1,
      }),
    };
    SetServiceConfig(query)
      .then(res => {
        setLoading(false);
        if (res.msg === 'Ok') {
          form.resetFields();
          callBackSubmit();
          prompt('success', '方案新增成功');
        } else {
          prompt('fail', '方案新增失败');
        }
      })
      .catch(err => {
        setLoading(false);
      });
  };

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

  // 添加瓦片
  const addTile = () => {
    form.setFieldsValue({
      serverName: serviceList[0],
    });
  };
  // 获取管网及默认底图
  const pipeNetwork = () => {
    form.resetFields();
    let req1 = GettMaplayer({ terminalType: 'base', isBaseMap: true });
    let req2 = GetVectorService();
    let pipeArr = [],
      baseMap = [];
    Promise.all([req1, req2]).then(res => {
      if (res[0].msg === 'Ok') {
        (res[0].data.general.baseMap.layers || []).map(item => {
          baseMap.push(item.servicename);
        });
      }
      if (res[1].msg === 'Ok') {
        (res[1].data.VectorList || []).map(item => {
          pipeArr.push(item.ServiceName.split('.')[0]);
        });
      }
      setPipeArr(pipeArr);
      setBaseMap(baseMap);
      form.setFieldsValue({
        baseMap: baseMap[0],
      });
    });
  };
  const layout = {
    layout: 'horizontal',
    labelCol: {
      span: 4,
    },
    wrapperCol: {
      span: 18,
    },
  };

  // 选择服务名
  const handleChange = () => {};
  // 选择管网
  const handleService = value => {
    form.setFieldsValue({
      label: value,
      url: `http://{IP}/CityInterface/rest/services/MapServer.svc/${value}`,
    });
  };

  // 选择底图
  const handleBaseMap = () => {};
  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}>
                          {item}
                        </Option>
                      );
                    })
                  : ''}
              </Select>
            </Item>
          ) : (
            <>
              <Item
                label="方案名"
                name="schemename"
                rules={[{ required: true, message: '请输入方案名' }]}
              >
                <Input placeholder="请输入方案名" allowClear />
              </Item>
              <Item label="管网" name="servicename">
                <Select onChange={handleService}>
                  {pipeArr.length
                    ? pipeArr.map((item, index) => {
                        return (
                          <Option key={index} value={item}>
                            {item}
                          </Option>
                        );
                      })
                    : ''}
                </Select>
              </Item>
              <Item label="标签" name="label">
                <Input placeholder="请输入标签" allowClear />
              </Item>
              <Item label="url" name="url">
                <Input placeholder="请输入url" allowClear />
              </Item>
              <Item
                label="默认底图"
                name="baseMap"
                rules={[{ required: true, message: '请选择底图' }]}
              >
                <Select onChange={handleBaseMap}>
                  {baseMap.length
                    ? baseMap.map((item, index) => {
                        return (
                          <Option key={index} value={item}>
                            {item}
                          </Option>
                        );
                      })
                    : ''}
                </Select>
              </Item>
            </>
          )}
        </Form>
      )}
    </Modal>
  );
};
export default AddModal;
