import React, { useState, useEffect, useCallback, useMemo } 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/sagacare_service/environment';
import { projectObj } from '@/config/api.js';
import { useModel } from 'umi';
import UserStorage from '@/config/sagacare/sagacare_user';

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;
  seasonType?: 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,
  seasonType,
}) => {
  //存储的 搜索到空间的buildingId floorId
  const { searchBuildId, searchFloorId } = useModel('sagacare_searchInfo');
  const { lastBuildId, lastFloorId, changeLastBuildId, changeLastFloorId } =
    useModel('sagacare_buildFloor');
  const [buildList, setBuildList] = useState<buildItem[]>([]);
  const [currentBuild, setCurrentBuild] = useState<string>();
  const [floorList, setFloorList] = useState<floorItem[]>([]);
  const [currentFloor, setCurrentFloor] = useState<string>();

  //则监听searchBuildId的改变    如果buildingId改变 请求楼层列表
  useEffect(() => {
    if (searchBuildId && searchFloorId) {
      if (searchBuildId !== currentBuild) {
        //如果搜索的buildId 改变
        setCurrentBuild(searchBuildId);
      } else {
        //如果搜索的buildId 没改变 floorId 改变了
        //为了 显示楼层选择
        setCurrentFloor(searchFloorId);
        //父亲的floorId
        //这块 其实只有楼层id改变时调用  建筑id 改变时不调用
        changeFloorId && changeFloorId(searchFloorId);
      }
    }
  }, [searchBuildId, searchFloorId]);

  var levelObj = useMemo(() => {
    let level = 0;
    let levelTxt = '';

    if (type === 'enviroment') {
      if (selParamObj.avgValues == undefined) {
        return { level: -1, levelTxt: '' };
      }
      var tdbParam = {
        Cooling: {
          range: [22, 26],
          text: ['偏冷', '舒适', '偏热'],
        },
        Warm: {
          range: [18, 24],
          text: ['偏冷', '舒适', '偏热'],
        },
        Transition: {
          range: [18, 26],
          text: ['偏冷', '舒适', '偏热'],
        },
      };

      let objList = {
        Tdb: tdbParam[seasonType],
        RH: {
          range: [30, 70],
          text: ['干燥', '健康', '潮湿'],
        },
        CO2: {
          range: [800, 1000, 1500],
          text: ['健康', '达标', '略高', '超标'],
        },
        PM2d5: {
          range: [35, 75, 115, 150, 250],
          text: ['健康', '良', '轻度污染', '中度污染', '重度污染', '严重污染'],
        },
        HCHO: {
          range: [0.1],
          text: ['健康', '超标'],
        },
      };
      let sortArr = [selParamObj.avgValues, ...objList[selParamObj.id].range].sort((a, b) => {
        return a - b;
      });

      level = sortArr.findIndex((item) => item === selParamObj.avgValues);

      levelTxt = objList[selParamObj.id].text[level];
    }
    return { level, levelTxt };
  }, [selParamObj, seasonType]);

  //请求建筑的接口
  useEffect(() => {
    var userObj = UserStorage.getInstance();
    const user = userObj.getUser();
    console.log('TopNavigator----getBuildingList', user, projectObj.projectId);
    if (buildList.length == 0) {
      getBuildingList({
        criteria: {
          projectId: projectObj.projectId,
        },
        orders: [
          {
            column: 'localId',
            asc: true,
          },
        ],
      }).then((res) => {
        var resData = res.content || [];
        setBuildList(
          (resData || []).map((item) => {
            return { label: item.localName, value: item.id };
          }),
        );

        var lastBuildId2 = lastBuildId || sessionStorage.getItem('lastBuildId') || '';
        var lastFilter = resData.filter((item) => {
          return item.id == lastBuildId2;
        });

        var lastBuildIdTemp = '';
        if (lastFilter.length > 0) {
          lastBuildIdTemp = lastBuildId2;
        }
        //debugger;
        setCurrentBuild(searchBuildId || lastBuildIdTemp || (resData[0] || {}).id); //设置第一个建筑值
        //changeBuildId && changeBuildId(lastBuildId || (resData[0] || {}).id);
      });
    }
  }, []);

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

      //如果最后选中的
      var lastFilter = resData.filter((item) => {
        return item.id == lastFloorId2;
      });

      var lastFloorIdTemp = '';
      if (lastFilter.length > 0) {
        lastFloorIdTemp = lastFloorId2;
      }
      //debugger;
      setCurrentFloor(searchFloorId || lastFloorIdTemp || (resData[0] || {}).id); //如果有搜索的楼层id 则用搜索的结果
      changeFloorId && changeFloorId(searchFloorId || lastFloorIdTemp || (resData[0] || {}).id); //改变父组件的floorId的值
    }

    if (currentBuild) {
      changeLastBuildId(currentBuild);
      asyncFunction();
    }
    //console.log('currentBuild22', currentBuild);
    return () => {
      //console.log('currentBuild111', currentBuild);
    };
  }, [currentBuild]);

  //   useEffect(() => {
  //     //为了 显示楼层选择
  //     if (floorList.length > 0) {
  //       debugger;
  //       setCurrentFloor(searchFloorId || lastFloorId || (floorList[0] || {}).value); //如果有搜索的楼层id 则用搜索的结果
  //       changeFloorId && changeFloorId(searchFloorId || lastFloorId || (floorList[0] || {}).value); //改变父组件的floorId的值
  //     }
  //   }, [floorList]);

  const changBuildHandle = useCallback((val) => {
    //显示的建筑改变
    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 #fff',
              }}
              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>
            <sup className={styles.unit}>{selParamObj.unit}</sup>
            <span className={styles.line}></span>
            <span className={styles.level}>{levelObj.levelTxt}</span>
          </div>

          <div className={styles.text}>
            当前楼层平均{selParamObj.name}
            {selParamObj.id == 'CO2' || selParamObj.id == 'PM2d5' || selParamObj.id == 'HCHO'
              ? '浓度'
              : ''}
          </div>
        </div>
      )}
      {type === 'equipment' && action}
      {type === 'runtime' && action}
    </div>
  );
};

export default TopNavigator;
