import React, { useEffect, useState } from 'react'
import {
  Modal,
  Input,
  Button,
  Row,
  Col,
  Space,
  DatePicker,
  Drawer,
  Form,
  Select,
  Image,
  Popover,
  Result,
  Upload
} from 'antd'
const { RangePicker } = DatePicker
const { TextArea } = Input
import PaginationCom from '@/common/Pagination'
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 { useSelector } from 'react-redux'
import FormTopocModal from './components/form-drawer'
import {
  getList,
  questionAdd,
  questionInfo,
  questionEdit,
  questionDel,
  questionImport,
  questionAddType,
  typeList,
  bookNameList
} from './request'
import { uploadFiles } from '@/utils/upload'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import { DomEditor } from '@wangeditor/editor'
import { MinusOutlined, PlusOutlined } from '@ant-design/icons'
import QuestionEditr from './questionEditr/index'
import dayjs from 'dayjs'
import success from '@/assets/images/success.png'
import err from '@/assets/images/err.png'
import { downloadFile } from '@/utils/common'
import './index.less'
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) // loading
  const [showModal, setShowModal] = useState(false) //抽屉显示
  const [isadd, setisadd] = useState(false) // 是否新增
  const [delMoadal, setDelModal] = useState(false) // 删除确认
  const [dateVal, setDateVal] = useState('') // 过滤
  // 获取操作权限
  const { operationPermissionsList } = useSelector(state => state.user)
  const [form] = Form.useForm()
  const [id, setid] = useState(0)
  const [typeId, setTypeId] = useState(0)

  const [filterObj, setfilterObj] = useState({
    question_style: null,
    type_id: null,
    titles: '',
    start_time: '',
    end_time: ''
  })

  // 编辑
  const [topicData, setTopicData] = useState({})
  const handleEdit = async obj => {
    const data = await questionInfo({ id: obj.id }) // 传递题目类型的 ID
    if (data) {
      const id = data.id // 从返回的对象中提取 ID 值
      setisadd(false)
      setid(id) // 设置状态变量 id 的值
      setTypeId(data.type_id) // 设置状态变量 id 的值
      setShowModal(true)
      setTopicData(data)
    } else {
      // 处理数据获取失败的情况
      console.log('处理数据获取失败的情况')
    }
  }

  const [typeDate, setTypeDate] = useState([])
  const [bookNameData, setbookNameData] = useState([])
  const [bookIdList, setbookIdList] = useState([])

  // 题目分类
  const getTypeList = async () => {
    const { list } = await typeList({ page: 1, page_size: 999 })
    setTypeDate(list)
  }

  // 书籍名称;
  const getbookNameList = async () => {
    const res = await bookNameList({})
    const nameList = res.map(item => item.name)

    setbookNameData(nameList)
    setbookIdList(res)
  }
  useEffect(() => {
    getTypeList()
    getbookNameList()
  }, [])
  // 过滤
  const handleFilter = (flag, val) => {
    if (flag === 'newCategory') {
      setNewCategory(val)
    } else {
      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 init = async obj => {
    setLoading(true)
    const { total, list } = await getList({ page, page_size, ...obj })
    setTotal(total)
    setData(list)
    setLoading(false)
  }

  // 删除
  const delSuccess = async () => {
    const bool = await questionDel({ id })
    bool && init()
    setDelModal(false)
  }
  const handleReset = () => {
    setfilterObj({ question_style: null, type_id: null, titles: '' })
    setDateVal('')
    init()
  }

  // 控制是否显示题目分类输入框和添加和删除按钮
  const [newCategory, setNewCategory] = useState('')

  // eslint-disable-next-line no-sparse-arrays
  const columns = [
    {
      title: 'ID',
      key: 'id',
      dataIndex: 'id',
      align: 'center'
    },
    {
      title: '书籍名称',
      key: 'book_name',
      dataIndex: 'book_name',
      align: 'center',
      width: 250,
      render: text => (
        <Popover
          overlayStyle={{ maxWidth: '500px' }}
          content={
            <div className="quesName" style={{ textAlign: 'center' }} dangerouslySetInnerHTML={{ __html: text }}></div>
          }>
          <div
            className="quesName"
            style={{
              display: '-webkit-box',
              WebkitLineClamp: '3',
              WebkitBoxOrient: 'vertical',
              overflow: 'hidden',
              textOverflow: 'ellipsis'
            }}
            dangerouslySetInnerHTML={{ __html: text }}></div>
        </Popover>
      )
    },
    ,
    {
      title: '题目名称',
      key: 'titles',
      dataIndex: 'titles',
      align: 'center',
      width: 250,
      render: text => (
        <Popover
          overlayStyle={{ maxWidth: '500px' }}
          content={
            <div className="quesName" style={{ textAlign: 'center' }} dangerouslySetInnerHTML={{ __html: text }}></div>
          }>
          <div
            className="quesName"
            style={{
              display: '-webkit-box',
              WebkitLineClamp: '3',
              WebkitBoxOrient: 'vertical',
              overflow: 'hidden',
              textOverflow: 'ellipsis'
            }}
            dangerouslySetInnerHTML={{ __html: text }}></div>
        </Popover>
      )
    },
    {
      title: '题目分类',
      key: 'type_id',
      dataIndex: 'type_id',
      align: 'center',
      render(_, { type_id }) {
        let title = typeDate && typeDate.length && typeDate.find(item => item.id === type_id).typename
        return title
      }
    },
    {
      title: '题目类型',
      key: 'question_style',
      dataIndex: 'question_style',
      align: 'center',
      render(_, record) {
        switch (record.question_style) {
          case 1:
            return '单选题'
          case 2:
            return '多选题'
          case 3:
            return '判断题'
          case 4:
            return '填空题'
          case 5:
            return '简答题'
          default:
            return '-'
        }
      }
    },
    {
      title: '创建时间',
      key: 'create_time',
      dataIndex: 'create_time',
      align: 'center'
    },
    {
      title: '更新时间',
      key: 'update_time',
      dataIndex: 'update_time',
      align: 'center'
    },
    {
      title: '操作',
      key: 'handle',
      dataIndex: 'handle',
      render: (_, record) => {
        return (
          <Space>
            {operationPermissionsList.includes('/books/question-bank/getInfoById') && (
              <Button onClick={() => handleEdit(record)}>编辑</Button>
            )}
            {operationPermissionsList.includes('/books/question-bank/del') && (
              <Button
                onClick={() => {
                  setid(record.id)
                  setDelModal(true)
                }}>
                删除
              </Button>
            )}
          </Space>
        )
      }
    }
  ]
  // 上传弹框
  const [uploadModal, setUploadModal] = useState(false)
  const [form2] = Form.useForm(null)
  useEffect(() => {
    if (!uploadModal) {
      form2.resetFields()
      form2.setFieldsValue({ file: '' })
      setimportFlag(false)
      setFile(null)
    }
  }, [uploadModal])
  const UploadProps = {
    name: 'file',
    accept: '.xlsx',
    showUploadList: false,
    beforeUpload(file) {
      const suffixArr = ['xlsx']
      const suffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (!suffixArr.includes(suffix)) {
        message.error(`请上传以${suffixArr.join('、')}的敏感词文件`)
        return false
      }
      setFile(file)
      return false
    }
  }
  const [file, setFile] = useState('')
  const [importRes, setimportRes] = useState(false)
  const [importMsg, setimportMsg] = useState(false)
  const [importFlag, setimportFlag] = useState(false)
  const [importErrFile, setImportErrFile] = useState('')
  const handleUpload = async () => {
    const formData = new FormData()
    formData.append('file', file)
    const {
      data: { err, name },
      msg
    } = await questionImport(formData)
    if (err === 0) {
      setimportRes(true)
    } else {
      setimportRes(false)
      setImportErrFile(name)
    }
    setimportMsg(msg)
    setimportFlag(true)
  }
  // 下载模板
  const handleDownload = async () => {
    downloadFile('题库导入示例.xlsx')
  }

  return (
    <div className="question-bank">
      <Row justify={'space-between'}>
        <Col span={21} className="form-devices-inline">
          <Form layout="inline">
            <Form.Item label="书籍名称">
              <Select
                value={filterObj.book_id}
                onChange={ev => handleFilter('book_id', ev)}
                placeholder="请输入书籍名称"
                allowClear
                id="classify"
                style={{ width: '200px' }}
                showSearch //下拉框出现搜素,并可以输入
                optionFilterProp="children" // 使搜索匹配子节点的文本内容
              >
                {' '}
                {bookIdList &&
                  bookIdList.length &&
                  bookIdList.map((item, index) => (
                    <Select.Option key={index} value={item.book_id}>
                      {item.name}
                    </Select.Option>
                  ))}
              </Select>
            </Form.Item>
            <Form.Item label="题干名称">
              <Input
                autoComplete="off"
                allowClear
                value={filterObj.titles}
                onChange={ev => handleFilter('titles', ev.target.value)}
                placeholder="请输入题干名称"
                id="name"></Input>
            </Form.Item>
            <Form.Item label="题目分类">
              <Select
                value={filterObj.type_id}
                onChange={ev => handleFilter('type_id', ev)}
                placeholder="请选择题目分类"
                allowClear
                id="classify"
                style={{ width: '200px' }}>
                {typeDate &&
                  typeDate.length &&
                  typeDate.map(item => (
                    <Select.Option key={item.id} value={item.id}>
                      {item.typename}
                    </Select.Option>
                  ))}
              </Select>
            </Form.Item>
            <Form.Item label="题目类型">
              <Select
                value={filterObj.question_style}
                onChange={ev => handleFilter('question_style', ev)}
                placeholder="请选择题目分类"
                allowClear
                style={{ width: '200px' }}
                id="type">
                <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.Option value={5}>简答</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"
                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/question-bank/add') && (
              <Button
                type="primary"
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '13px',
                      height: '12px',
                      pointerEvents: 'none'
                    }}>
                    <Image src={add} />
                  </span>
                }
                ghost
                onClick={() => {
                  setisadd(true)
                  setShowModal(true)
                }}>
                添加
              </Button>
            )}
            {operationPermissionsList.includes('/books/question-bank/import') && (
              <Button
                type="primary"
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '11px',
                      height: '12px',
                      pointerEvents: 'none'
                    }}>
                    <Image src={imports} />
                  </span>
                }
                onClick={() => setUploadModal(true)}
                ghost>
                导入
              </Button>
            )}
          </Space>
        </Col>
      </Row>
      <br />
      <Drawer
        mask={false}
        centered
        footer={null}
        open={uploadModal}
        onCancel={() => setUploadModal(false)}
        onClose={() => setUploadModal(false)}>
        {!importFlag ? (
          <>
            <Form onFinish={handleUpload} form={form2}>
              <div style={{ paddingLeft: 75 }}>
                <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 }}>
                  1.请勿修改模板表头，防止导入失败；2.按照示例填写
                </p>
                <Form.Item
                  style={{ marginLeft: -10 }}
                  label="导入模板"
                  name="file"
                  rules={[{ required: true, message: '请选择文件' }]}>
                  <Upload {...UploadProps}>
                    <Button ghost type="primary">
                      选择文件
                    </Button>
                    <p style={{ fontSize: 12, marginTop: 8 }}>{file?.name}</p>
                  </Upload>
                </Form.Item>
              </div>
              <Form.Item>
                <Row gutter={20} justify={'center'}>
                  <Col>
                    <Button onClick={() => setUploadModal(false)}>取消</Button>
                  </Col>
                  <Col>
                    <Button type="primary" htmlType="submit">
                      确认
                    </Button>
                  </Col>
                </Row>
              </Form.Item>
            </Form>
          </>
        ) : (
          <Result
            status={importRes ? 'success' : 'error'}
            icon={<img width={60} src={importRes ? success : err} />}
            subTitle={<p style={{ color: importRes ? '#029b00' : '#aa1941' }}>{importMsg}</p>}
            extra={[
              !importRes && (
                <Button
                  type="primary"
                  key="err"
                  ghost
                  onClick={() => {
                    downloadFile(`temp/${importErrFile}`)
                  }}>
                  下载导入失败的数据
                </Button>
              ),
              <Button
                type="primary"
                key="finsh"
                onClick={() => {
                  setUploadModal(false)
                }}>
                完成
              </Button>
            ]}
          />
        )}
      </Drawer>

      <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}
        init={init}
        filterObj={filterObj}
      />
      <Drawer
        placement="right"
        destroyOnClose
        onClose={() => setShowModal(false)}
        open={showModal}
        mask={false}
        width="600px">
        <FormTopocModal
          isadd={isadd}
          typeDate={typeDate}
          bookIdList={bookIdList}
          bookNameData={bookNameData}
          getTypeList={getTypeList}
          topicData={topicData}
          init={init}
          typeId={typeId}
          setShowModal={setShowModal}
        />
      </Drawer>
    </div>
  )
}

export default Audit
