import React, { useEffect, useState } from 'react'
import { Table, Input, Button, Row, Col, Space, DatePicker, Pagination, Drawer, Form, Modal, Radio, Image } from 'antd'
import { useNavigate } from 'react-router-dom'
const { RangePicker } = DatePicker
import PaginationCom from '@/common/Pagination'
import { getList, getInfo, addUser, editUser, delUser } 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 Classify = () => {
  const [data, setData] = useState([])
  const navigate = useNavigate()
  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 [filterObj, setfilterObj] = useState({
    name: '',
    phone: '',
    start_time: '',
    end_time: ''
  })
  const [dateVal, setDateVal] = 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)
      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 handleReset = () => {
    setfilterObj({ real_name: '', tel: '' })
    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 => {
    const data = await getInfo({ id: obj.id })
    let { birthday_time, id, sex } = data
    setIsAdd(false)
    setIsEdit(true)
    setId(id)
    form.setFieldsValue({ ...data, birthday_time: dayjs(birthday_time), sex: sex + '' })
  }
  const onClose = () => {
    setIsEdit(false)
  }
  const submitForm = async obj => {
    let bool
    let { birthday_time } = obj
    if (isAdd) {
      bool = await addUser({ ...obj, birthday_time: dayjs(birthday_time).unix() })
    } else {
      bool = await editUser({ ...obj, id, birthday_time: dayjs(birthday_time).unix() })
    }
    if (!bool) return
    init()
    setIsEdit(false)
  }
  const delSuccess = async () => {
    const bool = await delUser({ id })
    bool && init()
    setDelModal(false)
  }
  useEffect(() => {
    if (!isEdit) {
      form.setFieldsValue({ ...initialValues })
    }
  }, [isEdit])
  const columns = [
    {
      title: 'ID',
      key: 'id',
      align: 'center',
      dataIndex: 'id'
    },
    {
      title: '用户名',
      key: 'name',
      align: 'center',
      dataIndex: 'name',
      width: 250
    },
    {
      title: '用户手机号',
      key: 'phone',
      align: 'center',
      dataIndex: 'phone'
    },
    {
      title: '创建时间',
      key: 'create_time',
      align: 'center',
      dataIndex: 'create_time'
    },
    {
      title: '最后登录时间',
      key: 'last_login_time',
      align: 'center',
      dataIndex: 'last_login_time'
    },
    {
      title: '最后登录IP',
      key: 'last_ip',
      align: 'center',
      dataIndex: 'last_ip'
    },
    {
      title: '操作',
      key: 'handle',
      dataIndex: 'handle',
      render: (_, record) => {
        return (
          <Space>
            {operationPermissionsList.includes('/member/list/getInfoById') && (
              <Button onClick={() => handleEdit(record)}>编辑</Button>
            )}
            {operationPermissionsList.includes('/member/list/del') && (
              <Button
                onClick={() => {
                  setId(record.id)
                  setDelModal(true)
                }}>
                删除
              </Button>
            )}
            {operationPermissionsList.includes('/member/list/detail') && (
              <Button
                onClick={() => {
                  navigate('/member/list/detail', {
                    state: {
                      id: record.id
                    }
                  })
                }}>
                详情
              </Button>
            )}
          </Space>
        )
      }
    }
  ]
  return (
    <div className="classify">
      <Row justify={'space-between'}>
        <Col 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="手机号">
              <Input
                autoComplete="off"
                allowClear
                value={filterObj.phone}
                onChange={ev => handleFilter('phone', ev.target.value)}
                placeholder="请输入手机号"
                id="phone"></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
                type="primary"
                ghost
                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()
                }}>
                筛选
              </Button>
              <Button
                type="primary"
                ghost
                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())}>
                刷新
              </Button>
            </Space>
          </Form>
        </Col>
        <Col>
          <Space>
            {operationPermissionsList.includes('/member/list/add') && (
              <Button
                type="primary"
                ghost
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '13px',
                      height: '12px',
                      pointerEvents: 'none'
                    }}>
                    <Image src={add} />
                  </span>
                }
                onClick={() => {
                  setIsAdd(true)
                  setIsEdit(true)
                }}>
                添加
              </Button>
            )}
          </Space>
        </Col>
      </Row>
      <br />
      {TableCom({ columns, loading, data })}
      <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>
      <br />
      <PaginationCom
        total={total}
        page_size={page_size}
        setpage_size={setpage_size}
        page={page}
        setPage={setPage}
        init={init}
        filterObj={filterObj}
      />
      <Drawer
        onCancel={() => setIsEdit(false)}
        open={isEdit}
        mask={false}
        centered
        footer={null}
        onClose={() => setIsEdit(false)}>
        <Form form={form} onFinish={submitForm} labelCol={{ span: 7 }}>
          <Form.Item
            name="name"
            label="用户名称"
            rules={[
              { required: true, message: '请输入用户名称' },
              { max: 30, message: '最大30字符' }
            ]}>
            <Input autoComplete="off" placeholder="请输入用户名称"></Input>
          </Form.Item>
          <Form.Item
            name="phone"
            label="手机号名称"
            rules={[
              { required: true, message: '请输入手机号名称' },
              {
                pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
                message: '请输入正确格式的手机号',
                trigger: 'blur'
              }
            ]}>
            <Input autoComplete="off" placeholder="请输入手机号名称"></Input>
          </Form.Item>
          <Form.Item name="sex" label="性别" rules={[{ required: true, message: '请选择性别' }]}>
            <Radio.Group defaultValue={''}>
              <Radio value={'1'}>男</Radio>
              <Radio value={'2'}>女</Radio>
              <Radio value={'3'}>保密</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item name="birthday_time" label="出生日期" rules={[{ required: true, message: '请选择出生日期' }]}>
            <DatePicker />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 9, span: 16 }}>
            <Space size={20}>
              <Button onClick={() => setIsEdit(false)}>取消</Button>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  )
}

export default Classify
