import { putDeviceCategoryUpdateDeviceCategory } from '@/services/device/DeviceCategory';
import { postDeviceGroupGetDeviceGroupFkSelect } from '@/services/device/DeviceGroup';
import { ModalForm, ProForm, ProFormFieldSet, ProFormSelect, ProFormSwitch, ProFormText } from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Form, message,Image, Button, Popover, List, Avatar } from 'antd';
import React, { useEffect, useState } from 'react';
import { getUploadInvolvedTravelList, postUploadRecognition } from '@/services/alarm/Involved';
import styles from './InvolvedDetails.less'
import  './InvolvedDetails.less'
import moment from 'moment';
import { CloseCircleOutlined, EllipsisOutlined } from '@ant-design/icons';
import VirtualList from 'rc-virtual-list';
import trajectoryBottom from '../../../../../public/images/involved/trajectoryBottom.png'
export type FormValueType = {
  target?: string;
  template?: string;
  type?: string;
  time?: string;
  frequency?: string;
} & Partial<API.InvolvedDetailsParams>;

export type UpdateFormProps = {
  updateModalOpen: boolean;
  handleModal: () => void;
  values: Partial<API.InvolvedDetailsParams>;
  reload: any;
};
const InvolvedDetails: React.FC<UpdateFormProps> = (props) => {
  const intl = useIntl();
  const [form] = Form.useForm<API.InvolvedDetailsParams>();
  const [dataFlag, setDataFlag] = useState(false);;
  const [open, setOpen] = useState(false);
  const [trajectoryData, setTrajectoryData] = useState([]);
  //  动态设置每页数量
  const [currentPageSize, setCurrentPageSize] = useState<number>(10);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [total, setTotal] = useState<number>(0);
  const ContainerHeight = 630;
  const content = (
    <div style={{ display: 'flex', justifyContent: 'center',alignItems: 'center', height: '100%'}}>
      {/* <div>选项1</div>
      <div>选项2</div> */}
      <Button 
        type="text" 
        style={{ height:22, padding: 0,fontSize: 12,color: '#FFF'  }} 
        icon={<CloseCircleOutlined style={{ color: '#E80D0D',fontSize: 12}} />}
        onClick={(event)=>{
            event.stopPropagation();
            postUploadRecognition({
              person_id: props.values.person_id,
              classify: '0'
            })
              .then(() => {
                message.success('此人已被移除重点关注');
                props.reload();
              })
              .catch(() => {
                message.error(intl.formatMessage({ id: 'common.failure', defaultMessage: '失败' }));
              });
            setOpen(false)
            props.handleModal()
        }}
        >移除重点关注</Button>
    </div>
  );
  const handleOpenChange = (value: boolean) => {
    setOpen(value);
  };
  
  const appendData = (page: any, pageSize: any) => {
    const reqParams = {
      page: page,
      pageSize: pageSize,
      // desc: false,
      person_id: props.values.person_id,
      // ...rest,
    };
    getUploadInvolvedTravelList(reqParams).then((res) => {
      console.log(res);
      if(res.data.results) {
        setTrajectoryData(trajectoryData.concat(res.data.results));
        setTotal(res.data.count)
        if(res.data.next) {
          setDataFlag(true)
        }else {
          setDataFlag(false)
          // setTrajectoryData([]); // 重置trajectoryData数据为空数组
        }
      }
    })
    .catch(() => {
      // setLoading(false);
      setDataFlag(false)
      // setTrajectoryData([]); // 重置trajectoryData数据为空数组
    });
  };
  const onScroll = (e: React.UIEvent<HTMLElement, UIEvent>) => {
    // Refer to: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight#problems_and_solutions
    console.log(e.currentTarget.scrollHeight - e.currentTarget.scrollTop - ContainerHeight);
    
    if (Math.abs(e.currentTarget.scrollHeight - e.currentTarget.scrollTop - ContainerHeight) <= 1) {
      if(dataFlag) {
        const nextPage = currentPage + 1
        setCurrentPage(nextPage);
        appendData(nextPage, 10);
      }
    }
  };
  useEffect(() => {
    if (props.updateModalOpen) {
      // 调用接口获取数据
      setTrajectoryData([]); // 重置trajectoryData数据为空数组
      setCurrentPage(1);
      setCurrentPageSize(10);
      appendData(currentPage, currentPageSize);
    }
  }, [props.updateModalOpen]);
  return (
    <ModalForm<any>
      width={615}
      title={
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            padding: '24px 32px 0px',
            justifyContent: 'flex-start',
          }}
        >
          <div style={{ position: 'relative', boxSizing: 'border-box', width: 120, height: 120 }}>
            <Image
              style={{ borderRadius: 4 }}
              width={120}
              height={120}
              preview={false}
              src={props?.values?.picture_path}
            />
            <Popover
              placement="right"
              content={content}
              trigger="click"
              style={{ width: 104, height: 32 }}
              color="rgba(0, 0, 0, 0.6)"
              overlayInnerStyle={{ width: 104, height: 32, padding: 4, borderRadius: 2 }}
              open={open}
              onOpenChange={handleOpenChange}
            >
              <Button
                style={{ position: 'absolute', bottom: 0, right: -4 }}
                type="text"
                icon={<EllipsisOutlined style={{ color: '#fff', fontSize: 24, transform: 'rotate(90deg)' }} />}
                // onClick={handleButtonClick}
              />
            </Popover>
              <div
                style={{
                  position: 'absolute',
                  top: 0,
                  right: 0,
                  width: 64,
                  height: 24,
                  background: '#FAAD14',
                  borderRadius: '0px 4px 0px 4px',
                  color: '#FFF',
                  fontSize: 12,
                  textAlign: 'center',
                  lineHeight: '24px',
                  fontWeight: 400
                }}
              >
                重点关注
              </div>
          </div>
          <div
            style={{
              marginLeft: 12,
              height: 98,
              display: 'flex',
              flexDirection: 'column',
              justifyContent: 'flex-start',
              color: '#666',
              fontSize: 14,
              fontWeight: 400
            }}
          >
            <div>
              关注时间:{' '}
              <span
                style={{
                  color: '#333',
                }}
              >
                {moment(props?.values?.classify_time).format('YYYY-MM-DD hh:mm:ss')}
              </span>
            </div>
            <div>
              最近发现:{' '}
              <span
                style={{
                  color: '#333',
                }}
              >
                {moment(props?.values?.appear_time).format('YYYY-MM-DD hh:mm:ss')}
              </span>
            </div>
            {/* <div>
              来源设备:{' '}
              <span
                style={{
                  color: '#333',
                }}
              >
                {props?.values?.device_name}
              </span>
            </div> */}
          </div>
        </div>
      }
      open={props.updateModalOpen}
      form={form}
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
        onCancel: () => {
          setTrajectoryData([]);
          setCurrentPage(1);
          setCurrentPageSize(10);
          props.handleModal()
        },
        wrapClassName:"involvedModalForm"
      }}
      submitter={false}
      submitTimeout={2000}
      onFinish={async (values) => {
        values.is_ignore = true
        values.person_id = props.values.person_id
        // console.log(values);
        // postIgnoringvents(values)
        //   .then(() => {
        //     message.success(intl.formatMessage({ id: 'common.success', defaultMessage: '成功' }));
        //     props.reload();
        //   })
        //   .catch(() => {
        //     message.error(intl.formatMessage({ id: 'common.failure', defaultMessage: '失败' }));
        //   });
        setTrajectoryData([]);
        setCurrentPage(1);
        setCurrentPageSize(10);
        props.handleModal();
        return true;
      }}
      
    >
      {/* <ProForm.Group> */}
        {/* <div className={styles.alarmDetails}>
            告警名称: <span className={styles.alarmSpan}>单人徘徊告警</span>来源设备: <span className={styles.alarmSpan}>北广场检票口1#摄像头</span>触发时间: <span className={styles.alarmSpan}>2023-01-15 22:00:03</span>
        </div> */}
        <div className={styles.InvolvedImgBox}>
          <List>
            <VirtualList
              data={trajectoryData}
              height={ContainerHeight}
              itemHeight={64}
              itemKey="id"
              onScroll={onScroll}
            >
              {(item: any, index:any) => (
                 <div key={item.person_id + index}>
                  <List.Item style={{ borderBottom: 0, height: 64, padding: 0 }}>
                    <List.Item.Meta
                      avatar={
                        <div className={styles.involvedImgList}>
                          <img style={{ width: 32, height: 32 }} src={trajectoryBottom} />
                          {index + 1 !== total && <span />}
                        </div>
                      }
                      title={<div style={{ lineHeight: '30px', color: '#666' }}>时间定位: <span style={{ color: '#333', marginRight: 16}}>{moment(item.create_time).format('YYYY-MM-DD hh:mm:ss')}</span> 来源视频: <span style={{ color: '#333'}}>{item.video_name}</span></div>}
                    />
                    <div>
                      <Image
                        style={{ borderRadius: 4 }}
                        width={48}
                        height={48}
                        preview={{
                          mask: '',
                        }}
                        src={item.picture_path}
                      />
                    </div>
                  </List.Item>
                 {index === total - 1 && (
                   <div style={{ textAlign: 'center', color: '#999' }}>已无更多数据~</div>
                 )}
               </div>
              )}
            </VirtualList>
          </List>
        </div>
            
      {/* </ProForm.Group> */}
    </ModalForm>
  );
};
export default InvolvedDetails;
