import React, { useEffect, useState, useRef } from 'react';
import TableCom from '@/common/TableCom/index';
import {
  Table,
  Input,
  Button,
  Row,
  Col,
  Space,
  DatePicker,
  Image,
  Drawer,
  Form,
  Tree,
  Modal,
} from 'antd';
const { RangePicker } = DatePicker;
import { useNavigate } from 'react-router-dom';
import PaginationCom from '@/common/Pagination';
import { getList, getExamineList, addExamine } from './request';
import { getAllList, getInfoByChapterId } from '../section/request';
import reload from '@/assets/images/icon/reload.png';
import reset from '@/assets/images/icon/reset.png';
import filter from '@/assets/images/icon/filter.png';
import add from '@/assets/images/icon/add.png';
import { CloseOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import { useSelector } from 'react-redux';
import PreviewModal from './preview';

const Audit = () => {
  const navigate = useNavigate();
  const [data, setData] = useState([]);
  const [page_size, setpage_size] = useState(10);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [ids, setIds] = useState([]);
  const [chapterId, setChapterId] = useState([]);

  const [priviewVisible, setPriviewVisible] = useState(false);
  const previewRef = useRef();

  const [selectedId, setSelectedId] = useState(null);
  const [loading, setLoading] = useState(true);
  const [isEdit, setIsEdit] = useState(false);
  const [form] = Form.useForm();
  // 获取操作权限
  const { operationPermissionsList } = useSelector((state) => state.user);
  const [filterObj, setfilterObj] = useState({
    name: '',
    authors: '',
    start_time: '',
    end_time: '',
  });
  const [dateVal, setDateVal] = useState('');
  const [showPhone, setShowPhone] = useState(false);
  const [initialValues, setinitialValues] = useState(
    JSON.parse(sessionStorage.getItem('editData')) || {},
  );
  const [editor, setEditor] = useState(null);
  // 初始化 html 状态值
  const [html, setHtml] = useState(initialValues.help_content || '');

  const [shouldPreview, setShouldPreview] = useState(false);

  const handleRowClick = (record) => {
    setSelectedId(record.id);
    setShouldPreview(true);
  };

  useEffect(() => {
    if (shouldPreview) {
      setShowPhone(true);
      setShouldPreview(false);
      prev({ book_id: selectedId });
    }
  }, [selectedId, shouldPreview, data]);

  const Com = () => {
    const [h, setH] = useState(0);
    useEffect(() => {
      let height = document.querySelector('.ant-table-tbody').clientHeight;
      if (height > 600) {
        setH(600);
      }
    }, [data]);

    return (
      <Table
        scroll={{
          y: h,
          x: true,
        }}
        columns={columns}
        // rowKey={(record) => record.id}
        dataSource={data}
        loading={loading}
        pagination={false}
      ></Table>
    );
  };
  // 过滤
  const handleFilter = (flag, val) => {
    if (flag == 'startandend') {
      let val2 = val || [];
      filterObj['start_time'] = parseInt(
        new Date(dayjs(val2[0]).format('YYYY-MM-DD') + ' 00:00:00').getTime() / 1000,
      );
      const endDate = new Date(dayjs(val2[1])).getDate();
      const endTime = parseInt(
        new Date(dayjs(val2[1]).format('YYYY-MM-') + endDate + ' 23:59:59').getTime() / 1000,
      );
      filterObj['end_time'] = endTime;
      setDateVal(val);
      if (!val2.length) {
        delete filterObj['start_time'];
        delete filterObj['end_time'];
      }
    } else {
      filterObj[flag] = val;
    }
    for (const key in filterObj) {
      if (!filterObj[key]) {
        delete filterObj[key];
      }
    }
    setfilterObj({ ...filterObj });
    if (!val) init(filterObj);
  };
  // 重置
  const handleReset = () => {
    setfilterObj({ real_name: '', tel: '' });
    setDateVal('');
    init();
  };
  const init = async (obj = {}) => {
    setLoading(true);
    const { total, list } = await getList({ page, page_size, ...obj, audit_status: 2 });
    setTotal(total);
    setData(list);
    setIds(list.map((item) => item.id));
    console.log('setID', ids);

    setLoading(false);
  };

  const prev = async (obj = {}) => {
    setLoading(true);
    const res = await getAllList({ ...obj, book_id: selectedId });
    setChapterId(res.data.map((item) => item.id));
    setHtml(res.img);

    // if (res.length > 0) {
    //   const rowData = res.find((item) => item.id === id); // 找到对应id的行数据
    //   if (rowData) {
    //     // setHtml(rowData.img);
    //   }
    // }
    setLoading(false);
  };

  const submitForm = (obj) => {
    console.log(obj);
  };

  const columns = [
    {
      title: 'ID',
      key: 'id',
      align: 'center',
      dataIndex: 'id',
    },
    {
      title: '书籍图片',
      key: 'img',
      align: 'center',
      dataIndex: 'img',
      render: (_, { img }) => (
        <Image
          width={80}
          height={80}
          src={img}
          fallback='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMIAAADDCAYAAADQvc6UAAABRWlDQ1BJQ0MgUHJvZmlsZQAAKJFjYGASSSwoyGFhYGDIzSspCnJ3UoiIjFJgf8LAwSDCIMogwMCcmFxc4BgQ4ANUwgCjUcG3awyMIPqyLsis7PPOq3QdDFcvjV3jOD1boQVTPQrgSkktTgbSf4A4LbmgqISBgTEFyFYuLykAsTuAbJEioKOA7DkgdjqEvQHEToKwj4DVhAQ5A9k3gGyB5IxEoBmML4BsnSQk8XQkNtReEOBxcfXxUQg1Mjc0dyHgXNJBSWpFCYh2zi+oLMpMzyhRcASGUqqCZ16yno6CkYGRAQMDKMwhqj/fAIcloxgHQqxAjIHBEugw5sUIsSQpBobtQPdLciLEVJYzMPBHMDBsayhILEqEO4DxG0txmrERhM29nYGBddr//5/DGRjYNRkY/l7////39v///y4Dmn+LgeHANwDrkl1AuO+pmgAAADhlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAAAwqADAAQAAAABAAAAwwAAAAD9b/HnAAAHlklEQVR4Ae3dP3PTWBSGcbGzM6GCKqlIBRV0dHRJFarQ0eUT8LH4BnRU0NHR0UEFVdIlFRV7TzRksomPY8uykTk/zewQfKw/9znv4yvJynLv4uLiV2dBoDiBf4qP3/ARuCRABEFAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQ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PZF2ArbXTAyu4kDYB2YxUzwg0gi/41ztHnfQG26HbGel/crVrm7tNY+/1btkOEAZ2M05r4FB7r9GbAIdxaZYrHdOsgJ/wCEQY0J74TmOKnbxxT9n3FgGGWWsVdowHtjt9Nnvf7yQM2aZU/TIAIAxrw6dOnAWtZZcoEnBpNuTuObWMEiLAx1HY0ZQJEmHJ3HNvGCBBhY6jtaMoEiJB0Z29vL6ls58vxPcO8/zfrdo5qvKO+d3Fx8Wu8zf1dW4p/cPzLly/dtv9Ts/EbcvGAHhHyfBIhZ6NSiIBTo0LNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiEC/wGgKKC4YMA4TAAAAABJRU5ErkJggg=='
        />
      ),
    },
    {
      title: '书籍名称',
      key: 'name',
      align: 'center',
      dataIndex: 'name',
    },
    {
      title: '作者',
      key: 'authors',
      align: 'center',
      dataIndex: 'authors',
    },
    {
      title: '创建时间',
      key: 'create_time',
      align: 'center',
      dataIndex: 'create_time',
    },
    {
      title: '更新时间',
      key: 'update_time',
      align: 'center',
      dataIndex: 'update_time',
    },
    {
      title: '操作',
      key: 'handle',
      dataIndex: 'handle',
      render: (_, { id }) => {
        return (
          <Space>
            {operationPermissionsList.includes('/books/audit/getInfoByChapterId') && (
              <Button
                onClick={() => {
                  // setShowPhone(true);
                  // setShouldPreview(true);
                  setPriviewVisible(true);
                }}
              >
                预览
              </Button>
            )}
            {operationPermissionsList.includes('/books/audit/add') && (
              <Button
                onClick={() => {
                  navigate('/books/audit/detail', {
                    state: { id },
                    replace: true, // hyy
                  });
                }}
              >
                审核
              </Button>
            )}
          </Space>
        );
      },
    },
  ];
  return (
    <div>
      <Row justify={'space-between'}>
        <Col span={21} className='form-devices-inline'>
          <Form layout='inline'>
            <Form.Item label='书籍名称'>
              <Input
                autoComplete='off'
                allowClear
                value={filterObj.name}
                onChange={(ev) => handleFilter('name', ev.target.value)}
                placeholder='请输入书籍名称'
                id='name'
              ></Input>
            </Form.Item>
            <Form.Item label='作者'>
              <Input
                autoComplete='off'
                allowClear
                value={filterObj.authors}
                onChange={(ev) => handleFilter('authors', ev.target.value)}
                placeholder='请输入作者'
                id='author'
              ></Input>
            </Form.Item>
            <Form.Item label='创建时间'>
              <RangePicker
                value={dateVal}
                onChange={(ev) => handleFilter('startandend', ev)}
                id='createTime'
              ></RangePicker>
            </Form.Item>
            <Space>
              <Button
                type='primary'
                ghost
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '11px',
                      height: '10px',
                      pointerEvents: 'none',
                    }}
                  >
                    <Image src={reset} />
                  </span>
                }
                onClick={handleReset}
              >
                重置
              </Button>
              <Button
                type='primary'
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '13px',
                      height: '12px',
                      pointerEvents: 'none',
                    }}
                  >
                    <Image src={filter} />
                  </span>
                }
                ghost
                onClick={() => {
                  setPage(1);
                  Object.values(filterObj).some((item) => item) ? init(filterObj) : init();
                }}
              >
                筛选
              </Button>
              <Button
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '10px',
                      height: '12px',
                      pointerEvents: 'none',
                    }}
                  >
                    <Image src={reload} />
                  </span>
                }
                onClick={() =>
                  Object.values(filterObj).some((item) => item) ? init(filterObj) : init()
                }
                type='primary'
                ghost
              >
                刷新
              </Button>
            </Space>
          </Form>
        </Col>
        <Col>
          <Space></Space>
        </Col>
      </Row>
      <br />
      {/* {TableCom({ columns, loading, data })} */}
      <Table
        dataSource={data}
        columns={columns}
        loading={loading}
        pagination={false}
        rowKey='id'
        onRow={(record) => ({
          onClick: () => handleRowClick(record),
        })}
      />
      <br />
      <PaginationCom
        total={total}
        page_size={page_size}
        setpage_size={setpage_size}
        page={page}
        setPage={setPage}
        filterObj={filterObj}
        init={init}
      />

      <Modal
        open={priviewVisible}
        header={null}
        footer={null}
        destroyOnClose
        keyboard={false}
        closeIcon={<CloseOutlined style={{ fontSize: 20, color: '#fff' }} />}
        maskClosable={false}
        classNames={{ body: 'phone-body', wrapper: 'phone-wrapper' }}
        wrapClassName='wrap-phone-privew'
        width='494px'
        centered
        onCancel={() => setPriviewVisible(false)}
      >
        <PreviewModal ref={previewRef} bookId={selectedId} />
      </Modal>
    </div>
  );
};

export default Audit;
