/* eslint-disable indent */
import {
  Space,
  Table,
  Button,
  Popconfirm,
  notification,
  Spin,
  Divider,
  Tooltip,
  Empty,
} from 'antd';
import React, { useState, useEffect } from 'react';
import { PlusOutlined, UserAddOutlined } from '@ant-design/icons';
import AutoResponsive from 'autoresponsive-react';
import styles from '../SchemeConfig.less';
import {
  GettMaplayer,
  deleteConfig,
  GetMaplayerByTerminalType,
  QueryBaseMapItems,
} from '@/services/webConfig/api';
import AddModal from './AddModal';
import EditModal from './EditModal';
import NewEditModal from './NewEditModal';
import Cards from './card';
import AddProjectModal from './AddProjectModal';

const TileData = props => {
  const [treeLoading, setTreeLoading] = useState(false); // 弹窗显示
  const [tileData, setTileData] = useState([]); // table表格数据
  const [cardData, setCardData] = useState([]);
  const [visible, setVisible] = useState(false); // 弹窗
  const [projectVisible, setProjectVisible] = useState(false);
  const [addVisible, setAddVisible] = useState(false); // 弹窗
  const [editVisible, setEditVisible] = useState(false);
  const [type, setType] = useState(''); // 弹窗类型
  const [formObj, setFormObj] = useState({});
  const [flag, setFlag] = useState(0); // 弹窗类型
  const [baseMap, setBaseMap] = useState([]); // 底图数据
  const [name, setName] = useState([]);
  const [flagAdd, setFlagAdd] = useState(0);
  const [type1, setType1] = useState('');
  const [json, setJson] = useState([]);
  const columns = [
    {
      title: '服务名',
      dataIndex: 'servicename',
      key: 'servicename',
      align: 'center',
    },
    {
      title: '标签',
      dataIndex: 'label',
      key: 'label',
      align: 'center',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      align: 'center',
    },
    // {
    //   title: '透明度',
    //   dataIndex: 'alpha',
    //   key: 'alpha',
    //   align: 'center',
    //   render: (text, record) => <span>{`${(text * 100).toFixed()}%`}</span>,
    // },
    {
      title: '编辑',
      align: 'center',
      render: (text, record) => (
        <Space>
          <Button
            type="primary"
            size="small"
            onClick={() => {
              changebaseMap(record);
            }}
          >
            编辑
          </Button>
          <div onClick={e => e.stopPropagation()}>
            <Popconfirm
              title="是否删除该底图?"
              okText="确认"
              cancelText="取消"
              onConfirm={() => {
                delConfirm(record);
              }}
            >
              <Button size="small" danger>
                删除
              </Button>
            </Popconfirm>
          </div>
        </Space>
      ),
    },
  ];

  useEffect(() => {
    setTreeLoading(true);
    GetMaplayerByTerminalType({
      terminalType: 'baseMapscheme',
      isBaseMap: false,
    })
      .then(res => {
        console.log('res', res);
        if (res.code == '0') {
          setTreeLoading(false);
          setCardData(res.data.optionalLayer.layers);
        } else {
          setTreeLoading(false);
        }
      })
      .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);
      });
  }, [flagAdd]);
  const changebaseMap = record => {
    setType('edit');
    setFormObj(record);
    setEditVisible(true);
  };
  const onSubmit = prop => {
    setEditVisible(false);
    setFlag(flag + 1);
    setAddVisible(false);
  };

  const onSubmitProject = prop => {
    setProjectVisible(false);
    setFlagAdd(flagAdd + 1);
  };

  const delConfirm = record => {
    const { servicename = '' } = record;
    setTreeLoading(true);
    deleteConfig({
      servicename,
      terminalType: 'base',
      isBaseMap: true,
    })
      .then(res => {
        setFlag(flag + 1);
        setFlagAdd(flagAdd + 1);
        setTreeLoading(false);
        if (res.code == '0') {
          // form.resetFields();
          // callBackSubmit();
          notification.success({
            message: '提示',
            duration: 3,
            description: res.message || '删除成功',
          });
        } else {
          notification.error({
            message: '提示',
            duration: 3,
            description: res.message || '删除失败',
          });
        }
      })
      .catch(err => {
        setFlag(flag + 1);
        setTreeLoading(false);
      });
  };
  const handleAdd = () => {
    // console.log(baseMap);
    // if (baseMap.length) {
    setType('add');
    setAddVisible(true);
    // } else {
    //   notification.warning({
    //     message: '提示',
    //     duration: 3,
    //     description: '地图类型已都存在,可编辑修改',
    //   });
    // }
  };
  useEffect(() => {
    renderTile();
  }, [flag]);

  useEffect(() => {
    QueryBaseMapItems()
      .then(res => {
        if (res.code === '0') {
          setJson(res.data);
        }
      })
      .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 renderTile = () => {
    setTreeLoading(true);
    const baseMapData = [
      // '谷歌地形',
      // '谷歌影像',
      '高德地形',
      '高德影像',
      '天地图地形',
      '天地图影像',
    ];
    GettMaplayer({
      terminalType: 'base',
      isBaseMap: true,
    })
      .then(res => {
        if (res.code == '0') {
          setTreeLoading(false);
          let newdata = res.data.general.baseMap.layers?.filter(i => i.isVector === 0);
          setTileData(newdata);
          let data = [];
          res.data.general.baseMap.layers.map(item => {
            data.push(item.servicename);
            let index = baseMapData.indexOf(item.servicename);
            if (index != -1) {
              baseMapData.splice(index, 1);
            }
          });
          setName(data);
          setBaseMap(baseMapData);
        } else {
          setTreeLoading(false);
          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 addType = () => {
    setType1('schemeAdd');
    setProjectVisible(true);
  };

  const onDeletebaseMap = value => {
    setFlagAdd(flagAdd + 1);
  };
  return (
    <div className={styles.tileContainer}>
      <div>
        <Spin tip="loading..." spinning={treeLoading}>
          <Divider orientation="left">
            <div className={styles.divider}>
              基础底图{' '}
              <Tooltip title="新增基础底图">
                <PlusOutlined
                  onClick={() => {
                    handleAdd();
                  }}
                  style={{ marginTop: '5px', marginLeft: '10px', color: '#4699f4' }}
                />
              </Tooltip>
            </div>
          </Divider>
          <Table
            className={styles.tableTile}
            columns={columns}
            dataSource={tileData}
            bordered
            rowKey="servicename"
            pagination={{
              showTotal: (total, range) => `第${range[0]}-${range[1]} 条/共 ${total} 条`,
              pageSize: 5,
            }}
          />
          <Divider orientation="left">
            <div className={styles.divider}>
              分级底图{' '}
              <Tooltip title="新增分级底图">
                <PlusOutlined
                  onClick={() => {
                    addType();
                  }}
                  style={{ marginTop: '5px', marginLeft: '10px', color: '#4699f4' }}
                />
              </Tooltip>
            </div>{' '}
          </Divider>
          <div className={styles.cardsList1}>
            {/* <AutoResponsive
            itemMargin="10"
            containerWidth="100%"
            itemClassName="item"
            gridWidth="100"
            transitionDuration=".5"
          > */}
            {cardData && cardData.length ? (
              cardData.map((item, index) => (
                <div
                  className={styles.cardItem}
                  key={index}
                  span={5}
                  offset={2}
                  style={{ marginBottom: '1rem' }}
                >
                  <Cards item={item} deletebaseMaps={onDeletebaseMap} cardData={cardData} />
                </div>
              ))
            ) : (
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} style={{ margin: 'auto' }} />
            )}
            {/* </AutoResponsive> */}
          </div>

          <AddModal
            visible={addVisible}
            onCancel={() => setAddVisible(false)}
            callBackSubmit={onSubmit}
            type={type}
            formObj={formObj}
            baseMap={baseMap}
            name={name}
            json={json}
          />
          <EditModal
            visible={visible}
            onCancel={() => setVisible(false)}
            callBackSubmit={onSubmit}
            type={type}
            formObj={formObj}
            baseMap={baseMap}
          />
          <NewEditModal
            visible={editVisible}
            onCancel={() => setEditVisible(false)}
            callBackSubmit={onSubmit}
            type={type}
            formObj={formObj}
            baseMap={baseMap}
            name={name}
            json={json}
          />
          <AddProjectModal
            visible={projectVisible}
            onCancel={() => setProjectVisible(false)}
            callBackSubmit={onSubmitProject}
            type={type1}
            formObj={formObj}
          />
        </Spin>
      </div>
    </div>
  );
};
export default TileData;