import React, { useEffect, useState } from 'react'
import useRequest from '@ahooksjs/use-request'

import { Form, Input, Modal, message } from 'antd'
import { ReactComponent as Close } from 'assets/close.svg'

import { ColumnService, IColumnInfo } from 'Column/Column.service'
import styles from '../css/ColumnInfoEdit.module.scss'

interface IColumnInfoEditProps {
  visible: boolean
  info?: IColumnInfo
  onClose: () => void
  onRefresh?: () => void
}

/**
 * 编辑专栏信息
 */
const ColumnInfoEdit: React.FC<IColumnInfoEditProps> = props => {
  const { visible, info, onClose, onRefresh } = props
  const [addLabelFlag, setAddLabelFlag] = useState<boolean>(false) // 新增标签
  const [editInfo, setEditInfo] = useState<IColumnInfo | undefined>(info) // 编辑信息
  const [addLabelValue, setAddLabelValue] = useState<string>('') // 新增标签值
  const [form] = Form.useForm()

  const { run } = useRequest(ColumnService.postUpdateAuthorDetail, {
    manual: true,
    onSuccess: res => {
      res.data.Success ? message.success('保存成功') : message.error(res.data.Msg || res.data.ErrMsg)
      res.data.Success && onRefresh && onRefresh()
      handleToClose()
    }
  })
  useEffect(() => {
    const newInfo = { ...info, showLabel: info?.Label ? info?.Label?.split(',') : [] }
    setEditInfo(newInfo as IColumnInfo)
  }, [info])

  const handleToClose = () => {
    onClose()
  }
  // 删除标签
  const handleToDeleteLabel = (item: string) => {
    const newLabel = editInfo?.showLabel?.filter((label: string) => label !== item)
    setEditInfo({ ...editInfo, showLabel: newLabel } as IColumnInfo)
  }
  const handleChangeLabel = (e: React.ChangeEvent<HTMLInputElement>) => {
    setAddLabelValue(e.target.value.replace(/\s/g, ''))
  }
  // 新增标签
  const handleAddLabel = () => {
    setAddLabelFlag(false)
    if (!addLabelValue) return
    editInfo?.showLabel?.push(addLabelValue)
    setAddLabelValue('')
  }
  const handleChangeSometthing = (key: string, e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const newInfo = { ...editInfo, [key]: e.target.value.replace(/\s/g, '') }
    setEditInfo(newInfo as IColumnInfo)
  }
  const handleToSave = () => {
    form.validateFields().then(() => {
      if (!editInfo) return
      run({
        SpecialColumnId: editInfo?.Id,
        SpecialName: editInfo?.SpecialName,
        Introduction: editInfo?.Introduction,
        Label: editInfo?.showLabel?.join(',') || '',
        NickName: editInfo?.NickName
      })
    })
  }
  const handleShowAddLabel = () => {
    setAddLabelFlag(true)
  }

  return (
    <Modal
      open={visible}
      onCancel={handleToClose}
      destroyOnClose={true}
      maskClosable={false}
      title="编辑专栏信息"
      footer={null}
    >
      <div className={styles['columneditinfo-wrapper']}>
        <Form form={form}>
          <Form.Item
            name="SpecialName"
            rules={[
              { required: true, message: '请输入专栏名称' },
              {
                pattern: /^[^\s]*$/,
                message: '禁止输入空格'
              }
            ]}
            style={{ marginBottom: 0 }}
            initialValue={editInfo?.SpecialName}
          >
            <Input
              placeholder="请输入专栏名称"
              className="columneditinfo-input"
              maxLength={12}
              required
              value={editInfo?.SpecialName}
              onChange={handleChangeSometthing.bind(this, 'SpecialName')}
            />
          </Form.Item>
          <Form.Item
            name="NickName"
            rules={[
              { required: true, message: '请输入昵称' },
              {
                pattern: /^[^\s]*$/,
                message: '禁止输入空格'
              }
            ]}
            style={{ marginBottom: 0 }}
            initialValue={editInfo?.NickName}
          >
            <Input
              placeholder="请输入昵称"
              className="columneditinfo-input"
              maxLength={12}
              required
              value={editInfo?.NickName}
              onChange={handleChangeSometthing.bind(this, 'NickName')}
            />
          </Form.Item>
          <div className="m-t-md g-flex g-flex-v-center g-flex-between">
            <div className="com-fz16 com-fw-bold">专栏标签</div>
            {(editInfo?.showLabel?.length || 0) < 6 && (
              <div className="edit-input-wrapper">
                {addLabelFlag ? (
                  <Input
                    suffix={
                      <span className="brand-blue com-cursor-p add-labal-input" onClick={handleAddLabel}>
                        确定
                      </span>
                    }
                    placeholder="请输入标签名称"
                    ref={input => {
                      input?.focus()
                    }}
                    value={addLabelValue}
                    maxLength={8}
                    onChange={handleChangeLabel}
                    onPressEnter={handleAddLabel}
                  />
                ) : (
                  <div className="brand-blue com-cursor-p" onClick={handleShowAddLabel}>
                    + &nbsp;新建标签
                  </div>
                )}
              </div>
            )}
          </div>
          <div className="m-t-sm g-flex g-flex-v-center g-flex-wap">
            {editInfo?.showLabel?.map((item: string, index: number) => (
              <div className="columnedit-labal-item brand-blue g-flex g-flex-v-center" key={index}>
                <span>{item}</span>
                <Close className="labal-delete com-cursor-p" onClick={handleToDeleteLabel.bind(this, item)} />
              </div>
            ))}
          </div>
          <Form.Item
            name="Introduction"
            rules={[
              { required: true, message: '请输入专栏介绍' },
              {
                pattern: /^[^\s]*$/,
                message: '禁止输入空格'
              }
            ]}
            style={{ marginBottom: 0 }}
            initialValue={editInfo?.Introduction}
          >
            <Input.TextArea
              placeholder="请输入专栏介绍"
              className="columneditinfo-input"
              autoSize={{ minRows: 3, maxRows: 3 }}
              maxLength={30}
              required
              value={editInfo?.Introduction}
              onChange={handleChangeSometthing.bind(this, 'Introduction')}
            />
          </Form.Item>
          <div className="columneditinfo-footer g-flex g-flex-v-center g-flex-end">
            <div onClick={handleToClose} className="columneditinfo-footer-btn">
              取消
            </div>
            <div className="columneditinfo-footer-btn primary-btn m-l-md" onClick={handleToSave}>
              保存
            </div>
          </div>
        </Form>
      </div>
    </Modal>
  )
}

export default ColumnInfoEdit
