import React, { useEffect, useState } from 'react'
import { Table, Input, Button, Row, Col, Space, DatePicker, Image, Drawer, Form, Select, Modal } from 'antd'
const { RangePicker } = DatePicker
import { useNavigate } from 'react-router-dom'
import PaginationCom from '@/common/Pagination'
import { getList, changeStatus } from './request'
import reset from '@/assets/images/icon/reset.png'
import filter from '@/assets/images/icon/filter.png'
import reload from '@/assets/images/icon/reload.png'

import add from '@/assets/images/icon/add.png'
import imports from '@/assets/images/icon/import.png'
import TableCom from '@/common/TableCom/index'
import dayjs from 'dayjs'
import { useSelector } from 'react-redux'
const Audit = () => {
  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 navigate = useNavigate()
  // 是否上架
  const [isShelf, setIsShelf] = useState(true)
  const [showShelf, setShowShelf] = useState(false)
  // 获取操作权限
  const { operationPermissionsList } = useSelector(state => state.user)
  const [form] = Form.useForm()
  const [id, setId] = useState(0)
  const [filterObj, setfilterObj] = useState({
    name: '',
    authors: '',
    status: null,
    start_time: '',
    end_time: ''
  })
  const [dateVal, setDateVal] = useState('')
  // 重置
  const handleReset = () => {
    setfilterObj({ name: '', authors: '', audit_status: '1' })
    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 onClose = () => {
    setIsEdit(false)
  }
  const submitForm = obj => {
    console.log(obj)
  }
  const shelfSuccess = async () => {
    const bool = await changeStatus({ id, status: isShelf ? '0' : '1' })
    setShowShelf(false)
    if (!bool) return
    init()
  }
  // 将 0 转换成 "下架"，将 1 转换成 "上架"
  const renderStatus = status => {
    return status === 0 ? '下架' : status === 1 ? '上架' : ''
  }
  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/HnAAAHlklEQVR4Ae3dP3PTWBSGcbGzM6GCKqlIBRV0dHRJFarQ0eU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Qs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiEC/wGgKKC4YMA4TAAAAABJRU5ErkJggg=="
        />
      )
    },
    {
      title: '书籍名称',
      key: 'name',
      dataIndex: 'name',
      align: 'center'
    },
    {
      title: '作者',
      key: 'authors',
      dataIndex: 'authors',
      align: 'center'
    },
    {
      title: '类型',
      key: 'status',
      dataIndex: 'status',
      align: 'center',
      render: (text, record) => renderStatus(text)
    },
    {
      title: '零售价',
      key: 'price',
      dataIndex: 'price',
      align: 'center'
    },
    {
      title: '会员价',
      key: 'vip_price',
      align: 'center',
      dataIndex: 'vip_price'
    },
    {
      title: '创建时间',
      key: 'create_time',
      dataIndex: 'create_time',
      align: 'center'
    },
    {
      title: '上架时间',
      key: 'onsale_time',
      dataIndex: 'onsale_time',
      align: 'center',

      render: (_, record) => {
        switch (record.onsale_time) {
          case 0:
            return '--'

          default:
            return record.onsale_time
        }
      }
    },
    {
      title: '下架时间',
      key: 'offshelves_time',
      dataIndex: 'offshelves_time',
      align: 'center',
      render: (_, record) => {
        switch (record.offshelves_time) {
          case 0:
            return '--'

          default:
            return record.offshelves_time
        }
      }
    },
    // {
    //   title: '操作',
    //   key: 'handle',
    //   dataIndex: 'handle',
    //   render: (_, { status, id, name }) => {
    //     let txt = status ? '下架' : '上架';
    //     return (
    //       <Space size={8}>
    //         {status ? (
    //           <Button
    //             onClick={() => {
    //               navigate('/books/sale/discussP', {
    //                 state: { id, name },
    //               });
    //             }}
    //           >
    //             讨论
    //           </Button>
    //         ) : (
    //           ''
    //         )}
    //         {!status ? (
    //           <Button
    //             onClick={() => {
    //               navigate('/books/sale/detail', {
    //                 state: { id },
    //               });
    //             }}
    //           >
    //             编辑
    //           </Button>
    //         ) : (
    //           ''
    //         )}
    //         <Button
    //           onClick={() => {
    //             setId(id);
    //             setIsShelf(status);
    //             setShowShelf(true);
    //           }}
    //         >
    //           {txt}
    //         </Button>
    //       </Space>
    //     );
    //   },
    // },
    {
      title: '操作',
      key: 'handle',
      dataIndex: 'handle',
      render: (_, { status, id, name }) => {
        let txt = status ? '下架' : '上架'
        const buttons = [] // 定义一个空数组，用于存储需要渲染的按钮

        if (status && operationPermissionsList.includes('/books/sale/getCommentList')) {
          // 当商品状态为下架时
          buttons.push(
            // 将 "讨论" 按钮添加到数组中
            <Button
              key="discuss"
              onClick={() => {
                navigate('/books/sale/discussP', {
                  state: { id, name }
                })
              }}>
              讨论
            </Button>
          )
        } else if (operationPermissionsList.includes('/books/sale/getInfoById')) {
          // 当商品状态为上架时
          buttons.push(
            // 将 "编辑" 按钮添加到数组中
            <Button
              key="edit"
              onClick={() => {
                navigate('/books/sale/detail', {
                  state: { id }
                })
              }}>
              编辑
            </Button>
          )
        }

        if (operationPermissionsList.includes('/books/sale/changeStatus')) {
          // 将 "下架" 按钮添加到数组中
          buttons.push(
            <Button
              key="shelf"
              onClick={() => {
                setId(id)
                setIsShelf(status)
                setShowShelf(true)
              }}>
              {txt}
            </Button>
          )
        }

        return <Space size={8}>{buttons}</Space> // 将所有按钮包装在一个 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="上架状态">
              <Select
                value={filterObj.status}
                onChange={ev => handleFilter('status', ev)}
                placeholder="请选择上架状态"
                id="status"
                allowClear
                style={{ width: 200 }}>
                <Select.Option value={1}>上架</Select.Option>
                <Select.Option value={'0'}>下架</Select.Option>
              </Select>
            </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"
                ghost
                onClick={() => {
                  setPage(1)
                  Object.values(filterObj).some(item => item) ? init(filterObj) : init()
                }}
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '13px',
                      height: '12px',
                      pointerEvents: 'none'
                    }}>
                    <Image src={filter} />
                  </span>
                }>
                筛选
              </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 span={1}> </Col>
      </Row>
      <br />
      <Modal
        mask={false}
        centered
        open={showShelf}
        onOk={shelfSuccess}
        onCancel={() => setShowShelf(false)}
        footer={(_, { OkBtn, CancelBtn }) => {
          return (
            <Row justify={'center'} className="delModal" style={{ marginBottom: '30px' }}>
              <Space size={20}>
                <CancelBtn />
                <OkBtn />
              </Space>
            </Row>
          )
        }}
        okText="确认">
        <p style={{ textAlign: 'center', padding: '30px 0 18px', fontSize: 16 }}>
          书籍将{isShelf ? '下架' : '上架'}，是否继续？
        </p>
      </Modal>
      {TableCom({ columns, loading, data })}
      <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={isEdit} mask={false}>
        <Form form={form} onFinish={submitForm} labelCol={{ span: 5 }}>
          <Form.Item label="分类名称" rules={[{ required: true, message: '请输入分类名称' }]}>
            <Input autoComplete="off" placeholder="请输入分类名称"></Input>
          </Form.Item>
          <Form.Item label="排序" rules={[{ required: true, message: '请输入排序' }]}>
            <Input autoComplete="off" placeholder="请输入排序"></Input>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 5, span: 16 }} style={{ textAlign: 'center' }}>
            <Space>
              <Button>取消</Button>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  )
}

export default Audit
