import React, { useState, useEffect, useCallback, useRef } from 'react';
import styles from './index.less';
import cx from 'classnames';
import { Select } from 'antd';

import type { navigatorItem } from '@/pages/Environment/index';
import { getBuildingList, getFloorList } from '@/services/ant-design-pro/environment';
import { projectId } from '@/config/api.js';
import { useModel } from 'umi';
export type topNavigatorProps = {
  navigatorList?: navigatorItem[];
  type: string;
  navigatorChange?: (item: navigatorItem) => void;
  // action?: React.ReactElement<topNavRightProps>[];
  action?: React.ReactNode;
  changeFloorId?: (data: string) => void;
  changeBuildId?: (data: string) => void;
  selParamObj?: any;
};
type floorItem = {
  value: string;
  [key: string]: any;
};
type buildItem = {
  value: string;
  [key: string]: any;
};
const TopNavigator: React.FC<topNavigatorProps> = ({
  navigatorList = [],
  type,
  navigatorChange,
  action,
  changeFloorId,
  changeBuildId,
  selParamObj,
}) => {
  //存储的 搜索到空间的buildingId floorId
  const { searchBuildId, searchFloorId } = useModel('searchInfo');
  const [buildList, setBuildList] = useState<buildItem[]>([]);
  const [currentBuild, setCurrentBuild] = useState<string>();

  const [floorList, setFloorList] = useState<floorItem[]>([]);
  const [currentFloor, setCurrentFloor] = useState<string>();

  //const [shishi, setShishi] = useState<string>('22');
  //则监听searchBuildId的改变    如果buildingId改变 请求楼层列表
  useEffect(() => {
    if (searchBuildId && searchFloorId) {
      if (searchBuildId !== currentBuild) {
        //如果搜索的buildId 改变
        setCurrentBuild(searchBuildId);
      } else {
        //显示
        setCurrentFloor(searchFloorId);
        //父亲的floorId
        //这块 其实只想楼层id改变时调用 建筑id 改变时不调用
        changeFloorId && changeFloorId(searchFloorId);
      }
    }
  }, [searchBuildId, searchFloorId]);

  //请求建筑的接口
  useEffect(() => {
    //console.log('TopNavigator----getBuildingList');
    getBuildingList({
      criteria: {
        projectId: projectId,
      },
    }).then((res) => {
      var resData = res.content || [];
      setBuildList(
        (resData || []).map((item) => {
          return { label: item.localName, value: item.id };
        }),
      );
      //   var resData2 = [];
      //   resData2.push(JSON.parse(JSON.stringify(resData[0])));
      //   resData2.push(JSON.parse(JSON.stringify(resData[0])));
      //   resData2[1].id = 'sdfsd';
      //   resData2[1].localName = 'boruiÎ';
      setBuildList(
        (resData || []).map((item) => {
          return { label: item.localName, value: item.id };
        }),
      );

      setCurrentBuild((resData[0] || {}).id); //设置第一个建筑值
      changeBuildId && changeBuildId((resData[0] || {}).id);
    });
  }, []);

  //请求楼层列表的接口
  useEffect(() => {
    async function asyncFunction() {
      var res = await getFloorList({
        criteria: {
          buildingId: currentBuild,
          //buildingId: 'Bd1101080259317347f00d0811ebb06b1d2749356f83',
        },
      });
      var resData = res.content || [];
      setFloorList(
        (resData || []).map((item) => {
          return { label: item.localName, value: item.id };
        }),
      );

      setCurrentFloor(searchFloorId || (resData[0] || {}).id); //如果有搜索的楼层id 则用搜索的结果
      changeFloorId && changeFloorId(searchFloorId || (resData[0] || {}).id); //改变父组件的floorId的值
    }
    if (currentBuild) {
      asyncFunction();
    }

    // if (currentBuild) {
    //   getFloorList({
    //     criteria: {
    //       buildingId: currentBuild,
    //       //buildingId: 'Bd1101080259317347f00d0811ebb06b1d2749356f83',
    //     },
    //   }).then((res) => {
    //     var resData = res.content || [];
    //     setFloorList(
    //       (resData || []).map((item) => {
    //         return { label: item.localName, value: item.id };
    //       }),
    //     );

    //     setCurrentFloor(searchFloorId || (resData[0] || {}).id); //如果有搜索的楼层id 则用搜索的结果
    //     changeFloorId && changeFloorId(searchFloorId || (resData[0] || {}).id); //改变父组件的floorId的值
    //   });
    // }
  }, [currentBuild]);

  const changBuildHandle = useCallback((val) => {
    //console.log('select-onChange', val);

    //changeSearchFloorId('');
    //setShishi('fsdf');
    //显示的建筑改变
    setCurrentBuild(val);
    //父亲的buildId改变
    changeBuildId && changeBuildId(val);
  }, []);
  const changFloorHandle = useCallback((val) => {
    setCurrentFloor(val);

    changeFloorId && changeFloorId(val);
  }, []);

  //当前切换导航条时
  const itemClick = (item: navigatorItem) => {
    //console.log('itemclick', item);
    navigatorChange && navigatorChange(item);
  };

  return (
    <div className={styles.topnavigator}>
      <div className={styles.floor}>
        <Select
          options={buildList}
          placeholder="楼栋"
          value={currentBuild}
          onChange={changBuildHandle}
          size="large"
          dropdownMatchSelectWidth={true}
          style={{ width: '100%' }}
          bordered={false}
          //   labelInValue={true}
          // fieldNames={{ label: 'name', value: 'id' }}
        />
      </div>
      <div className={styles.floor}>
        <Select
          options={floorList}
          placeholder="楼层"
          value={currentFloor}
          onChange={changFloorHandle}
          size="large"
          dropdownMatchSelectWidth={true}
          style={{ width: '100%' }}
          bordered={false}
        />
      </div>
      <div className={styles.navigator}>
        {navigatorList.map((item, index) => {
          return (
            <div
              className={cx(styles.navItem, { [styles.sel]: item.id === selParamObj.id })}
              style={{
                borderBottom:
                  item.id === selParamObj.id ? `3px solid  ${item.color}` : '3px solid #ffffff',
              }}
              key={'nav' + index}
              onClick={() => {
                itemClick(item);
              }}
            >
              <img src={item.src} style={{ height: 20 }}></img>
              <div className={styles.text}>{item.name}</div>
            </div>
          );
        })}
      </div>
      {type === 'enviroment' && (
        <div className={styles.right}>
          <div className={styles.firstLine} style={{ color: selParamObj.color }}>
            <span className={styles.value}>{selParamObj.avgValues}</span>{' '}
            <span className={styles.unit}>{selParamObj.unit}</span>
          </div>
          <div className={styles.text}>当前楼层平均{selParamObj.name}</div>
        </div>
      )}
      {type === 'equipment' && action}
      {type === 'runtime' && action}
    </div>
  );
};

export default TopNavigator;
