import TabsComp from '@/components/TabsComp';
import styles from '../../../GLQ/index.less';
import styles1 from './index.less';
import { useEffect, useState } from 'react';
import { ConfigProvider, Pagination, Table, Upload, UploadProps, message } from 'antd';

import { rowClassName } from '@/utils';
import ButtonComp from '@/components/ButtonComp';
import { devicePhotoList } from '@/services/register';

export default function Page() {
  const [activeTab, setActiveTab] = useState(1)
  const [tableData, setTableData] = useState([]);
  const [pageNumber, setPageNumber] = useState(1);
  const [pageSize, setpageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [imageUrl, setImageUrl] = useState('');

  const columns: any = [
    { title: '设备型号', dataIndex: 'name', key: 'name', align: 'center' },
    { title: '', align: 'center' },
  ]

  useEffect(() => {
    getList();
    setSelectedRowKeys([])
  }, [pageNumber]);

  const getList = () => {
    devicePhotoList({ pageNumber, pageSize }).then((res) => {
      if (res?.result == "success") {
        setTotal(res.data[0].total)
        setTableData(res.data[0].list)
      } else {
        message.error(res?.errorMsg);
      }
    })
  }

  const pageOnChange = (pageNumber: number) => {
    setPageNumber(pageNumber);
  }

  const onShowSizeChange = (current: any, pageSize: any) => {
    setpageSize(pageSize);
    getList();
  }

  const props: UploadProps = {
    maxCount: 1,
    beforeUpload: (file: any) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt64K = file.size / 1024 <= 64;
      if (!isJpgOrPng) {
        message.error('只能上传 JPG/PNG 图片文件！');
        return
      }
      if (!isLt64K) {
        message.error('图片大小不能超过 64KB！');
        return
      }
      return isJpgOrPng && isLt64K;
    },
    onChange: (info: any) => {
      if (info.file.status === 'done') {
        // 上传完成后，从响应数据中获取图片 URL
        const imageUrl = info.file.response.url;
        console.log("imageUrl",info);
        
        setImageUrl(imageUrl);

        //   const formData = new FormData();
        // formData.append('file', file);
        // secretInit_loadData(formData).then((res) => {
        //   if (res?.result == "success" && res?.data.length > 0) {
        //     message.success('加载数据成功');
        //     form.setFieldsValue({ ...res?.data[0] })
        //     localStorage.setItem('MMJInit', JSON.stringify(res?.data[0]));
        //     setDataLoading(true);
        //   } else {
        //     message.error(res?.errorMsg);
        //   }
        // })
      }
      if (info.file.status === 'error') {
        message.error('上传失败！');
      }
    }
  };

  return (
    <div className={`${styles.params_warp}`}>
      <TabsComp
        dataSource={[{ id: 1, name: '设备照片维护' }]}
        activeTab={activeTab}
        onChange={(e) => setActiveTab(e)} />

      <div className='flex_jB'>
        <div style={{ width: 'calc(50% - 20px)' }}>
          <ButtonComp type={'special'} text={`设备型号列表（共${total}条）`} onClick={() => { }} />
          <Table
            scroll={tableData.length > 0 ? { y: 41 * 14 } : {}}
            pagination={false}
            bordered
            columns={columns}
            dataSource={tableData}
            rowKey={(record: any) => record?.id}
            rowClassName={rowClassName}
            rowSelection={{
              type: 'radio',
              selectedRowKeys,
              onChange: (selectedKeys: any) => {
                setSelectedRowKeys(selectedKeys);
              }
            }}
          />

          {total > 0 && <div className='flex_aiC_jB mt20'>
            <div>共 {total} 条</div>
            <Pagination
              current={pageNumber}
              pageSize={pageSize}
              total={total}
              showQuickJumper
              onChange={pageOnChange}
              onShowSizeChange={onShowSizeChange}
            />
          </div>}
        </div>
        <div style={{ width: '50%' }}>
          <div className={styles1.info}>提示：请选择设备型号，然后选择该型号的照片，照片大小不要超过64KB，建议尺寸为128×128像素。</div>
          <div className={styles1.picture}>
            <ButtonComp style={{ position: 'absolute', left: '-1px', top: '-8px' }} type={'special'} text={'照片'} />
            <img src={imageUrl}/>
          </div>
          <div className='flex_jE mt20 mb20'>
            <Upload {...props} showUploadList={false}>
              <ButtonComp type='cancel' style={{ marginRight: 20 }} text={'选择'} onClick={() => { }} />
            </Upload>
            <ButtonComp text={'保存'} onClick={() => { }} />
          </div>
        </div>
      </div>
    </div>
  );
}