import { useState, useEffect } from 'react'
import { Modal, Form, Radio, Space, App } from 'antd'
import { getChapterEditors, updateChapterEditors } from '../api'

const EditChapterEditors = ({ chapter = {}, onChange, ...props }) => {
  const { message } = App.useApp()
  const [editors, setEditors] = useState([])
  const [value, setValue] = useState('')

  useEffect(() => {
    getChapterEditors({ book_id: chapter.book_id, chapter_id: chapter.id }).then((res) => {
      setEditors(res.data.editors || [])
      const value = res.data.selected_editor_ids[0] || ''
      setValue(value)
    })
  }, [chapter])

  const handleSubmit = async () => {
    await updateChapterEditors({ book_id: chapter.book_id, chapter_id: chapter.id, editor_id: value })
    message.success('设置成功')
    onChange && onChange()
  }

  return (
    <Modal title="设置章节编写者" centered {...props} onOk={handleSubmit}>
      <Form labelCol={{ span: 8 }}>
        <Form.Item label="当前章节">{chapter.title}</Form.Item>
        <Form.Item label="编写者">
          <Radio.Group value={value} onChange={(e) => setValue(e.target.value)}>
            <Space direction="vertical">
              {editors.map((item) => {
                return (
                  <Radio value={item.editor_id} key={item.editor_id}>
                    {item.real_name}({item.tel})
                  </Radio>
                )
              })}
            </Space>
          </Radio.Group>
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default EditChapterEditors
