import { alarmRulesEnums } from '@/enums/status';
import { ActionType, PageContainer, ProCard, ProList, useIntl } from '@ant-design/pro-components';
import { Image, Modal, Tabs } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { proTablePaginationOptions } from '../../../../config/defaultTable';
// import DeviceStatusCard from './components/DeviceStatusCard';
// import CreateForm from './components/CreateForm';
import { getInvolvedList } from '@/services/alarm/Involved';
import { QuestionCircleFilled } from '@ant-design/icons';
import InvolvedDetails from './components/InvolvedDetails';
import moment from 'moment';
import ImageWithPopover from './components/ImageWithPopover';

/**
 * @交互说明
 * 1、列表分页展示服务器状态
 */
const tabOptions: Record<string, any> = {
  singlePersonHoveringAlarm: 90,
  multiplePersonGatheringAlarm: 20,
  sensitiveTimePeriodAlarm: 20,
  ignored: 2,
  // processingStatus: 10,
  // errorStatus: 20,
};
export type DeleteBoxProps = {
  modalOpen: boolean;
  handleModal: () => void;
  values: any;
  reload: any;
};

const InvolvedList: React.FC = () => {
  const [cardActionProps, setCardActionProps] = useState<'actions' | 'extra'>('extra');
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, setCreateModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 更新窗口的弹窗
   * */
  const [updateModalOpen, setUpdateModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 删除窗口
   * */
  const [modalOpen, setModalOpen] = useState(false);
  const [currentRow, setCurrentRow] = useState<Record<string, any>>({});
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  // const access = useAccess();
  // const intl = useIntl();
  const actionRef = useRef<ActionType>();
  //  动态设置每页数量
  const [currentPageSize, setCurrentPageSize] = useState<number>(10);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [total, setTotal] = useState<number>(0);

  const [activeTabIndex, setActiveTabIndex] = useState<number>(0);
  const [dataTestList, setdataTestList] = useState<any>([]);

  const [tab, setTab] = useState<string>(alarmRulesEnums[0].key);
  const [tabs, setTabs] = useState<any>([]);
  // const changeProjectTab = (key: string) => {
  //   setTab(key);
  //   console.log(key);
  //   // eslint-disable-next-line @typescript-eslint/no-use-before-define
  //   initList(key)
  // };
  const getTabs = () => {
    // if (alarmRulesEnums.length) {
    //   setTab(alarmRulesEnums[0].key);
    // }
    setTabs(alarmRulesEnums);
  };
  // useEffect(() => {
  //   getTabs();
  // }, []);
  const handleCreateModal = () => {
    if (createModalOpen) {
      setCreateModalOpen(false);
      setCurrentRow(undefined);
    } else {
      setCreateModalOpen(true);
    }
  };

  const handleUpdateModal = () => {
    if (updateModalOpen) {
      setUpdateModalOpen(false);
      setCurrentRow(undefined);
    } else {
      setUpdateModalOpen(true);
    }
  };

  const handleDestroy = async () => {
    if (modalOpen) {
      setModalOpen(false);
      setCurrentRow(undefined);
    } else {
      setModalOpen(true);
    }
    // deleteBusinessImageDeleteBusinessImage({ id: selectedRow.id })
    //   .then(() => {
    //     message.success(intl.formatMessage({ id: 'common.success', defaultMessage: '$$$' }));
    //     actionRef.current?.reload();
    //   })
    //   .catch(() => {
    //     message.error(intl.formatMessage({ id: 'common.failure', defaultMessage: '$$$' }));
    //   });
  };

  const { confirm } = Modal;
  const showConfirm = (record: any) => {
    confirm({
      title: `确定删除${record.name}吗`,
      icon: <QuestionCircleFilled />,
      content: '确定删除服务器1吗？删除后将找不到此服务器，请谨慎操作.',
      okText: '确认',
      cancelText: '取消',
      width: 560,
      onOk() {
        console.log('OK');
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  // 处理初始值
  function initDataTestList(dataList: Record<string, any>[]) {
    console.log(dataList, 'initDataTestList');
    let finalList: { content: React.JSX.Element; }[] = []
    if (Array.isArray(dataList) && dataList.length) {
       finalList = dataList.map((record, index) => {
        return {
          content: (
            <ProCard
              className="gn"
              style={{ backgroundColor: '#F5F6FF', margin: 0, padding: 0, borderRadius: 4 }}
              bodyStyle={{ margin: 0, padding: 0 }}
            >
              <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  padding: 20,
                  justifyContent: 'flex-start',
                }}
                onClick={() => {
                  console.log(index, 'index');
                  setUpdateModalOpen(true);
                  setCurrentRow(record);
                }}
              >
                {/* <Image
                  width={96}
                  preview={false}
                  src={record.picture_path[0]}
                /> */}
                <ImageWithPopover
                  src={record.picture_path}
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  reload={initList}
                  person_id={record.person_id}
                  // handleInvolved={handleInvolved}
                ></ImageWithPopover>
                <div
                  style={{
                    marginLeft: 16,
                    height: 90,
                    display: 'flex',
                    flexDirection: 'column',
                    justifyContent: 'space-between',
                    color: '#666',
                  }}
                >
                  <div>
                    关注时间:{' '}
                    <span
                      style={{
                        color: '#333',
                      }}
                    >
                      {moment(record.classify_time).format('YYYY-MM-DD hh:mm:ss')}
                    </span>
                  </div>
                  <div>
                    最近发现:{' '}
                    <span
                      style={{
                        color: '#333',
                      }}
                    >
                      {moment(record.appear_time).format('YYYY-MM-DD hh:mm:ss')}
                    </span>
                  </div>
                  <div>
                    来源设备:{' '}
                    <span
                      style={{
                        color: '#333',
                      }}
                    >
                      {record.device_name}
                    </span>
                  </div>
                </div>
              </div>
            </ProCard>
          ),
        };
      });
    }
    
    setdataTestList(() => [...finalList]);
  }

  // 初始化加载
  async function initList(tabId:string = '1') {
    const reqParams = {
      page: currentPage,
      pageSize: currentPageSize,
      // desc: false,
      classify: tabId,
      // ...rest,
    };
    const resp = await getInvolvedList({ ...reqParams });
    // console.log(resp,'resp');
    // setCurrentPageSize(resp?.data?.count)
    setTotal(resp?.data?.count)
    initDataTestList(resp?.data?.results);
    // request={async (params = {}, sort) => {
    //   const { current, ...rest } = params;
    //   const reqParams = {
    //     page: current,
    //     desc: false,
    //     warning_type: tab,
    //     ...rest,
    //   };
    //   if (sort && Object.keys(sort).length) {
    //     reqParams.orderKey = Object.keys(sort)[0];
    //     let sort_select = sort[reqParams.orderKey];
    //     reqParams.desc = sort_select === 'descend';
    //   }
    //   // TODO 联调查询设备状态接口
    //   console.log(reqParams, 'reqParams');
    //   let resp = await postAlarmList({ ...reqParams });
    //   console.log(resp, 'postAlarmList_result');

    //   initDataTestList(resp.result);
    //   // return {
    //   //   data: resp.result,
    //   //   success: resp.success,
    //   //   total: resp.count,
    //   //   current: resp.count,
    //   //   pageSize: resp.count,
    //   // };
    // }}
  }
  useEffect(() => {
    getTabs();
    initList();
  }, []);
  useEffect(() => {
    // 模拟异步请求数据
    initList();
  }, [currentPage, currentPageSize]);
  return (
    <PageContainer
    // title={false}
    // content={
    //   <div style={{
    //     display: 'flex',
    //     justifyContent: 'space-between'
    //   }}>
    //     <div style={{
    //       fontWeight: 600,
    //       fontSize: 20,
    //       color: '#333'
    //     }}></div>
    //   </div>
    // }
    >
      <ProCard
        className="gn"
        bodyStyle={{ padding: 10, margin: 0 }}
        style={{ padding: 0, margin: 0 }}
      >
        {/* <Tabs
          activeKey={tab}
          items={tabs}
          onChange={(key) => {
            changeProjectTab(key);
          }}
        ></Tabs> */}
        <ProList<any>
          className="gn"
          ghost={true}
          itemCardProps={{
            ghost: true,
            bodyStyle: { padding: 0, margin: 0 },
            style: {
              width: '100%',
              border: 0,
              // minHeight: 700
              // padding: 0, margin: 0
            },
          }}
          // search={{
          //   labelWidth: proTableCommonOptions.searchLabelWidth,
          // }}
          // headerTitle={
          //   <>
          //     <div>
          //       {Object.keys(tabOptions).map((item, index) => {
          //         // eslint-disable-next-line react/jsx-key
          //         return (
          //           <Button
          //             style={{ marginRight: 12,border: 'none' }}
          //             // type={activeTabIndex === index ? 'primary' : 'default'}
          //             key={index}
          //             onClick={() => {
          //               setActiveTabIndex(index);
          //             }}
          //           >
          //             {Object.keys(alarmRulesEnums).includes(item)
          //               ? alarmRulesEnums[item].miniName
          //               : ''}
          //           {"("+tabOptions[item]+ ')'}
          //           </Button>
          //         );
          //       })}
          //     </div>
          //   </>
          // }
          cardProps={{
            bodyStyle: {
              padding: '8px 16px 16px',
              borderRadius: 8,
            },
          }}
          pagination={{
            ...proTablePaginationOptions,
            total: total,
            current: currentPage,
            pageSize: currentPageSize,
            showSizeChanger: true,
            onChange: (page, pageSize) => {
              console.log(page, pageSize);
              setCurrentPage(page)
              setCurrentPageSize(pageSize)
            },
          }}
          showActions="hover"
          rowSelection={false}
          grid={{ gutter: 16, xs: 1, md: 2, lg: 2, xl: 3, xxl: 3 }}
          metas={{
            type: {
              // 不展示在筛选项
              hideInSearch: true,
            },
            content: {
              hideInSearch: true,
            },
            actions: {
              cardActionProps,
            },
            // status1: {
            //   // 自己扩展的字段，主要用于筛选，不在列表中显示
            //   title: '设备组',
            //   valueType: 'select',
            //   valueEnum: {
            //     '0': { text: '全部设备分组', status: '0' },
            //     '1': {
            //       text: '设备分组1',
            //       status: '1',
            //     },
            //     '2': {
            //       text: '设备分组2',
            //       status: '2',
            //     },
            //     '3': {
            //       text: '设备分组3',
            //       status: '3',
            //     },
            //   },
            // },
            // status2: {
            //   // 自己扩展的字段，主要用于筛选，不在列表中显示
            //   title: '分类',
            //   valueType: 'select',
            //   valueEnum: {
            //     '0': { text: '全部分类', status: '0' },
            //     '1': {
            //       text: '外围监控',
            //       status: '1',
            //     },
            //     '2': {
            //       text: '室内监控',
            //       status: '2',
            //     },
            //     '3': {
            //       text: '违规监控',
            //       status: '3',
            //     },
            //   },
            // },
          }}
          dataSource={dataTestList}
        />
      </ProCard>

      {/* <CreateForm
        createModalOpen={createModalOpen}
        values={currentRow || {}}
        handleModal={handleCreateModal}
        reload={actionRef.current?.reload}
      /> */}
      <InvolvedDetails
        updateModalOpen={updateModalOpen}
        values={currentRow || {}}
        handleModal={handleUpdateModal}
        reload={initList}
      />
    </PageContainer>
  );
};

export default InvolvedList;
