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

import { Checkbox, Drawer, Modal, Tabs, TabsProps, message, Button, Form, Input, Row } from 'antd'
import { ReactComponent as Close } from 'assets/close.svg'
import { ColumnService, IMessageDetail } from 'Column/Column.service'
import styles from '../css/ColumnIndex.module.scss'

import { CheckboxValueType } from 'antd/lib/checkbox/Group'

const { Item } = Form
interface IColumnCenterProps {
  open: boolean // 是否打开
  onClose: (type: 'editInfo' | 'openCenter' | 'openMessage') => void // 关闭
}

/**研选专栏 留言管理 */
const ColumnMessage: React.FC<IColumnCenterProps> = props => {
  const { open } = props
  const pageSize = 10
  const currentIndex = 1
  const [messageList, setMessageList] = useState<IMessageDetail[]>([]) // 列表
  const [selectCheckbox, setSelectCheckbox] = useState<(string | number)[]>([]) // 选择Id
  const [msgTextVisible, setMsgTextVisible] = useState<boolean>(false) // 选择Id
  const [replyItemID, setReplyItemID] = useState<number>(0) // 选择Id
  const [replyParentId, setReplyreplyParentId] = useState<number>(0) // 选择Id
  const [tabsAct, setTabsAct] = useState<number>(1) // 选择Id
  const [form] = Form.useForm()
  useEffect(() => {
    console.log(11)
    if (open) {
      getColumnManageList(pageSize, currentIndex, tabsAct)
    }
  }, [open])

  // 列表
  const { run: getColumnManageList } = useRequest(ColumnService.getColumnManageList, {
    manual: true,
    formatResult: response => response.data.Data,
    onSuccess: res => {
      console.log(res)

      setMessageList(res.List)
    }
  })

  // 多选框的选择事件
  const checkboxChange = (e: CheckboxValueType[], item: IMessageDetail) => {
    const updatedMessage = messageList.map(msg => {
      if (item.MessageId === msg.MessageId) {
        if (e.length > 0 && item.CheckIds.length === 0) {
          const arr = []
          arr.push(item.MessageId)
          item.ChildList.forEach(child => {
            arr.push(child.MessageId)
          })
          return { ...msg, CheckIds: arr }
        } else {
          return { ...msg, CheckIds: [] }
        }
      } else {
        return msg
      }
    })
    let arr: number[] = []

    updatedMessage.forEach(_ => {
      arr = [...arr, ..._.CheckIds]
    })
    setSelectCheckbox(arr)
    setMessageList(updatedMessage)
  }

  // 设置共开的按钮点击事件
  const setupClickHandler = () => {
    postMessagePublic(selectCheckbox, 1)
  }

  // 留言的确定事件
  const handleFinish = (value: { Content: string }) => {
    console.log(value)
    applyCheckColumnNote(replyItemID, value.Content, replyParentId)
  }
  // 留言的取消事件
  const handleOnModalClose = () => {
    form.resetFields()
    setMsgTextVisible(false)
  }
  //删除留言回复的按钮
  const deleteHandle = (id: number) => {
    Modal.confirm({
      title: '提醒',
      content: '确定要删除此回复内容吗？',
      okText: '确定',
      cancelText: '取消',
      centered: true,
      closable: true,
      onOk: () => {
        postMessageDelete(id)
      }
    })
  }
  // 点击回复的按钮
  const replyMsgHandler = (item: IMessageDetail) => {
    setReplyItemID(item.YanxuanSpecialId)
    setReplyreplyParentId(item.MessageId)
    setMsgTextVisible(true)
  }

  // 点击了置顶按钮
  const toppingHandler = (item: IMessageDetail) => {
    const DoType = item.TopTime > 0 ? 0 : 1
    postMessageTop(item.MessageId, DoType)
  }

  // 点击取消精选
  const cancelSelectionHandler = (item: IMessageDetail) => {
    Modal.confirm({
      title: '提醒',
      content: '取消精选后，留言将回到普通留言栏下',
      okText: '确定',
      cancelText: '取消',
      centered: true,
      closable: true,
      onOk: () => {
        postMessagePublic([item.MessageId], 0)
      }
    })
  }
  // 文章详情
  const handleToDetail = (item: IMessageDetail) => {
    window.open(`/column/detail/${item.YanxuanSpecialId}`)
  }
  const items: TabsProps['items'] = [
    {
      key: '1',
      label: <span className="column-tabs">普通留言</span>,
      children: (
        <div className="columncenter-content">
          <div className="content-disclosure">
            <span
              className={selectCheckbox.length ? 'columncenter-content-btn' : 'columncenter-content-btn btn-disabled'}
              onClick={setupClickHandler}
            >
              设为公开
            </span>
            <span> 留言设为公开后将在文章下展示</span>
          </div>
          {messageList.length > 0 &&
            messageList.map(item => (
              <div key={item.MessageId}>
                <Checkbox.Group
                  style={{ display: 'block' }}
                  value={item.CheckIds}
                  onChange={(e: CheckboxValueType[]) => {
                    checkboxChange(e, item)
                  }}
                >
                  <Checkbox value={item.MessageId}>
                    <span style={{ fontWeight: '600' }}>{item.Content}</span>
                  </Checkbox>
                  <div className="columncenter-content-img-time">
                    <img src={item.Headimgurl} alt="" />
                    <span> {item.CreateTime}</span>
                  </div>
                  <div className="columncenter-content-item-title">
                    <p className="item-title" onClick={() => handleToDetail(item)}>
                      {item.SourceTitle}
                    </p>
                    <span className="columncenter-content-btn" onClick={() => replyMsgHandler(item)}>
                      回复
                    </span>
                  </div>
                  <div className="columncenter-content-child">
                    {item.ChildList.length > 0 &&
                      item.ChildList.map(child => (
                        <div key={child.MessageId} style={{ marginLeft: 20 }}>
                          <Checkbox disabled={item.CheckIds.includes(item.MessageId)} value={child.MessageId}>
                            {child.Content}
                          </Checkbox>
                          <div className="child-img-time">
                            <div className="columncenter-content-img-time">
                              <img src={child.Headimgurl} alt="" />
                              <span> {child.CreateTime}</span>
                            </div>
                            <span
                              className="columncenter-content-btn detele-btn"
                              onClick={() => deleteHandle(child.MessageId)}
                            >
                              删除
                            </span>
                          </div>
                        </div>
                      ))}
                  </div>
                </Checkbox.Group>
              </div>
            ))}
        </div>
      )
    },

    {
      key: '2',
      label: <span className="column-tabs">公开的留言</span>,
      children: (
        <div className="columncenter-content">
          {messageList &&
            messageList.length > 0 &&
            messageList.map(item => (
              <div key={item.MessageId} style={{ marginBottom: 30 }}>
                <div className="columncenter-content-disclosure"> {item.Content}</div>
                <div className="columncenter-content-img-time">
                  <span> {item.RealName}</span>
                  <span style={{ marginLeft: 10 }}> {item.CreateTime}</span>
                </div>
                <div className="columncenter-content-item-title">
                  <p className="item-title" onClick={() => handleToDetail(item)}>
                    {item.SourceTitle}
                  </p>
                  <div>
                    <span className="columncenter-content-btn" onClick={() => toppingHandler(item)}>
                      {item.TopTime > 0 ? '已置顶' : '置顶'}
                    </span>
                    <span
                      style={{ marginLeft: 10 }}
                      className="columncenter-content-btn"
                      onClick={() => cancelSelectionHandler(item)}
                    >
                      取消精选
                    </span>
                  </div>
                </div>
                {item.ChildList.length > 0 &&
                  item.ChildList.map(child => (
                    <div key={child.MessageId} style={{ marginLeft: 20 }}>
                      <div className="columncenter-content-disclosure"> {child.Content}</div>
                      {child.CreateTime}
                    </div>
                  ))}
              </div>
            ))}
        </div>
      )
    }
  ]

  // 点击了tabs的change
  const onChange = (key: string) => {
    setMessageList([])
    setSelectCheckbox([])
    setTabsAct(Number(key))
    getColumnManageList(pageSize, currentIndex, Number(key))
  }

  // 关闭了侧边Drawer
  const handleOnClose = () => {
    props.onClose('openMessage')
  }

  //  留言的回复
  const { run: applyCheckColumnNote } = useRequest(ColumnService.postMessageAdd, {
    manual: true,
    onSuccess: res => {
      res.data.Success ? message.success(res.data.Msg) : message.error(res.data.Msg || res.data.ErrMsg)
      setMsgTextVisible(false)
      getColumnManageList(pageSize, currentIndex, tabsAct)
    }
  })

  //  删除留言的接口
  const { run: postMessageDelete } = useRequest(ColumnService.postMessageDelete, {
    manual: true,
    onSuccess: res => {
      res.data.Success ? message.success(res.data.Msg) : message.error(res.data.Msg || res.data.ErrMsg)
      getColumnManageList(pageSize, currentIndex, tabsAct)
    }
  })
  //  精选留言的接口
  const { run: postMessagePublic } = useRequest(ColumnService.postMessagePublic, {
    manual: true,
    onSuccess: res => {
      res.data.Success ? message.success(res.data.Msg) : message.error(res.data.Msg || res.data.ErrMsg)
      getColumnManageList(pageSize, currentIndex, tabsAct)
    }
  })
  //  置顶留言的接口
  const { run: postMessageTop } = useRequest(ColumnService.postMessageTop, {
    manual: true,
    onSuccess: res => {
      res.data.Success ? message.success(res.data.Msg) : message.error(res.data.Msg || res.data.ErrMsg)
      getColumnManageList(pageSize, currentIndex, tabsAct)
    }
  })
  return (
    <Drawer
      title="留言管理"
      placement="right"
      width="625px"
      closable={false}
      onClose={handleOnClose}
      open={props.open}
      extra={<Close className="com-cursor-p" onClick={handleOnClose} />}
      className={styles['columnindex-drawer']}
    >
      <Modal title="留言回复" centered open={msgTextVisible} onCancel={handleOnModalClose} footer={null}>
        <Form form={form} onFinish={handleFinish} labelAlign="left" preserve>
          <Item
            label=""
            name="Content"
            wrapperCol={{ span: 24 }}
            rules={[
              { required: true, message: '请输入内容!' },
              {
                pattern: /^[^\s]*$/,
                message: '禁止输入空格'
              }
            ]}
          >
            <Input.TextArea
              placeholder="留言回复将私信给读者，设为公开后可在文章下展示"
              maxLength={100}
              showCount={true}
              autoSize={{ minRows: 5, maxRows: 5 }}
            />
          </Item>
          <Row align="middle" justify="center">
            <Item>
              <Button onClick={handleOnModalClose} className="m-r-xs">
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
            </Item>
          </Row>
        </Form>
      </Modal>
      <Tabs defaultActiveKey={'1'} items={items} onChange={onChange} className="columnindex-tab-wrapper" />
    </Drawer>
  )
}

export default ColumnMessage
