import { useState } from 'react'
import { Input, Button, Row, Col, Space, DatePicker, Image, Drawer, Form, Select, Modal, Upload, Spin } from 'antd'
const { RangePicker } = DatePicker
const { TextArea } = Input
import { useNavigate } from 'react-router-dom'
import PaginationCom from '@/common/Pagination'
import { getList, delUser, exportBook, releaseExamine, importBook } from '../request'
import { exportHtmlToWord } from '@/utils/exportWordHtmlDocx'
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 dayjs from 'dayjs'
import TableCom from '@/common/TableCom/index'
import { useSelector } from 'react-redux'
import { downloadFile } from '@/utils/common'

const Audit = () => {
  const [data, setData] = useState([])
  const navigate = useNavigate()
  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 [exportModal, setExportModal] = useState(false)
  const [importModal, setImportModal] = useState(false)
  const [bookFile, setBookFile] = useState('')
  const [showAudit, setShowAudit] = useState(false)
  const [id, setId] = useState(0)
  const [filterObj, setFilterObj] = useState({
    name: '',
    authors: '',
    audit_status: null,
    start_time: '',
    end_time: '',
  })
  const [dateVal, setDateVal] = useState('')
  // 获取操作权限
  const { operationPermissionsList } = useSelector((state) => state.user)
  const { userInfo } = useSelector((state) => state.user)
  // 重置
  const handleReset = () => {
    setFilterObj({ name: '', authors: '', audit_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 delSuccess = async () => {
    const bool = await delUser({ id })
    bool && init()
    setDelModal(false)
  }
  const exportSuccess = async () => {
    setExportModal(false)
    setLoading(true)
    try {
      const { name, content } = await exportBook({ id })
      if (!name) return

      await exportHtmlToWord(name, content, [
        '.chapter-gallery-container',
        '.chapter-expand',
        '.chapter-practice',
        '.chapter-item-link',
        '.chapter-item-tooltip',
        "div[data-w-e-type='video']",
      ])
    } catch (e) {
      console.error('导出Word失败', e)
    } finally {
      setLoading(false)
    }
  }
  const importSuccess = async (obj) => {
    setUploading(true)
    const bool = await importBook({ ...obj, file: bookFile })
    // if (!bool)   return;
    if (bool) {
      window.location.replace(window.location.href)
    }
    setImportModal(false)
    setUploading(false)
  }

  const UploadProps = {
    name: 'file',
    accept: '.doc , .docx',
    showUploadList: false,
    beforeUpload(file) {
      const suffixArr = ['doc', 'docx']
      const suffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (!suffixArr.includes(suffix)) {
        message.error(`请上传以${suffixArr.join('、')}格式的书籍`)
        return false
      }
      setBookFile(file)
      return false
    },
  }
  const handleReleaseExamine = async (obj) => {
    const bool = await releaseExamine({ ...obj, id })
    if (bool) {
      window.location.replace(window.location.href) // 几乎完美
    }

    if (!bool) return
    setShowAudit(false)
    init()
  }
  // 下载模板
  const handleDownload = async () => {
    downloadFile('书籍导入示例.docx')
  }

  const [uploading, setUploading] = useState(false)
  const columns = [
    {
      title: '书籍名称',
      key: 'name',
      align: 'center',
      dataIndex: 'name',
    },
    {
      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/ARuCRABEFAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmB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hm7DekRYKQPZF2ArbXTAyu4kDYB2YxUzwg0gi/41ztHnfQG26HbGel/crVrm7tNY+/1btkOEAZ2M05r4FB7r9GbAIdxaZYrHdOsgJ/wCEQY0J74TmOKnbxxT9n3FgGGWWsVdowHtjt9Nnvf7yQM2aZU/TIAIAxrw6dOnAWtZZcoEnBpNuTuObWMEiLAx1HY0ZQJEmHJ3HNvGCBBhY6jtaMoEiJB0Z29vL6ls58vxPcO8/zfrdo5qvKO+d3Fx8Wu8zf1dW4p/cPzLly/dtv9Ts/EbcvGAHhHyfBIhZ6NSiIBTo0LNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiEC/wGgKKC4YMA4TAAAAABJRU5ErkJggg=="
        />
      ),
    },
    {
      title: '作者',
      key: 'authors',
      align: 'center',
      dataIndex: 'authors',
    },
    {
      title: '审核状态',
      key: 'audit_status',
      align: 'center',
      dataIndex: 'audit_status',
      render: (_, { audit_status }) => {
        switch (audit_status) {
          case 1:
            return (
              <Button type="link" style={{ color: '#000', cursor: 'initial' }}>
                待发布
              </Button>
            )
          case 2:
            return (
              <Button type="link" style={{ color: '#000', cursor: 'initial' }}>
                审核中
              </Button>
            )
          case 3:
            return (
              <Button type="link" style={{ cursor: 'initial' }} danger>
                审核未通过
              </Button>
            )
          case 4:
            return (
              <Button type="link" style={{ color: '#000', cursor: 'initial' }}>
                审核通过
              </Button>
            )
        }
      },
    },
    {
      title: '发布次数',
      key: 'release_num',
      dataIndex: 'release_num',
      width: 150,
      align: 'center',
    },
    {
      title: '创建时间',
      key: 'create_time',
      align: 'center',
      dataIndex: 'create_time',
    },
    {
      title: '更新时间',
      key: 'update_time',
      align: 'center',
      dataIndex: 'update_time',
    },
    {
      title: '操作',
      key: 'handle',
      dataIndex: 'handle',
      width: 400,
      render: (_, { audit_status, id, user_id }) => {
        // 审核中
        // if (audit_status === 2) return
        // 创建者或者管理员
        const isAdminOrCreator = userInfo.id === user_id || userInfo.type === 1
        return (
          <Space>
            {isAdminOrCreator && operationPermissionsList.includes('/books/management/getAllList') && (
              <Button
                onClick={() => {
                  navigate('/books/management/add-edit', { state: { id: id } })
                }}
                type="primary"
                ghost>
                基本信息
              </Button>
            )}

            {operationPermissionsList.includes('/books/management/getInfoById') && (
              <Button
                onClick={() => {
                  navigate('/books/management/chapter', { state: { id, isAdminOrCreator: isAdminOrCreator } })
                }}>
                编辑
              </Button>
            )}

            {isAdminOrCreator && operationPermissionsList.includes('/books/management/export') && (
              <Button
                onClick={() => {
                  setId(id)
                  setExportModal(true)
                }}>
                导出
              </Button>
            )}

            {isAdminOrCreator && operationPermissionsList.includes('/books/management/del') && (
              <Button
                onClick={() => {
                  setId(id)
                  setDelModal(true)
                }}>
                删除
              </Button>
            )}

            {isAdminOrCreator &&
              operationPermissionsList.includes('/books/management/release') &&
              audit_status === 1 && (
                <Button
                  onClick={() => {
                    setId(id)
                    setShowAudit(true)
                  }}>
                  发布审核
                </Button>
              )}
          </Space>
        )
      },
    },
  ]
  return (
    <>
      <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
                style={{ width: 160 }}
                allowClear
                value={filterObj.audit_status}
                onChange={(ev) => handleFilter('audit_status', ev)}
                placeholder="请选择审核状态"
                id="status">
                <Select.Option value="1">待发布</Select.Option>
                <Select.Option value="2">审核中</Select.Option>
                <Select.Option value="3">审核未通过</Select.Option>
                <Select.Option value="4">审核通过</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={flag}
                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)
                  console.log(filterObj)
                  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 span={2} style={{ marginLeft: 20, display: 'flex', justifyContent: 'flex-end' }}>
          <Space>
            {operationPermissionsList.includes('/books/management/import') && (
              <Button
                type="primary"
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '11px',
                      height: '12px',
                      pointerEvents: 'none',
                    }}>
                    <Image src={imports} />
                  </span>
                }
                ghost
                onClick={() => setImportModal(true)}>
                导入
              </Button>
            )}
            {operationPermissionsList.includes('/books/management/add') && (
              <Button
                type="primary"
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '13px',
                      height: '12px',
                      pointerEvents: 'none',
                    }}>
                    <Image src={add} />
                  </span>
                }
                ghost
                onClick={() => navigate('/books/management/add-edit')}>
                添加
              </Button>
            )}
          </Space>
        </Col>
      </Row>
      <Modal
        mask={false}
        centered
        open={delModal}
        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="确认"
        ghost>
        <p style={{ textAlign: 'center', padding: '30px 0 18px', fontSize: 16 }}>确认删除书籍？</p>
      </Modal>
      <Modal
        mask={false}
        centered
        open={exportModal}
        onOk={exportSuccess}
        onCancel={() => setExportModal(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 }}>
          只能导出文本部分，画廊、音频、视频不支持
        </p>
      </Modal>
      <Drawer
        mask={false}
        centered
        open={importModal}
        onCancel={() => setImportModal(false)}
        onClose={() => setImportModal(false)}
        footer={null}
        okText="确认">
        <Spin spinning={uploading}>
          <Form labelCol={{ span: 8 }} onFinish={importSuccess}>
            <Form.Item label="下载模板" style={{ marginBottom: 10 }}>
              <Button ghost type="primary" onClick={handleDownload}>
                下载模板
              </Button>
            </Form.Item>
            <p
              className="linetext"
              style={{
                fontWeight: 400,
                color: '#999999',
                fontSize: 12,
                marginBottom: 30,
                paddingLeft: 75,
              }}>
              目录需设置为word中的标题样式或按照示例编写,防止导入失败
            </p>
            <Form.Item label="选择书籍" required>
              <Form.Item name="file" rules={[{ required: true, message: '请上传书籍' }]} noStyle>
                <Upload {...UploadProps}>
                  <Button>点击上传</Button>
                </Upload>
              </Form.Item>
              <p style={{ color: '#999999' }}>{bookFile?.name}</p>
            </Form.Item>

            <Form.Item
              label="目录结构等级"
              name="catalog_level"
              rules={[{ required: true, message: '请选择目录结构等级' }]}>
              <Select placeholder="请选择目录结构的等级" style={{ width: 260 }}>
                <Select.Option value={1}>标题1</Select.Option>
                <Select.Option value={2}>标题2</Select.Option>
                <Select.Option value={3}>标题3</Select.Option>
                <Select.Option value={4}>标题4</Select.Option>
                <Select.Option value={5}>标题5</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item>
              <Row justify={'center'} className="delModal" style={{ marginBottom: '30px', marginTop: '0px' }}>
                <Space size={20}>
                  <Button onClick={() => setImportModal(false)}>取消</Button>
                  <Button type="primary" htmlType="submit">
                    确认
                  </Button>
                </Space>
              </Row>
            </Form.Item>
          </Form>
        </Spin>
      </Drawer>
      <Drawer placement="right" onClose={() => setShowAudit(false)} open={showAudit} mask={false}>
        <Form labelCol={{ span: 5 }} onFinish={handleReleaseExamine}>
          <Form.Item label="发布信息" name="release_mess" rules={[{ max: 255, message: '最大255字符' }]}>
            <TextArea
              placeholder="请输入发布信息"
              autoSize={{
                minRows: 5,
                maxRows: 8,
              }}
            />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 10, span: 16 }}>
            <Space size={20}>
              <Button
                onClick={() => {
                  setShowAudit(false)
                }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                发布
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Drawer>
      <br />
      {TableCom({ columns, loading, data })}
      <br />
      <PaginationCom
        total={total}
        page_size={page_size}
        setpage_size={setpage_size}
        page={page}
        setPage={setPage}
        init={init}
        filterObj={filterObj}
      />
    </>
  )
}

export default Audit
