/* eslint-disable indent */
import React, { useState, useEffect } from 'react';
import { Form, Modal, Input, Select, notification, Radio } from 'antd';
import {
  GettMaplayer,
  GetVectorService,
  SetServiceConfig,
  bindSchemeBaseMap,
  GetbaseMapschemeName,
} from '@/services/webConfig/api';
const { Item } = Form;
const { Option } = Select;
const AddModal = props => {
  const {
    callBackSubmit = () => {},
    type,
    formObj,
    visible,
    serviceList,
    keepData,
    nameData,
  } = props;
  const [loading, setLoading] = useState(false);
  const [baseMap, setBaseMap] = useState([]);
  const [pipeArr, setPipeArr] = useState([]);
  const [list, setList] = useState([]);
  const [radio, setRadio] = useState('');
  const [tileSlicedData, setTileSlicedData] = 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,
        tileMaps: obj.tileMaps ? [obj.tileMaps] : [],
        label: obj.label,
        url: obj.url,
        alpha: 1,
      }),
    };
    SetServiceConfig(query)
      .then(res => {
        setLoading(false);
        if (res.code == '0') {
          form.resetFields();
          callBackSubmit();
          prompt('success', '方案新增成功');
        } else {
          prompt('fail', '方案新增失败');
        }
      })
      .catch(err => {
        setLoading(false);
      });
  };

  const onFinish = value => {};
  useEffect(() => {
    console.log(keepData);
    if (visible) {
      switch (type) {
        case 'add':
          addTile();
          break;
        case 'schemeAdd':
          pipeNetwork();
          renderTileSliced();
          setRadio('基础底图');
          form.setFieldsValue({ choose: '基础底图' });
          form.setFieldsValue({
            baseMap: keepData[0],
          });
          break;
        default:
          break;
      }
    } else {
      setRadio('');
      form.resetFields();
    }
  }, [visible]);

  // 添加瓦片
  const addTile = () => {
    console.log(formObj);
    form.setFieldsValue({
      serverName: serviceList[0],
    });
  };
  // 获取管网及默认底图
  const pipeNetwork = () => {
    form.resetFields();
    let req1 = GetbaseMapschemeName();
    let req2 = GetVectorService();
    let pipeArr = [];
    let baseMap = [];
    Promise.all([req1, req2]).then(res => {
      if (res[0].code == '0') {
        (res[0].data || []).map(item => {
          baseMap.push(item);
        });
      }
      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 renderTileSliced = () => {
    GettMaplayer({
      terminalType: 'base',
      isBaseMap: true,
    })
      .then(res => {
        if (res.code == '0') {
          let newdata = res.data.general.baseMap.layers?.filter(i => i.isVector === 1);
          setTileSlicedData(newdata);
        } else {
          notification.error({
            message: '获取失败',
            description: res.message,
          });
        }
      })
      .catch(err => {
        if (err.message.indexOf('timeout') !== -1) {
          notification.error({
            message: '提示',
            duration: 3,
            description: '请求超时',
          });
        } else {
          notification.error({
            message: '提示',
            duration: 3,
            description: err.message,
          });
        }
        setTreeLoading(false);
      });
  };
  const layout = {
    layout: 'horizontal',
    labelCol: {
      span: 4,
    },
    wrapperCol: {
      span: 18,
    },
  };

  // 选择服务名
  const handleChange = () => {};
  // 选择管网
  const handleService = value => {
    form.setFieldsValue({
      label: value,
      // url: `http://{IP}/PandaGIS/MapServer/Export?mapServerName=${value}`,
      url: `http://{IP}/PandaGIS/MapServer/${value}`,
    });
  };

  const onChange = e => {
    console.log(keepData);
    setRadio(e.target.value);
    if (e.target.value === '基础底图') {
      form.setFieldsValue({
        baseMap: keepData[0],
      });
    } else {
      form.setFieldsValue({
        baseMap: baseMap[0],
      });
    }
  };

  // 选择底图
  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
      getContainer={false}
    >
      {visible && (
        <Form form={form} {...layout} onFinish={onFinish}>
          {type === 'add' ? (
            <Item label="分级底图" name="serverName">
              <Select onChange={handleChange}>
                {serviceList.length
                  ? serviceList.map((item, index) => (
                      <Option key={index} value={item}>
                        {item}
                      </Option>
                    ))
                  : ''}
              </Select>
            </Item>
          ) : (
            <>
              <Item
                label="方案名"
                name="schemename"
                rules={[
                  { required: true, message: '请输入方案名' },
                  {
                    validator: (rule, value) => {
                      let aa = form.getFieldValue().schemename;
                      if (nameData.indexOf(aa) != -1) {
                        return Promise.reject('方案名已存在');
                      }
                      return Promise.resolve();
                    },
                  },
                ]}
              >
                <Input placeholder="请输入方案名" allowClear />
              </Item>
              <Item label="管网" name="servicename" placeholder="请选择管网">
                <Select onChange={handleService} showSearch>
                  {pipeArr.length
                    ? pipeArr.map((item, index) => (
                        <Option key={index} value={item}>
                          {item}
                        </Option>
                      ))
                    : ''}
                </Select>
              </Item>
              <Item label="切片管网" name="tileMaps" placeholder="请选择切片管网">
                <Select showSearch allowClear>
                  {tileSlicedData.length
                    ? tileSlicedData.map((item, index) => (
                        <Option key={index} value={item.servicename}>
                          {item.servicename}
                        </Option>
                      ))
                    : ''}
                </Select>
              </Item>
              <Item label="标签" name="label">
                <Input placeholder="请输入标签" allowClear />
              </Item>
              <Item label="url" name="url">
                <Input placeholder="请输入url" allowClear />
              </Item>
              <Item name="choose" style={{ marginLeft: '110px' }}>
                <Radio.Group onChange={onChange} value={radio}>
                  <Radio value="基础底图">基础底图</Radio>
                  <Radio value="分级底图">分级底图</Radio>
                </Radio.Group>
              </Item>
              {form.getFieldsValue().choose === '分级底图' ? (
                <Item
                  label="默认分级底图"
                  name="baseMap"
                  rules={[{ required: true, message: '请选择分级底图' }]}
                >
                  <Select onChange={handleBaseMap}>
                    {baseMap.length
                      ? baseMap.map((item, index) => (
                          <Option key={index} value={item}>
                            {item}
                          </Option>
                        ))
                      : ''}
                  </Select>
                </Item>
              ) : (
                <Item
                  label="默认基础底图"
                  name="baseMap"
                  rules={[{ required: true, message: '请选择基础底图' }]}
                >
                  <Select onChange={handleBaseMap}>
                    {keepData.length
                      ? keepData.map((item, index) => (
                          <Option key={index} value={item}>
                            {item}
                          </Option>
                        ))
                      : ''}
                  </Select>
                </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;
