/* eslint-disable indent */
/* eslint-disable object-shorthand */
import React, { useState, useEffect } from 'react';
import classnames from 'classnames';
import { Popconfirm, notification, Card, Button, message, Tooltip } from 'antd';
import {
  unbindSchemeBaseMap,
  GettMaplayer,
  SetServiceConfig,
  deleteConfig,
  GetbaseMapschemeName,
} from '@/services/webConfig/api';
import {
  CloseOutlined,
  PlusOutlined,
  GlobalOutlined,
  BlockOutlined,
  FormOutlined,
} from '@ant-design/icons';
import AddModal from '../AddModal';
import EditModal from '../EditModal';
import MapScope from '@/components/MapScope';
import { createGuid } from '@/utils/transformUtil';
import AddModalBase from '../AddModalBase';
import styles from '../../SchemeConfig.less';
const CardData = props => {
  const { deletebaseMaps = () => {}, item, cardFlag, keepData, nameData } = props;
  const [visible, setVisible] = useState(false); // 弹窗
  const [basevisible, setBaseVisible] = useState(false); // 弹窗
  const [flag, setFlag] = useState(0); // 状态更新
  const [type, setType] = useState(''); // 弹窗类型
  const [formObj, setFormObj] = useState({});
  const [serviceList, setServiceList] = useState([]);
  const [mapScopeVisible, setMapScopeVisible] = useState(false);
  const [cardData, setCardData] = useState([]);
  const [editVisible, setEditVisible] = useState(false);
  // 删除瓦片

  useEffect(() => {
    // GettMaplayer({ terminalType: 'base', isBaseMap: true }).then(res => {
    //   if (res.msg === 'Ok') {
    //     let arr = [];
    //     res.data.general.baseMap.layers.map(i => {
    //       arr.push(i.servicename);
    //     });
    //   }
    // });
    setCardData(keepData);
    console.log(props.item);
  }, [cardFlag]);

  const deletebaseMap = (item, baseMapItem) => {
    console.log(item);
    console.log(props.item.defaultOldBaseMap);
    console.log(baseMapItem);
    let j = props.item.defaultOldBaseMap.indexOf(baseMapItem);
    let i = props.item.defaultBaseMap;
    console.log(j);
    console.log(i);
    if (item.baseMap.length > 1) {
      unbindSchemeBaseMap({ schemename: item.schemename, basemapName: baseMapItem }).then(res => {
        if (res.code == '0') {
          if (j == i) {
            SetServiceConfig({
              schemename: props.item.schemename,
              terminalType: 'scheme',
              isBaseMap: false,
              jsonCfg: JSON.stringify({
                defaultBaseMap: 0,
              }),
            }).then(resdata => {
              if (resdata.code == '0') {
                deletebaseMaps();
              }
            });
          } else if (j < i) {
            SetServiceConfig({
              schemename: props.item.schemename,
              terminalType: 'scheme',
              isBaseMap: false,
              jsonCfg: JSON.stringify({
                defaultBaseMap: i - 1,
              }),
            }).then(resdata => {
              if (resdata.code == '0') {
                deletebaseMaps();
              }
            });
          } else {
            deletebaseMaps();
          }
          notification.success({
            message: '提示',
            duration: 3,
            description: '底图方案删除成功',
          });
        } else {
          notification.error({
            message: '提示',
            duration: 3,
            description: '底图方案删除失败',
          });
        }
      });
    } else {
      message.warning('方案至少需要一张底图');
    }
  };
  // 删除方案
  const deleteTile = item => {
    deleteConfig({
      schemename: item.schemename,
      terminalType: 'scheme',
      isBaseMap: false,
    }).then(res => {
      if (res.code == '0') {
        notification.success({
          message: '提示',
          duration: 3,
          description: '方案删除成功',
        });
        deletebaseMaps();
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: '方案删除失败',
        });
      }
    });
  };
  const onSubmit = prop => {
    setVisible(false);
    deletebaseMaps();
    setBaseVisible(false);
  };

  // 增加瓦片
  const addTile = value => {
    let serverList = [];
    setFormObj(value);
    if (JSON.stringify(value) != '{}') {
      GettMaplayer({ terminalType: 'base', isBaseMap: true }).then(res => {
        if (res.code == '0') {
          res.data.general.baseMap.layers.map(item => {
            if (value.baseMap.indexOf(item.servicename) == -1) {
              serverList.push(item.servicename);
            }
          });
        }
        let arr = [];
        GetbaseMapschemeName().then(resdata => {
          if (resdata.data.length) {
            resdata.data.map(i => {
              if (value.baseMap.indexOf(i) == -1) {
                arr.push(i);
              }
            });
            if (arr.length) {
              setServiceList(arr);
              setType('add');
              setVisible(true);
            } else {
              notification.warning({
                message: '提示',
                duration: 3,
                description: '请先在底图配置-配置底图分级显示方案',
              });
            }
          } else {
            notification.warning({
              message: '提示',
              duration: 3,
              description: '请先在底图配置-配置底图分级显示方案',
            });
          }
        });
      });
    }
  };

  const addTileBase = value => {
    let serverList = [];
    setFormObj(value);
    if (JSON.stringify(value) != '{}') {
      GettMaplayer({ terminalType: 'base', isBaseMap: true }).then(res => {
        if (res.code == '0') {
          res.data.general.baseMap.layers.map(item => {
            if (value.baseMap.indexOf(item.servicename) == -1) {
              serverList.push(item.servicename);
            }
          });
        }
        if (serverList.length) {
          setServiceList(serverList);
          setType('add');
          setBaseVisible(true);
        } else {
          notification.warning({
            message: '提示',
            duration: 3,
            description: '请先在基础配置-配置底图',
          });
        }
      });
    }
  };

  const editTile = value => {
    setFormObj(value);
    setEditVisible(true);
  };

  const submitExtent = (extent, areaName, flag) => {
    if (flag === 0) {
      notification.warn({
        message: '提交失败',
        description: '请框选范围',
      });
      return;
    }
    const jsConfig = {
      extent: extent,
      areaName: areaName,
      boundColor: '#86c8f8',
      boundWidth: '10px',
      backgroundColor: '#000000',
      backgroundOpacity: '0.6',
    };
    SetServiceConfig({
      schemename: item.schemename,
      terminalType: 'web',
      isBaseMap: false,
      jsonCfg: JSON.stringify(jsConfig),
    }).then(res => {
      if (res.code == '0') {
        setMapScopeVisible(false);
        message.info('范围设置成功');
      }
    });
  };

  const pick = (schemename, baseMapItem) => {
    console.log(schemename);
    console.log(props.item.defaultOldBaseMap);
    let i = props.item.defaultOldBaseMap.indexOf(baseMapItem);
    console.log(i);
    SetServiceConfig({
      schemename: schemename,
      terminalType: 'scheme',
      isBaseMap: false,
      jsonCfg: JSON.stringify({
        defaultBaseMap: i,
      }),
    }).then(res => {
      if (res.code == '0') {
        deletebaseMaps();
        message.success('设置成功');
      } else {
        message.warning(res.msg);
      }
    });
  };

  const onEditSubmit = () => {
    setEditVisible(false);
    deletebaseMaps();
  };

  return (
    <>
      <Card
        title={
          <div>
            <span className={styles.schemeName}>方案名</span>
            {props.item.schemename}
          </div>
        }
        extra={
          <a href="#">
            <Popconfirm
              title="是否删除该方案?"
              okText="确认"
              cancelText="取消"
              onConfirm={() => {
                deleteTile(props.item);
              }}
            >
              <CloseOutlined />
            </Popconfirm>{' '}
          </a>
        }
        style={{ width: 360 }}
      >
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '13px' }}>
          <div>
            <span className={styles.schemeName}>管网</span> {props.item.servicename}
          </div>
          <div>
            <FormOutlined
              style={{ marginRight: '10px', color: '#1890ff' }}
              onClick={() => editTile(props.item)}
            />
          </div>
        </div>

        {/* <div>
          <span className={styles.schemeName}>范围</span>
          <Button
            style={{ width: '12rem', marginBottom: '0.5rem' }}
            onClick={() => setMapScopeVisible(true)}
          >
            选择范围
          </Button>
        </div> */}
        <div className={styles.schemeItem}>
          {/* <span className={styles.schemeName}>底图方案</span> */}
          <Button className={styles.schemeBtn} onClick={() => addTileBase(props.item)}>
            {' '}
            <GlobalOutlined />
            添加基础底图
          </Button>
          <Button className={styles.schemeBtn} onClick={() => addTile(props.item)}>
            {' '}
            <BlockOutlined />
            添加分级底图
          </Button>
        </div>
        <div style={{ overflowY: 'scroll', height: '11.4rem' }}>
          {props.item.baseMap && props.item.baseMap.length
            ? props.item.baseMap.map((baseMapItem, baseindex) => (
                <div className={styles.mapItem} key={baseindex}>
                  <div
                    onClick={() => pick(props.item.schemename, baseMapItem)}
                    className={classnames({
                      [styles.defaultTile]: true,
                      [styles.activeTile]: baseindex == props.item.defaultBaseMap,
                    })}
                  >
                    默认
                    {cardData.indexOf(baseMapItem) == -1 ? (
                      <BlockOutlined style={{ marginTop: '5px' }} />
                    ) : (
                      <GlobalOutlined style={{ marginTop: '5px' }} />
                    )}
                  </div>
                  <div className={styles.mapText}>
                    <Tooltip title={baseMapItem}>{baseMapItem}</Tooltip>
                  </div>
                  <div className={styles.mapIcon}>
                    <Popconfirm
                      title={
                        cardData.indexOf(baseMapItem) == -1 ? (
                          <span>是否删除该分级底图?</span>
                        ) : (
                          <span>是否删除该底图?</span>
                        )
                      }
                      okText="确认"
                      cancelText="取消"
                      onConfirm={() => {
                        deletebaseMap(props.item, baseMapItem);
                      }}
                    >
                      <CloseOutlined />
                    </Popconfirm>{' '}
                  </div>
                </div>
              ))
            : ''}
        </div>
      </Card>
      <AddModal
        visible={visible}
        onCancel={() => setVisible(false)}
        callBackSubmit={onSubmit}
        type={type}
        serviceList={serviceList}
        formObj={formObj}
        nameData={nameData}
      />
      <EditModal
        visible={editVisible}
        onCancel={() => setEditVisible(false)}
        callBackSubmit={onEditSubmit}
        formObj={formObj}
      />
      <AddModalBase
        visible={basevisible}
        onCancel={() => setBaseVisible(false)}
        callBackSubmit={onSubmit}
        type={type}
        serviceList={serviceList}
        formObj={formObj}
        nameData={nameData}
      />
      <MapScope
        mapId={createGuid()}
        visible={mapScopeVisible}
        onCancel={() => setMapScopeVisible(false)}
        confirmModal={submitExtent}
        schemename={props.item.schemename}
        title={props.item.schemename}
      />
    </>
  );
};
export default CardData;