import React, { useEffect, useState, useRef } from 'react'
import { Table, Input, Button, Row, Col, Space, DatePicker, Drawer, Form, Modal, Image } from 'antd'
const { RangePicker } = DatePicker
import './index.less'
import PaginationCom from '@/common/Pagination'
import { getList, getInfo, addLabel, editLabel, delLabel, getAllBooks } from './request'
import reload from '@/assets/images/icon/reload.png'
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 dayjs from 'dayjs'
import TableCom from '@/common/TableCom/index'
import { useSelector } from 'react-redux'
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)
  const [isEdit, setIsEdit] = useState(false)
  const [delMoadal, setDelModal] = useState(false)
  const [form] = Form.useForm()
  const [isAdd, setIsAdd] = useState(false)
  const [id, setId] = useState(0)
  // 获取操作权限
  const { operationPermissionsList } = useSelector(state => state.user)
  const [initialValues, setinitialValues] = useState({
    name: '',
    phone: '',
    sex: '1',
    birthday_time: ''
  })
  const [labelObj, setLabelObj] = useState({})
  const [filterObj, setfilterObj] = useState({
    name: '',
    start_time: '',
    end_time: ''
  })
  const [dateVal, setDateVal] = useState('')
  // 全部标签数组
  const [bookLabels, setBookLabels] = useState([])
  //选中id数组
  const [book_ids, setBook_ids] = useState([])
  // 过滤
  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)
      console.log(' setDateVal(val);', 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)
  }
  useEffect(() => {
    if (!isEdit) {
      form.setFieldsValue({ ...initialValues })
    }
  }, [isEdit])
  // 选择标签
  const handlChangeLabel = async obj => {
    const { flag = false, id } = obj
    // 全选
    if (flag) {
      if (!book_ids.length) {
        let arr = []
        let obj = {}
        bookLabels.length &&
          bookLabels.forEach(item => {
            arr.push(item.id)
            obj[item.id.toString()] = item.id
          })
        setBook_ids(arr)
        setLabelObj(obj)
      } else if (book_ids.length === bookLabels.length) {
        setBook_ids([])
        setLabelObj({})
      } else {
        let arr = []
        let obj = {}
        bookLabels.length &&
          bookLabels.forEach(item => {
            arr.push(item.id)
            obj[item.id.toString()] = item.id
          })
        setBook_ids(arr)
        setLabelObj(obj)
      }
      // 单选
    } else {
      // 有
      if (id == labelObj[id]) {
        labelObj[id] = 0
        setLabelObj({ ...labelObj })
      } else {
        labelObj[id] = id
        setLabelObj({ ...labelObj })
      }
      let arr = Object.values(labelObj).filter(item => item !== 0)
      setBook_ids(arr)
    }
  }
  // 重置
  const handleReset = () => {
    setfilterObj({ name: '' })
    setDateVal('')
    init()
  }
  const init = async obj => {
    setLoading(true)
    const { total, list } = await getList({ page, page_size, ...obj })
    setTotal(total)
    setData(list)
    setLoading(false)
  }
  const handleEdit = async obj => {
    console.log('edit obj', obj)
    const { books, id, name } = await getInfo({ id: obj.id })

    setIsAdd(false)
    setIsEdit(true)
    console.log('我是点击编辑以后得obj', id)
    setId(id)
    let copyObj = {}
    books.forEach(item => {
      copyObj[item.toString()] = item
    })
    setLabelObj({ ...copyObj })
    setBook_ids(books)
    form.setFieldsValue({ name })
  }
  const onClose = () => {
    setIsEdit(false)
  }
  const submitForm = async obj => {
    let bool
    let arr = Object.values(labelObj)
    console.log(arr)
    // setBook_ids(arr)
    if (isAdd) {
      bool = await addLabel({ ...obj, book_ids })
    } else {
      bool = await editLabel({ ...obj, id, book_ids })
    }
    if (!bool) return
    init()
    setIsEdit(false)
  }
  const delSuccess = async () => {
    const bool = await delLabel({ id })
    bool && init()
    setDelModal(false)
  }
  const columns = [
    {
      title: 'ID',
      key: 'id',
      dataIndex: 'id',
      align: 'center'
    },
    {
      title: '标签名称',
      key: 'name',
      dataIndex: 'name',
      align: 'center'
    },
    {
      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/label/getInfoById') && (
              <Button onClick={() => handleEdit(record)}>编辑</Button>
            )}
            {operationPermissionsList.includes('/books/label/del') && (
              <Button
                onClick={() => {
                  setDelModal(true)
                  setId(record.id)
                }}>
                删除
              </Button>
            )}
          </Space>
        )
      }
    }
  ]
  const getBookList = async () => {
    const data = await getAllBooks()
    setBookLabels(data)
  }
  useEffect(() => {
    getBookList()
  }, [])
  return (
    <div className="label">
      <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="创建时间">
              {' '}
              <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
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '13px',
                      height: '12px',
                      pointerEvents: 'none'
                    }}>
                    <Image src={filter} />
                  </span>
                }
                onClick={() => {
                  setPage(1)
                  Object.values(filterObj).some(item => item) ? init(filterObj) : init()
                }}
                type="primary"
                ghost>
                筛选
              </Button>
              <Button
                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())}
                type="primary"
                ghost>
                刷新
              </Button>
            </Space>
          </Form>
        </Col>
        <Col>
          <Space>
            {operationPermissionsList.includes('/books/label/add') && (
              <Button
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '13px',
                      height: '12px',
                      pointerEvents: 'none'
                    }}>
                    <Image src={add} />
                  </span>
                }
                onClick={() => {
                  setIsAdd(true)
                  setIsEdit(true)
                }}
                type="primary"
                ghost>
                添加
              </Button>
            )}
          </Space>
        </Col>
      </Row>
      <br />
      <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 18px', 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" onClose={onClose} open={isEdit} mask={false}>
        <Form form={form} onFinish={submitForm} labelCol={{ span: 5 }}>
          <Form.Item label="标签名称" name="name" rules={[{ required: true, message: '请输入标签名称' }]}>
            <Input autoComplete="off" placeholder="请输入标签名称"></Input>
          </Form.Item>
          <Form.Item label="书籍" name="name" rules={[{ required: true, message: '请选择书籍' }]}>
            <Button
              onClick={() => handlChangeLabel({ flag: true })}
              style={{
                background: 'rgba(170, 25, 65, 0.05)',
                marginRight: 0, // 取消右侧间距
                fontWeight: 'bold',

                letterSpacing: '-2px' // 设置负值来减小字母之间的间距
              }}
              type="primary"
              ghost>
              全选
            </Button>
            <br />
            <br />
            <Row gutter={20}>
              {bookLabels.length &&
                bookLabels.map(item => {
                  return (
                    <Col style={{ marginBottom: 15 }} flex={'0 0 70px'} key={item.id}>
                      <Button
                        type={item.id == labelObj[item.id] ? 'primary' : 'default'}
                        ghost={item.id == labelObj[item.id]}
                        onClick={() => handlChangeLabel({ id: item.id })}>
                        {item.name}
                      </Button>
                    </Col>
                  )
                })}
            </Row>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 5, span: 16 }}>
            <Row justify={'center'}>
              <Space size={20}>
                <Button onClick={() => setIsEdit(false)}>取消</Button>
                <Button type="primary" htmlType="submit">
                  提交
                </Button>
              </Space>
            </Row>
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  )
}

export default Audit
