// 设备管理 导航条的右侧
import React, { useState, useEffect, useMemo } from 'react';
import { Dropdown, Menu, Modal, message } from 'antd';
import Icon from '@/tenants-ui/SgIcon';
import { EllipsisOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import styles from './index.less';
//import { equipImageMap } from '@/config/sagacare/sagacare_image.js';
import type { navigatorItem } from '@/pages/Environment/index';
import { socketType } from '@/pages/Equipment/index';
import type { MenuProps } from 'antd';
import { projectObj } from '@/config/api.js';

import {
  changeCurtain,
  changeAllAir,
  changeLight,
  changeSocket,
} from '@/pages/Equipment/equipmentControl';

export type topNavRightProps = {
  selNavObj: navigatorItem;
  navigatorList: navigatorItem[];
  mapList: API.MapInfo[];
  selSocketType: socketType;
  socketTypeArr: socketType[];
  //queryDeviceManage: () => Promise<any>;
};

const TopNavRight: React.FC<topNavRightProps> = ({
  selNavObj,
  navigatorList,
  mapList,
  selSocketType,
  socketTypeArr,
}) => {
  //const [modalvisible, setModalvisible] = useState<boolean>(false);
  //去掉全部设备的 设备列表
  const [deviceList, setDeviceList] = useState<navigatorItem[]>([]);
  useEffect(() => {
    var navigatorListCopy: navigatorItem[] = [];
    navigatorList.forEach((item) => {
      if (item.id !== 'all' && item.id !== 'curtain') {
        navigatorListCopy.push(item);
      }
    });
    //console.log('navigatorListCopy', navigatorListCopy, navigatorList);
    setDeviceList(navigatorListCopy);
  }, [navigatorList]);

  // const deviceList = useMemo(() => {
  //   debugger;
  //   var navigatorListCopy=JSON.parse(JSON.stringify(navigatorList));
  //   navigatorListCopy.splice(3,1);
  //   navigatorListCopy.splice(0,1);
  //   return navigatorListCopy;
  // }, [navigatorList]);

  const allOpenClick = (key) => {
    //debugger;
    console.log('key', key);
    confirm({
      title: '请确认',
      icon: <ExclamationCircleOutlined />,
      //content: `确定要全部开启${selNavObj.name}吗？`,
      content:
        selNavObj.id == 'socket' && selSocketType.code !== 'all'
          ? `确定要全部开启${selSocketType.name}吗？`
          : `确定要全部开启${selNavObj.name}吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk() {
        //console.log('mapListmapList', mapList,selNavObj);
        //筛选 没有开启的空间
        if (selNavObj.id == 'light' || selNavObj.id == 'socket') {
          var filterSpaceArr = mapList.filter((item) => {
            return (item[selNavObj.id] == 0 || item[selNavObj.id] == 2) && item.spaceId;
          });
        } else {
          var filterSpaceArr = mapList.filter((item) => {
            return item.spaceId;
          });
        }

        var flag = 1;
        //现在加上循环调用 所以把查询关了F
        function getDeviceStatus() {
          //   flag = flag + 1;
          //   queryDeviceManage().then((res) => {
          //     if (flag < 13) {
          //       setTimeout(() => {
          //         getDeviceStatus();
          //       }, 800);
          //     } else {
          //       flag = 1;
          //     }
          //   });
        }
        //如果是空调
        if (filterSpaceArr.length == 0) return;
        if (selNavObj.id == 'airConditioner') {
          changeAllAir(filterSpaceArr, getDeviceStatus, '打开', projectObj.projectId);
        }
        if (selNavObj.id == 'light') {
          changeLight('all', filterSpaceArr, getDeviceStatus, '打开');
        }
        if (selNavObj.id == 'socket') {
          changeSocket('all', filterSpaceArr, '打开', selSocketType);
        }
        if (selNavObj.id == 'curtain') {
          changeCurtain('all', filterSpaceArr, getDeviceStatus, '打开'); // '关闭' : '打开';
        }
      },
      onCancel() {
        //console.log('Cancel');
      },
    });
  };
  const { confirm } = Modal;
  const allCloseClick = () => {
    console.log('showModal');
    // setModalvisible(true);
    confirm({
      title: '请确认',
      icon: <ExclamationCircleOutlined />,
      content:
        selNavObj.id == 'socket' && selSocketType.code !== 'all'
          ? `确定要全部关闭${selSocketType.name}吗？`
          : `确定要全部关闭${selNavObj.name}吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk() {
        if (selNavObj.id == 'light' || selNavObj.id == 'socket') {
          var filterSpaceArr = mapList.filter((item) => {
            return (item[selNavObj.id] == 1 || item[selNavObj.id] == 2) && item.spaceId;
          });
        } else {
          var filterSpaceArr = mapList.filter((item) => {
            return item.spaceId;
          });
        }

        var flag = 1;
        function getDeviceStatus() {
          //   flag = flag + 1;
          //   queryDeviceManage().then((res) => {
          //     if (flag < 13) {
          //       setTimeout(() => {
          //         getDeviceStatus();
          //       }, 800);
          //     } else {
          //       flag = 1;
          //     }
          //   });
        }

        //如果是空调
        if (selNavObj.id == 'airConditioner') {
          changeAllAir(filterSpaceArr, getDeviceStatus, '关闭', projectObj.projectId);
        }
        if (selNavObj.id == 'light') {
          changeLight('all', filterSpaceArr, getDeviceStatus, '关闭');
        }
        if (selNavObj.id == 'socket') {
          changeSocket('all', filterSpaceArr, '关闭', selSocketType);
        }
        if (selNavObj.id == 'curtain') {
          changeCurtain('all', filterSpaceArr, getDeviceStatus, '关闭');
        }
      },
      onCancel() {
        //console.log('Cancel');
      },
    });
  };
  const menuitems: MenuProps['items'] = [
    {
      key: '1',
      label: (
        <div style={{ width: 160 }} onClick={(key) => allOpenClick(key)}>
          全部开启
        </div>
      ),
    },
  ];

  return (
    <>
      {/* 全部设备 */}
      {selNavObj.id === 'all' && (
        <div className={styles.right}>
          <div className={styles.title}>运行中的设备</div>
          <div className={styles.allList}>
            {deviceList.map(function (litem, index) {
              return (
                <div className={styles.item} key={'run' + index}>
                  <img src={litem.src} style={{ height: 20 }}></img>
                  <div className={styles.num}>{litem.num}</div>
                </div>
              );
            })}
          </div>
        </div>
      )}
      {/* 设备 */}
      {selNavObj.id !== 'all' && (
        <div className={styles.right}>
          {selNavObj.id !== 'curtain' && <div className={styles.title}>运行中的设备</div>}
          {selNavObj.id !== 'curtain' &&
            (selNavObj.id == 'socket' && selSocketType.code !== 'all' ? (
              <div className={styles.onlyNum}>
                {socketTypeArr.map(function (sitem, sindex) {
                  if (sitem.code == selSocketType.code) {
                    return <span key={'snum' + sindex}>{sitem.openNum}</span>;
                  } else {
                    return;
                  }
                })}
              </div>
            ) : (
              <div className={styles.onlyNum}>
                {deviceList.map(function (ditem, dindex) {
                  if (ditem.id == selNavObj.id) {
                    return <span key={'dnum' + dindex}>{ditem.num}</span>;
                  } else {
                    return;
                  }
                })}
              </div>
            ))}
          <div
            className={styles.closeButton}
            onClick={allCloseClick}
            style={{ display: selNavObj.id == 'curtain' ? 'none' : '' }}
          >
            {/* <Button type="primary"  size={'large'}  icon={<Icon type="closeall"  style={{color:'red',fontSize:20}} />} style={{'background':'rgba(196, 196, 196, 0.2)',border:'none'}} >
              全部关闭
            </Button> */}
            <Icon className="" type="closeall" style={{ fontSize: 20 }} />
            <span className={styles.text}>全部关闭</span>
          </div>
          <div
            className={styles.moreWrap}
            style={{ display: selNavObj.id == 'curtain' ? 'none' : '' }}
          >
            {/* ...下拉菜单 */}
            <Dropdown trigger={['click']} placement="bottomLeft" menu={{ items: menuitems }}>
              <span className={styles.trigger}>
                <EllipsisOutlined style={{ fontSize: 20, marginTop: '4px' }} />
              </span>
            </Dropdown>
          </div>
        </div>
      )}

      {/* <Modal
        title="确认"
        visible={modalvisible}
        onOk={hideModal}
        onCancel={hideModal}
        okText="确认"
        cancelText="取消"
      >
        <p>确定全部开启吗</p>
      </Modal> */}
    </>
  );
};

export default TopNavRight;
