import React, { useEffect, useState, useRef } from 'react'
import {
  Table,
  Input,
  Button,
  Row,
  Col,
  Space,
  DatePicker,
  Pagination,
  Drawer,
  Form,
  Modal,
  Switch,
  Image,
  Select,
  Radio
} from 'antd'
const { RangePicker } = DatePicker
import { useNavigate } from 'react-router-dom'
import PaginationCom from '@/common/Pagination/index.jsx'
import { getList, changeStatus, delComment, getSystem, systemEdit, getBooklist } from './requset'
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 TableCom from '@/common/TableCom/index'
import { getList as getBooks } from '../management/request'
import { useSelector } from 'react-redux'
import dayjs from 'dayjs'
const Discuss = () => {
  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 [isEdit, setIsEdit] = useState(false)
  const [delMoadal, setDelModal] = useState(false)
  const [form] = Form.useForm()
  const [form1] = Form.useForm()
  const [books, setBooks] = useState([])
  // 获取操作权限
  const { operationPermissionsList } = useSelector(state => state.user)
  const [filterObj, setfilterObj] = useState({
    book_id: null,
    title: '',
    start_time: '',
    end_time: ''
  })
  const [id, setId] = useState(0)
  const [dateVal, setDateVal] = useState('')
  const [isEditValidity, setIsEditValidity] = useState(false)
  const [isAdd, setIsAdd] = useState(false)
  const flag = useRef(true)

  // 过滤
  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)
    // else init({ ...filterObj, book_id: val }); // 在此处传入包含 book_id 的 filterObj,hyy
  }
  //改变状态
  const changeState = async obj => {
    let status = obj.status === 1 ? 2 : 1
    const bool = await changeStatus({ ...obj, status, book_id: filterObj.book_id })
    let obj2 = { ...filterObj }
    for (let key in obj2) {
      if (!obj2[key]) {
        delete obj2[key]
      }
    }
    bool && init(obj2)
  }
  // 重置
  const handleReset = () => {
    setfilterObj({ title: '', book_id: books[0].id })
    setDateVal('')
    init({ book_id: books[0].id })
  }
  // 获取书籍名称
  const getBookOption = async () => {
    const res = await getBooklist()
    filterObj.book_id = res[0].id
    setfilterObj(filterObj)
    setBooks(res)

    return res[0].id
  }
  const init = async (obj = {}) => {
    setLoading(true)
    let bookid
    if (flag.current) {
      bookid = await getBookOption()
      flag.current = false
    }
    const { total, list } = await getList({
      page,
      page_size,
      book_id: bookid,
      ...obj
    })
    setTotal(total)
    setData(list)
    setLoading(false)
  }
  const onClose = () => {
    setIsEdit(false)
  }
  const submitForm = obj => {
    console.log(obj)
  }
  const delSuccess = async () => {
    const bool = await delComment({ id, book_id: filterObj.book_id })
    if (!bool) return
    init(filterObj)
    setDelModal(false)
  }

  // 获取信息
  const getInfo = async () => {
    const data = await getSystem({ type: 3 })
    console.log('data', data)
    form1.setFieldsValue({
      set_value: data.set_value
    })
  }
  // 设置个性化信息
  const handleSystemEdit = async values => {
    const { set_value } = values // 获取输入框的内容
    const data = { type: 3, set_value } // 构造传递给systemEdit的参数对象
    const bool = await systemEdit(data)
    console.log('bool', bool)
    bool && getInfo()
  }
  useEffect(() => {
    if (operationPermissionsList.includes('/books/discussion/getSystem')) {
      getInfo()
    }
  }, [operationPermissionsList])

  const columns = [
    {
      title: 'ID',
      key: 'id',
      dataIndex: 'id',
      align: 'center'
    },
    {
      title: '书籍名称',
      key: 'name',
      dataIndex: 'name',
      align: 'center'
    },
    {
      title: '话题',
      key: 'title',
      dataIndex: 'title',
      align: 'center',
      width: 200
    },
    {
      title: '讨论人',
      key: 'person_name',
      dataIndex: 'person_name',
      align: 'center'
    },
    {
      title: '讨论时间',
      key: 'create_time',
      dataIndex: 'create_time',
      align: 'center'
    },
    {
      title: '讨论内容',
      key: 'content',
      dataIndex: 'content',
      align: 'center',
      render: contentList => {
        // 如果contentList不存在或者为空，则返回null或自定义提示
        if (!contentList || contentList.length === 0) {
          return <span>暂无内容</span>
        }

        return contentList.map((item, index) => {
          const type = item.types
          const value = item.content

          if (type === 'audio') {
            return (
              <div key={index}>
                <span>
                  <audio controls>
                    <source src={value} type="audio/mp3" />
                    Your browser does not support the audio element.
                  </audio>
                </span>
              </div>
            )
          } else if (type === 'text') {
            return <span key={index}>{value}</span>
          } else if (type === 'image') {
            // return <img height={100} src={value}></img>;
            return (
              <Image
                height={100}
                src={value}
                fallback="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMIAAADDCAYAAADQvc6UAAABRWlDQ1BJQ0MgUHJvZmlsZQAAKJFjYGASSSwoyGFhYGDIzSspCnJ3UoiIjFJgf8LAwSDCIMogwMCcmFxc4BgQ4ANUwgCjUcG3awyMIPqyLsis7PPOq3QdDFcvjV3jOD1boQVTPQrgSkktTgbSf4A4LbmgqISBgTEFyFYuLykAsTuAbJEioKOA7DkgdjqEvQHEToKwj4DVhAQ5A9k3gGyB5IxEoBmML4BsnSQk8XQkNtReEOBxcfXxUQg1Mjc0dyHgXNJBSWpFCYh2zi+oLMpMzyhRcASGUqqCZ16yno6CkYGRAQMDKMwhqj/fAIcloxgHQqxAjIHBEugw5sUIsSQpBobtQPdLciLEVJYzMPBHMDBsayhILEqEO4DxG0txmrERhM29nYGBddr//5/DGRjYNRkY/l7////39v///y4Dmn+LgeHANwDrkl1AuO+pmgAAADhlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAAAwqADAAQAAAABAAAA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TbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiEC/wGgKKC4YMA4TAAAAABJRU5ErkJggg=="
              />
            )
          } else {
            return <span key={index}>其他类型</span>
          }
        })
      }
    },

    {
      title: '审核',
      key: 'status',
      dataIndex: 'status',
      align: 'center',
      render(_, { status, id }) {
        let bool = status == 1 ? true : false
        return <Switch checked={bool} onChange={() => changeState({ status, id })} />
      }
    },
    {
      title: '操作',
      key: 'handle',
      dataIndex: 'handle',
      align: 'center',
      render: (_, { id }) => {
        return (
          <Space>
            {operationPermissionsList.includes('/books/discussion/delComment') && (
              <Button
                onClick={() => {
                  setDelModal(true)
                  setId(id)
                }}
                style={{
                  letterSpacing: '-2px' // 设置负值来减小字母之间的间距
                }}>
                删除
              </Button>
            )}
          </Space>
        )
      }
    }
  ]
  return (
    <div>
      <Row justify={'space-between'}>
        <Col className="form-devices-inline">
          <Form layout="inline">
            <Form.Item label="书籍名称">
              <Select
                showSearch //下拉框出现搜素,并可以输入
                optionFilterProp="children" // 使搜索匹配子节点的文本内容
                value={filterObj.book_id}
                onChange={ev => handleFilter('book_id', ev)}
                placeholder="请选择书籍名称"
                autoComplete="off"
                style={{ width: 160 }}
                id="name">
                {books &&
                  books.map(item => (
                    <Select.Option value={item.id} key={item.id}>
                      {item.name}
                    </Select.Option>
                  ))}
              </Select>
            </Form.Item>
            <Form.Item label="话题">
              <Input
                value={filterObj.title}
                onChange={ev => handleFilter('title', ev.target.value)}
                autoComplete="off"
                placeholder="请输入话题"
                allowClear
                id="title"></Input>
            </Form.Item>
            <Form.Item label="讨论时间">
              <RangePicker
                value={dateVal}
                allowClear
                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>
                }
                type="primary"
                ghost
                onClick={() => (Object.values(filterObj).some(item => item) ? init(filterObj) : init())}>
                刷新
              </Button>
            </Space>
          </Form>
        </Col>
        <Col>
          <Space>
            {operationPermissionsList.includes('/books/discussion/getSystem') && (
              <Button
                type="primary"
                ghost
                onClick={() => {
                  setIsAdd(true)
                  setIsEditValidity(true)
                }}>
                审核设置
              </Button>
            )}
          </Space>
        </Col>
      </Row>
      <br />
      <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 />
                <OkBtn />
              </Space>
            </Row>
          )
        }}
        okText="确认">
        <p style={{ textAlign: 'center', padding: '30px 0 6px', fontSize: 16 }}>讨论将永久删除，是否继续?</p>
      </Modal>
      {TableCom({ columns, loading, data })}
      <br />
      <PaginationCom
        total={total}
        page_size={page_size}
        setpage_size={setpage_size}
        page={page}
        setPage={setPage}
        filterObj={filterObj}
        init={init}
      />
      <Drawer placement="right" onClose={onClose} open={isEdit} mask={false}>
        <Form form={form} onFinish={submitForm} labelCol={{ span: 6 }}>
          <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: 6, span: 16 }} style={{ textAlign: 'center' }}>
            <Space>
              <Button>取消</Button>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Drawer>

      <Drawer
        onClose={() => setIsEditValidity(false)}
        open={isEditValidity}
        footer={null}
        mask={false}
        keyboard={false}
        onCancel={() => setIsEditValidity(false)}>
        <Form form={form1} onFinish={handleSystemEdit}>
          <Form.Item name="set_value" label="评论是否需要审核" labelCol={{ span: 12 }} wrapperCol={{ span: 16 }}>
            <Radio.Group style={{ textAlign: 'center' }}>
              <Radio value={'1'}>是</Radio>
              <Radio value={'0'}>否</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 26 }}>
            <Space size={20}>
              <Button onClick={() => setIsEditValidity(false)}>取消</Button>
              <Button type="primary" htmlType="submit" onClick={() => setIsEditValidity(false)}>
                提交
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  )
}

export default Discuss
