import React, { useEffect, useState } from 'react';
import {
  Table,
  Input,
  Button,
  Row,
  Col,
  Space,
  DatePicker,
  Popover,
  Modal,
  Form,
  Image,
} from 'antd';
const { RangePicker } = DatePicker;
import PaginationCom from '@/common/Pagination';
import { getList, delHelp } from './requet';
import { useNavigate } from 'react-router-dom';
import Add from '@/assets/images/icon/add.png';
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 dayjs from 'dayjs';
import TableCom from '@/common/TableCom/index';
import { useSelector } from 'react-redux';
const HelpTable = () => {
  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 [loading, setLoading] = useState(true);
  const [delModal, setDelModal] = useState(false);
  const [delid, setdelid] = useState(0);
  const [form] = Form.useForm();
  // 获取操作权限
  const { operationPermissionsList } = useSelector((state) => state.user);
  const [filterObj, setFilterObj] = useState({
    help_title: '',
    start_time: '',
    end_time: '',
  });
  const [dateVal, setDateVal] = useState('');

  const handleReset = () => {
    setFilterObj({
      help_title: '',
      start_time: '',
      end_time: '',
    });

    setDateVal('');

    init();
  };

  // useEffect(() => {
  //   init();
  // }, []);

  // 过滤
  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 handleDel = async (id) => {
    const bool = await delHelp({ id: delid });
    bool && init();
    setDelModal(false);
  };
  // 获取数据
  const init = async (obj = {}) => {
    setLoading(true);
    let requestParams = { page, page_size, ...obj };
    if (obj.start_time && obj.end_time) {
      const start_time = parseInt(obj.start_time);
      const end_time = parseInt(obj.end_time);
      requestParams = { ...requestParams, start_time, end_time };
    }
    const { total, list } = await getList(requestParams);
    console.log('init list', list);
    setTotal(total);
    setData(list);
    setLoading(false);
  };

  const columns = [
    {
      title: 'ID',
      key: 'id',
      dataIndex: 'id',
      align: 'center',
    },
    {
      title: '问题名称',
      key: 'help_title',
      dataIndex: 'help_title',
      align: 'center',
      width: 200,
      render: (text) => (
        <Popover content={text} overlayStyle={{ maxWidth: '400px' }}>
          <div
            style={{
              display: '-webkit-box',
              WebkitLineClamp: '2',
              WebkitBoxOrient: 'vertical',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              textAlign: 'center',
            }}
          >
            {text}
          </div>
        </Popover>
      ),
    },
    {
      title: '创建时间',
      key: 'create_time',
      dataIndex: 'create_time',
      align: 'center',
    },
    {
      title: '操作',
      key: 'handle',
      dataIndex: 'handle',
      align: 'center',
      render: (_, record) => {
        return (
          <Space>
            {operationPermissionsList.includes('/setting/help/getInfoById') && (
              <Button
                onClick={() => {
                  navigate('/setting/help/addedit', {
                    state: { id: record.id },
                  });
                }}
              >
                编辑
              </Button>
            )}
            {operationPermissionsList.includes('/setting/help/del') && (
              <Button
                onClick={() => {
                  setdelid(record.id);
                  setDelModal(true);
                }}
              >
                删除
              </Button>
            )}
          </Space>
        );
      },
    },
  ];
  return (
    <div>
      <Row justify={'space-between'}>
        <Col className='form-devices-inline'>
          <Form layout='inline'>
            <Form.Item label='问题名称'>
              <Input
                autoComplete='off'
                allowClear
                placeholder='请输入问题名称'
                id='name'
                value={filterObj.help_title}
                onChange={(ev) => handleFilter('help_title', ev.target.value)}
              ></Input>
            </Form.Item>
            <Form.Item label='创建时间'>
              <RangePicker
                id='createTime'
                value={dateVal}
                onChange={(ev) => handleFilter('startandend', ev)}
              ></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
                type='primary'
                ghost
                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()
                }
              >
                刷新
              </Button>
            </Space>
          </Form>
        </Col>
        <Col>
          <Space>
            {operationPermissionsList.includes('/setting/help/add') && (
              <Button
                type='primary'
                ghost
                onClick={() => {
                  navigate('/setting/help/addedit');
                }}
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '13px',
                      height: '12px',
                      pointerEvents: 'none',
                    }}
                  >
                    <Image src={Add} />
                  </span>
                }
              >
                添加
              </Button>
            )}
          </Space>
        </Col>
      </Row>
      <br />
      <Modal
        mask={false}
        centered
        open={delModal}
        onOk={handleDel}
        onCancel={() => setDelModal(false)}
        footer={(_, { OkBtn, CancelBtn }) => {
          return (
            <Row justify={'center'} className='delModal' style={{ marginBottom: '30px' }}>
              <Space size={20}>
                <CancelBtn className='cancel' />
                <OkBtn className='true' />
              </Space>
            </Row>
          );
        }}
        okText='确认'
      >
        <p style={{ textAlign: 'center', padding: '30px 0 18px', fontSize: 16 }}>
          问题将永久删除，是否继续?
        </p>
      </Modal>
      {TableCom({ loading, data, columns })}
      <br />
      <PaginationCom
        total={total}
        init={init}
        page={page}
        page_size={page_size}
        setPage={setPage}
        setpage_size={setpage_size}
        filterObj={filterObj}
      />
    </div>
  );
};

export default HelpTable;
