import React, { useState, useRef, useEffect } from 'react'
import { Button, Form, Input, Switch, Space, Drawer, Spin } from 'antd'
import { getIntegral, integralSet, integralEdit, integralAdd, getSystem, systemEdit, getList } from './request'
import { useSelector } from 'react-redux'
const { TextArea } = Input
const Point = () => {
  const flag = useRef(true)
  const [form] = Form.useForm()
  const [form2] = Form.useForm()
  const [initialValues] = useState({
    reward_points_ratio: '',
    one_point_deduction_amount: '',
    integral_use_limit: ''
  })
  const [rechargeModal, setRechargeModal] = useState(false)
  const [integralSwitch, setIntegralSwitch] = useState(false)
  const [loading, setLoading] = useState(false)
  // 获取操作权限
  const { operationPermissionsList } = useSelector(state => state.user)
  // 获取信息
  const geySettingInfo = async () => {
    setLoading(true)
    const data = await getIntegral()
    const { integral_switch } = data
    if (integral_switch == '0') {
      setIntegralSwitch(false)
    } else {
      setIntegralSwitch(true)
    }
    form.setFieldsValue(data)
    setLoading(false)
  }
  // 充值积分
  const submitForm = async obj => {
    const bool = await integralAdd(obj)
    bool && setRechargeModal(false)
  }
  // 修改设置
  const editInfo = async obj => {
    let copyObj = { ...obj }
    delete copyObj.integral_switch
    const bool = await integralEdit(obj)
    bool && geySettingInfo()
  }
  // 修改开关
  const changeIntegralSwitch = async val => {
    const integral_switch = val ? '1' : '0'
    const bool = await integralSet({ integral_switch })
    bool && geySettingInfo()
    if (!val) {
      setRechargeModal(false)
    }
  }
  useEffect(() => {
    // if(!flag.current){
    geySettingInfo()
    // }else{
    // flag.current=false
    // }
  }, [])
  const responsiveFormItemLayout = {
    labelCol: { xxl: 2, xl: 3, lg: 4, md: 5, sm: 6, xs: 8 },
    wrapperCol: { xs: 24, sm: 18 }
  }
  return (
    <div style={{ padding: 20 }}>
      <Spin spinning={loading}>
        <Form form={form} {...responsiveFormItemLayout} initialValues={initialValues} onFinish={editInfo}>
          <Form.Item label="积分开关">
            <div>
              <Switch
                checked={integralSwitch}
                onChange={changeIntegralSwitch}
                disabled={!operationPermissionsList.includes('/setting/point-management/integralSet')}></Switch>
              {operationPermissionsList.includes('/setting/point-management/add') && (
                <Button
                  disabled={!integralSwitch}
                  style={{ marginLeft: 30, opacity: integralSwitch ? '1' : '0' }}
                  onClick={() => {
                    setRechargeModal(true)
                  }}
                  type="primary"
                  ghost>
                  积分充值
                </Button>
              )}
            </div>
          </Form.Item>
          <Form.Item
            label="赠送积分比例(%)"
            name="reward_points_ratio"
            rules={[
              { required: true, message: '请输入赠送积分比例' },
              {
                validator: (_, value) => {
                  if (/^(?:100|[1-9]?[0-9])$/.test(value) || !value) {
                    return Promise.resolve()
                  } else {
                    return Promise.reject('请输入区间0-100的正整数')
                  }
                }
              }
            ]}>
            <Input autoComplete="off" style={{ width: 340 }} placeholder="请输入赠送积分比例"></Input>
          </Form.Item>
          <Form.Item
            label="1积分抵扣金额(元)"
            name="one_point_deduction_amount"
            rules={[
              { required: true, message: '请输入1积分抵扣金额' },
              {
                validator: (_, value) => {
                  if (/^(?:100(?:\.0{1,2})?|\d{1,2}(?:\.\d{1,2})?)$/.test(value) || !value) {
                    return Promise.resolve()
                  } else {
                    return Promise.reject('请输入区间0-100的数字，可以是小数，支持俩位小数')
                  }
                }
              }
            ]}>
            <Input autoComplete="off" style={{ width: 340 }} placeholder="请输入1积分抵扣金额"></Input>
          </Form.Item>
          <Form.Item
            label="积分使用上限(%)"
            name="integral_use_limit"
            rules={[
              { required: true, message: '请输入积分使用上限' },
              {
                validator: (_, value) => {
                  if (/^(?:100|[1-9]?[0-9])$/.test(value) || !value) {
                    return Promise.resolve()
                  } else {
                    return Promise.reject('请输入区间0-100的正整数')
                  }
                }
              }
            ]}>
            <Input autoComplete="off" style={{ width: 340 }} placeholder="请输入积分使用上限"></Input>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 3, span: 16 }}>
            <Space size={20}>
              {operationPermissionsList.includes('/setting/point-management/integralEdit') && (
                <Button
                  onClick={() => {
                    form.setFieldsValue(initialValues)
                  }}>
                  重置
                </Button>
              )}
              {operationPermissionsList.includes('/setting/point-management/integralEdit') && (
                <Button type="primary" htmlType="submit">
                  确定
                </Button>
              )}
            </Space>
          </Form.Item>
        </Form>
      </Spin>
      <Drawer placement="right" onClose={() => setRechargeModal(false)} open={rechargeModal} mask={false}>
        <Form form={form2} onFinish={submitForm} labelCol={{ span: 6 }}>
          <Form.Item name="phone" label="用户手机号" rules={[{ required: true, message: '请输入用户手机号' }]}>
            <TextArea
              placeholder="请输入用户手机号，用逗号隔开，每次最多100个"
              autoSize={{
                minRows: 5,
                maxRows: 8
              }}></TextArea>
          </Form.Item>
          <Form.Item
            name="num"
            label="充值积分"
            rules={[
              { required: true, message: '请输入充值积分数量' },
              { pattern: /^[1-9]\d*$/, message: '请输入正整数' }
            ]}>
            <Input autoComplete="off" placeholder="请输入充值积分数量"></Input>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 6, span: 16 }} style={{ textAlign: 'center' }}>
            <Space size={20}>
              <Button onClick={() => setRechargeModal(false)}>取消</Button>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  )
}

export default Point
