import React, { useEffect, useState } from 'react';
import {
  Table,
  Input,
  Button,
  Row,
  Col,
  Space,
  DatePicker,
  Drawer,
  Form,
  Modal,
  Image,
} from 'antd';
const { RangePicker } = DatePicker;
import PaginationCom from '@/common/Pagination';
import './index.less';
import {
  getList,
  categoryAdd,
  getInfoById,
  categoryEdit,
  categoryDel,
  changeSort,
} from './request';
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 imports from '@/assets/images/icon/import.png';
import reload from '@/assets/images/icon/reload.png';
import TableCom from '@/common/TableCom/index';
import dayjs from 'dayjs';
import { useSelector } from 'react-redux';
const Classify = () => {
  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 [isEdit, setIsEdit] = useState(false);
  const [showModal, setShowModal] = useState(false);
  const [delMoadal, setDelModal] = useState(false);
  const [isadd, setisadd] = useState(true);
  const [form] = Form.useForm();
  const [id, setId] = useState(0);
  // 获取操作权限
  const { operationPermissionsList } = useSelector((state) => state.user);
  const [filterObj, setfilterObj] = useState({
    name: '',
    authors: '',
    status: null,
    start_time: '',
    end_time: '',
  });
  const [dateVal, setDateVal] = useState('');

  // 重置
  const handleReset = () => {
    setfilterObj({ name: '', authors: '', status: null });
    setDateVal('');
    init();
  };
  const init = async (obj = {}) => {
    setLoading(true);
    const { total, list } = await getList({ page, page_size, ...obj });
    setTotal(total);
    setData(list);
    setLoading(false);
  };

  // 过滤
  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 handleEdit = async (id) => {
    setisadd(false);
    setShowModal(true);
    const data = await getInfoById({ id });
    form.setFieldsValue(data);
    setId(id);
  };
  const onClose = () => {
    setShowModal(false);
  };
  const submitForm = async (obj) => {
    let bool;
    if (isadd) {
      bool = await categoryAdd(obj);
    } else {
      bool = await categoryEdit({
        ...obj,
        id,
      });
    }
    if (!bool) return;
    init();
    setShowModal(false);
  };
  const delSuccess = async () => {
    const bool = await categoryDel({ id });
    if (!bool) return;
    init();
    setDelModal(false);
  };
  useEffect(() => {
    if (!showModal) {
      form.setFieldsValue({ name: '', sort: '' });
    }
  }, [showModal]);

  const columns = [
    {
      title: 'ID',
      key: 'id',
      dataIndex: 'id',
      align: 'center',
    },
    {
      title: '分类名称',
      key: 'name',
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: '创建时间',
      key: 'create_time',
      dataIndex: 'create_time',
      align: 'center',
    },
    {
      title: '更新时间',
      key: 'update_time',
      dataIndex: 'update_time',
      align: 'center',
    },
    {
      title: '排序',
      key: 'sort',
      dataIndex: 'sort',
      align: 'center',
    },
    {
      title: '操作',
      key: 'handle',
      dataIndex: 'handle',
      render: (_, { id }) => {
        return (
          <Space>
            {operationPermissionsList.includes('/books/classify/getInfoById') && (
              <Button
                style={{
                  letterSpacing: '-2px', // 设置负值来减小字母之间的间距
                }}
                onClick={() => handleEdit(id)}
              >
                编辑
              </Button>
            )}
            {operationPermissionsList.includes('/books/classify/del') && (
              <Button
                style={{
                  letterSpacing: '-2px', // 设置负值来减小字母之间的间距
                }}
                onClick={() => {
                  setId(id);
                  setDelModal(true);
                }}
              >
                删除
              </Button>
            )}
          </Space>
        );
      },
    },
  ];
  return (
    <div className='classify'>
      <Row justify={'space-between'}>
        <Col span={21} className='form-devices-inline'>
          <Form layout='inline'>
            <Form.Item label='分类名称'>
              <Input
                autoComplete='off'
                allowClear
                placeholder='请输入分类名称'
                id='name'
                value={filterObj.name}
                onChange={(ev) => handleFilter('name', ev.target.value)}
              ></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>
                }
                onClick={() => {
                  setPage(1);
                  Object.values(filterObj).some((item) => item) ? init(filterObj) : init();
                }}
                ghost
              >
                筛选
              </Button>
              <Button
                type='primary'
                onClick={() =>
                  Object.values(filterObj).some((item) => item) ? init(filterObj) : init()
                }
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '10px',
                      height: '12px',
                      pointerEvents: 'none',
                    }}
                  >
                    <Image src={reload} />
                  </span>
                }
                ghost
              >
                刷新
              </Button>
            </Space>
          </Form>
        </Col>
        <Col>
          <Space>
            {operationPermissionsList.includes('/books/classify/add') && (
              <Button
                type='primary'
                ghost
                onClick={() => {
                  setIsEdit(false);
                  setShowModal(true);
                }}
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '13px',
                      height: '12px',
                      pointerEvents: 'none',
                    }}
                  >
                    <Image src={add} />
                  </span>
                }
              >
                添加
              </Button>
            )}
          </Space>
        </Col>
      </Row>
      <br />
      {TableCom({ columns, loading, data })}
      <Modal
        mask={false}
        centered
        open={delMoadal}
        onOk={delSuccess}
        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='确认'
        style={{
          position: 'absolute',
          top: '33%',
          left: '36%',
        }}
      >
        <p style={{ textAlign: 'center', padding: '30px 0 18px', fontSize: 16 }}>
          分类将永久删除，是否继续?
        </p>
      </Modal>
      <br />
      <PaginationCom
        total={total}
        page_size={page_size}
        setpage_size={setpage_size}
        page={page}
        setPage={setPage}
        init={init}
        filterObj={filterObj}
      />
      <Drawer placement='right' onClose={onClose} open={showModal} mask={false}>
        <Form form={form} onFinish={submitForm} labelCol={{ span: 6 }}>
          <Form.Item
            name='name'
            label='分类名称'
            rules={[{ required: true, message: '请输入分类名称' }]}
          >
            <Input autoComplete='off' placeholder='请输入分类名称'></Input>
          </Form.Item>
          <Form.Item name='sort' label='排序' rules={[{ required: true, message: '请输入排序' }]}>
            <Input autoComplete='off' placeholder='请输入排序'></Input>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 6, span: 16 }} style={{ textAlign: 'center' }}>
            <Space size={20}>
              {operationPermissionsList.includes('/books/classify/edit') && (
                <Button className='cancel' onClick={() => setShowModal(false)}>
                  取消
                </Button>
              )}
              {operationPermissionsList.includes('/books/classify/edit') && (
                <Button className='submit' htmlType='submit'>
                  提交
                </Button>
              )}
            </Space>
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  );
};

export default Classify;
