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, infoGrade, addGrade, editGrade, delGrade, getSystem, systemEdit } 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 TableCom from '@/common/TableCom/index'
import dayjs from 'dayjs'
import { useSelector } from 'react-redux'

const Userlevel = () => {
  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 [form1] = Form.useForm()
  const [isAdd, setIsAdd] = useState(false)
  const [id, setId] = useState(0)
  const [isEditValidity, setIsEditValidity] = useState(false)
  const [initialValues, setinitialValues] = useState({
    name: '',
    consumption: ''
  })
  const [filterObj, setfilterObj] = useState({
    name: '',
    start_time: '',
    end_time: ''
  })

  const [dateVal, setDateVal] = useState('')
  // 获取操作权限
  const { operationPermissionsList } = useSelector(state => state.user)

  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 infoGrade({ id: obj.id })
    setIsAdd(false)
    setIsEdit(true)
    setId(data.id)
    form.setFieldsValue(data)
  }
  const onClose = () => {
    setIsEdit(false)
  }
  const submitForm = async obj => {
    let bool
    if (isAdd) {
      bool = await addGrade({ ...obj })
    } else {
      bool = await editGrade({ ...obj, id })
    }
    if (!bool) return
    init()
    setIsEdit(false)
  }
  const delSuccess = async () => {
    const bool = await delGrade({ id })
    bool && init()
    setDelModal(false)
  }
  useEffect(() => {
    if (!isEdit) {
      form.setFieldsValue({ ...initialValues })
      form.resetFields()
    }
  }, [isEdit])

  // 获取信息
  const getInfo = async () => {
    const data = await getSystem({ type: 2 })
    form1.setFieldsValue({
      set_value: data.set_value
    })
  }
  // 设置个性化信息
  const handleSystemEdit = async values => {
    const { set_value } = values // 获取输入框的内容
    const data = { type: 2, set_value } // 构造传递给systemEdit的参数对象
    const bool = await systemEdit(data)
    console.log('bool', bool)
    bool && getInfo()
  }
  useEffect(() => {
    // 是否有权限设置有效期
    if (operationPermissionsList.includes('/member/userlevel/getSystem')) {
      getInfo()
    }
  }, [operationPermissionsList])
  const columns = [
    {
      title: 'ID',
      key: 'id',
      align: 'center',
      dataIndex: 'id'
    },
    {
      title: '等级名称',
      key: 'name',
      align: 'center',
      dataIndex: 'name'
    },
    {
      title: '达标金额',
      key: 'consumption',
      align: 'center',
      dataIndex: 'consumption'
    },
    {
      title: '创建时间',
      key: 'create_time',
      align: 'center',
      dataIndex: 'create_time'
    },
    {
      title: '更新时间',
      key: 'update_time',
      align: 'center',
      dataIndex: 'update_time'
    },
    {
      title: '操作',
      key: 'handle',
      dataIndex: 'handle',
      render: (_, record) => {
        return (
          <Space>
            {operationPermissionsList.includes('/member/userlevel/getInfoById') && (
              <Button
                style={{
                  letterSpacing: '-2px'
                }}
                onClick={() => handleEdit(record)}>
                编辑
              </Button>
            )}
            {operationPermissionsList.includes('/member/userlevel/del') && (
              <Button
                onClick={() => {
                  setId(record.id)
                  setDelModal(true)
                }}
                style={{
                  letterSpacing: '-2px'
                }}>
                删除
              </Button>
            )}
          </Space>
        )
      }
    }
  ]
  return (
    <div>
      {/* <Space style={{ paddingBottom: '20px' }}>
        <Form form={form1} onFinish={handleSystemEdit}>
          <Form.Item label='用户等级有效期(月)' name='user_grade_validity'>
            <Input
              autoComplete='off'
              style={{ width: 260 }}
              placeholder='请输入用户等级有效期'
            ></Input>
            <span style={{ marginLeft: '10px', color: '#999999' }}>
              用于计算用户等级,根据当前时间之前有效期内的消费金额总和来计算
            </span>
          </Form.Item>
        </Form>
      </Space> */}
      <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="创建时间">
              <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"
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '13px',
                      height: '12px',
                      pointerEvents: 'none'
                    }}>
                    <Image src={filter} />
                  </span>
                }
                ghost
                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/userlevel/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>
            )}
            {operationPermissionsList.includes('/member/userlevel/getSystem') && (
              <Button
                type="primary"
                ghost
                onClick={() => {
                  setIsAdd(true)
                  setIsEditValidity(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
        onClose={onClose}
        open={isEdit}
        footer={null}
        mask={false}
        keyboard={false}
        onCancel={() => setIsEdit(false)}>
        <Form
          form={form}
          onFinish={submitForm}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 12 }}
          style={{
            marginBottom: '-30px'
          }}>
          <Form.Item
            label="等级名称"
            name="name"
            rules={[
              { required: true, message: '请输入等级名称' },
              { max: 30, message: '最大30字符' }
            ]}>
            <Input autoComplete="off" placeholder="请输入等级名称"></Input>
          </Form.Item>
          <Form.Item
            label="达标金额"
            name="consumption"
            rules={[
              { required: true, message: '请输入达标金额' },
              { pattern: /^[0-9]\d*$/, message: '必须是正整数' }
            ]}>
            <Input autoComplete="off" placeholder="请输入达标金额"></Input>
          </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>

      <Drawer
        onClose={() => setIsEditValidity(false)}
        open={isEditValidity}
        footer={null}
        mask={false}
        keyboard={false}
        onCancel={() => setIsEditValidity(false)}>
        <Row align="middle" justify="center">
          <Col span={20}>
            <Form form={form1} onFinish={handleSystemEdit} labelCol={{ span: 9 }} wrapperCol={{ span: 26 }}>
              <Form.Item label="用户等级有效期(月)" name="set_value" style={{ marginBottom: 10 }}>
                <Input
                  autoComplete="off"
                  style={{ width: '100%', marginRight: 10 }} // 使用百分比宽度
                  placeholder="请输入用户等级有效期"
                />
              </Form.Item>
              <Form.Item wrapperCol={{ offset: 0, span: 26 }}>
                {/* 调整偏移和跨度，使按钮居中 */}
                <div style={{ color: '#999999', fontSize: 12 }}>
                  用于计算用户等级，根据当前时间之前有效期内的消费金额总和来计算 (1-24正整数)
                </div>
              </Form.Item>
              <Form.Item wrapperCol={{ offset: 9, span: 26 }}>
                <Space size={20}>
                  {operationPermissionsList.includes('/member/userlevel/systemEdit') && (
                    <Button onClick={() => setIsEditValidity(false)}>取消</Button>
                  )}
                  {operationPermissionsList.includes('/member/userlevel/systemEdit') && (
                    <Button type="primary" htmlType="submit" onClick={() => setIsEditValidity(false)}>
                      提交
                    </Button>
                  )}
                </Space>
              </Form.Item>
            </Form>
          </Col>
        </Row>
      </Drawer>
    </div>
  )
}

export default Userlevel
