/* eslint-disable prefer-promise-reject-errors */
/* eslint-disable indent */
import React, { useState, useEffect } from 'react';
import { Form, Modal, Input, Select, notification, InputNumber, Tooltip, Row, Col } from 'antd';
import {
  GettMaplayer,
  GetVectorService,
  SetServiceConfig,
  bindSchemeBaseMap,
  SetBaseMapschemeName,
} from '@/services/webConfig/api';
import { InfoCircleOutlined } from '@ant-design/icons';
const { Item } = Form;
const { Option } = Select;
const AddProjectModal = props => {
  const { callBackSubmit = () => {}, type, formObj, visible, serviceList, cardData, all } = props;
  const [loading, setLoading] = useState(false);
  const [baseMap, setBaseMap] = useState([]);
  const [pipeArr, setPipeArr] = useState([]);
  const [arr, setArr] = useState([]);

  const [form] = Form.useForm();
  // 提交
  const onSubmit = () => {
    form.validateFields().then(validate => {
      if (validate) {
        setLoading(true);
        let obj = form.getFieldsValue();

        if (type === 'add') {
          // let aa = cardData.find(i => i.schemename == formObj.schemename);
          // aa.baseMap.push(obj.serverName);
          // aa.baseMapDetail.push({ servicename: obj.serverName, zoom: obj.zoom });
          // let query = {
          //   schemename: formObj.schemename,
          //   terminalType: 'baseMapscheme',
          //   isBaseMap: 'false',
          //   jsonCfg: JSON.stringify({
          //     baseMap: aa.baseMap,
          //     baseMapDetail: aa.baseMapDetail,
          //   }),
          // };
          // SetServiceConfig(query)
          //   .then(res => {
          //     setLoading(false);
          //     if (res.msg === 'Ok') {
          //       form.resetFields();
          //       callBackSubmit();
          //       prompt('success', '瓦片新增成功');
          //     } else {
          //       prompt('fail', '瓦片新增失败');
          //     }
          //   })
          //   .catch(err => {
          //     setLoading(false);
          //   });

          let data = {
            schemename: formObj.schemename,
            servicename: obj.serverName,
            zoom: obj.zoom,
            maxZoom: obj.maxzoom,
          };
          SetBaseMapschemeName(data)
            .then(res => {
              setLoading(false);
              if (res.code == '0') {
                form.resetFields();
                callBackSubmit();
                prompt('success', '基础底图新增成功');
              } else {
                prompt('fail', '基础底图新增失败');
              }
            })
            .catch(err => {
              setLoading(false);
            });
        } 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: 'baseMapscheme',
    //   isBaseMap: 'false',
    //   jsonCfg: JSON.stringify({
    //     baseMap: [obj.baseMap],
    //     alpha: 1,
    //   }),
    // };
    let data = {
      schemename: obj.schemename,
      servicename: obj.baseMap,
      zoom: 0,
    };
    SetBaseMapschemeName(data)
      .then(res => {
        setLoading(false);
        if (res.code == '0') {
          form.resetFields();
          callBackSubmit();
          prompt('success', '分级底图新增成功');
        } else {
          prompt('fail', '分级底图新增失败');
        }
      })
      .catch(err => {
        setLoading(false);
      });
    // 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(() => {
    console.log(type);
    switch (type) {
      case 'add':
        addTile();
        break;
      case 'schemeAdd':
        pipeNetwork();
        break;
      default:
        break;
    }
  }, [visible]);

  // 添加瓦片
  const addTile = () => {
    let aa = cardData.find(i => i.schemename == formObj.schemename);
    console.log(aa);
    let arrNew = [];
    aa.baseMapDetail.map(i => {
      arrNew.push(i.zoom);
    });
    console.log(arrNew);
    setArr(arrNew);
    form.setFieldsValue({
      serverName: serviceList[0],
    });
  };
  // 获取管网及默认底图
  const pipeNetwork = () => {
    form.resetFields();
    let req1 = GettMaplayer({ terminalType: 'base', isBaseMap: true });
    let req2 = GetVectorService();
    let pipeArr = [];
    let baseMap = [];
    Promise.all([req1, req2]).then(res => {
      if (res[0].code == '0') {
        (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}/PandaGIS/MapServer/Export?mapServerName=${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="600px"
      destroyOnClose
      maskClosable={false}
      cancelText="取消"
      okText="确认"
      {...props}
      onOk={() => onSubmit()}
      confirmLoading={loading}
      forceRender
      getContainer={false}
    >
      {visible && (
        <Form form={form} {...layout} onFinish={onFinish}>
          {type === 'add' ? (
            <>
              <Item label="底图级别" style={{ marginBottom: '0px' }}>
                <Row>
                  <Col span={7}>
                    <Item
                      // label={
                      //   <div>
                      //     {/* <Tooltip title="同一分级底图中的不同基础底图级别不能相同">
                      //       <InfoCircleOutlined
                      //         style={{
                      //           color: 'rgb(24, 144, 255)',
                      //           marginLeft: '0px',
                      //           marginRight: '5px',
                      //         }}
                      //       />
                      //     </Tooltip> */}
                      //     <span>最小级别</span>
                      //   </div>
                      // }
                      name="zoom"
                      rules={[
                        { required: true, message: '请输入最小级别' },
                        // {
                        //   validator: (rule, value) => {
                        //     const obj = form.getFieldsValue().zoom;
                        //     console.log(obj);
                        //     if (arr.indexOf(obj) != -1) {
                        //       console.log(111);
                        //       return Promise.reject('已存在该级别的基础底图');
                        //     }
                        //     return Promise.resolve();
                        //   },
                        // },
                      ]}
                    >
                      <InputNumber min={0} max={99} />
                    </Item>
                  </Col>
                  <Col span={2}>
                    <div style={{ marginTop: '4px' }}>~</div>
                  </Col>
                  <Col span={10}>
                    <Item
                      // label="最大级别"
                      name="maxzoom"
                      rules={[
                        {
                          validator: (rule, value) => {
                            const obj = form.getFieldsValue().zoom;
                            const objmax = form.getFieldsValue().maxzoom;
                            if (objmax < obj) {
                              return Promise.reject('最大级别不能小于最小级别');
                            }
                            return Promise.resolve();
                          },
                        },
                      ]}
                    >
                      <InputNumber min={0} max={99} />
                    </Item>
                  </Col>
                </Row>
              </Item>
              <Item
                label="基础底图"
                name="serverName"
                rules={[{ required: true, message: '请输入基础底图' }]}
              >
                <Select onChange={handleChange}>
                  {serviceList.length
                    ? serviceList.map((item, index) => (
                        <Option key={index} value={item}>
                          {item}
                        </Option>
                      ))
                    : ''}
                </Select>
              </Item>
            </>
          ) : (
            <>
              <Item
                label="名称"
                name="schemename"
                labelCol={{ span: 5 }}
                rules={[{ required: true, message: '请输入名称' }]}
              >
                <Input placeholder="请输入名称" allowClear />
              </Item>
              <Item
                label="默认基础底图"
                labelCol={{ span: 5 }}
                name="baseMap"
                rules={[{ required: true, message: '请选择基础底图' }]}
              >
                <Select onChange={handleBaseMap}>
                  {baseMap.length
                    ? baseMap.map((item, index) => (
                        <Option key={index} value={item}>
                          {item}
                        </Option>
                      ))
                    : ''}
                </Select>
              </Item>
            </>
          )}
        </Form>
      )}
    </Modal>
  );
};
export default AddProjectModal;