import { useEffect, useState } from 'react';
import { Button, Form, InputNumber, message, Modal, Switch, Table } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import AddOrEditModal from './comp/addOrEditModal';
import { ActivityManageAPI } from '~/api';
import { InterDataType } from '~/api/interface';
import { SignInListType } from '~/api/interface/activityManage';

const RewardsManageView = () => {
  // 表单钩子
  const [formRefs] = Form.useForm();
  // 连续签到信息
  const [signInfoList, setSignInfoList] =
    useState<InterDataType<SignInListType>[0]['userContinuousCheckInVO']>();
  // 签到信息
  const [signData, setSignData] = useState<InterDataType<SignInListType>[0]>();
  // 获取签到设置
  const getDataInfo = async () => {
    const res = await ActivityManageAPI.SignInList();
    if (res && res.code === '200') {
      if (!res.result?.length) return;
      setSignInfoList(res.result[0]?.userContinuousCheckInVO || []);
      setSignData(res.result[0]);
      formRefs.setFieldsValue({
        period: res.result[0].period,
        integral: res.result[0].integral,
        status: res.result[0].status,
      });
    }
  };
  // 需要编辑的数据
  const [editData, setEditData] =
    useState<InterDataType<SignInListType>[0]['userContinuousCheckInVO'][0]>();
  // 编辑弹窗是否展示
  const [addEditShow, setAddEditShow] = useState(false);
  // 提交数据
  const handleSubmit = async () => {
    const valid = await formRefs.validateFields();
    if (!valid) return;
    const res = await ActivityManageAPI.DataInfo({
      ...valid,
      userContinuousCheckInVO: signInfoList,
      id: signData?.id,
    });
    if (res && res.code === '200') {
      message.success('操作成功');
      await getDataInfo();
    }
    // console.log('提价数据 --->', valid);
  };
  // 删除数据
  const handleDelete = (record: InterDataType<SignInListType>[0]) => {
    Modal.confirm({
      title: '提示',
      content: '请确认是否删除？',
      onOk: () => {
        setSignInfoList(signInfoList?.filter((item) => item.id !== record.id));
        message.success('删除成功').then();
      },
    });
  };
  // 组件挂载
  useEffect(() => {
    getDataInfo().then();
  }, []);

  return (
    <>
      <div className='rewards-form' style={{ width: '90%' }}>
        <Form
          labelCol={{ span: 3 }}
          wrapperCol={{ offset: 1 }}
          form={formRefs}
          initialValues={{ show: 1, activityType: 1 }}
        >
          <Form.Item
            label='是否启用'
            name='status'
            rules={[{ required: true, message: '请选择是否启用' }]}
            valuePropName='checked'
          >
            <Switch />
          </Form.Item>
          <Form.Item
            label='签到周期'
            name='period'
            rules={[
              { required: true, message: '请输入签到周期' },
              { pattern: /^[0-9]*$/g, message: '请输入整数' },
            ]}
            extra='签到周期需在7-100天内'
          >
            <InputNumber min={7} max={100} placeholder='请输入签到周期' addonAfter={'天'} />
          </Form.Item>
          <Form.Item
            label='每日奖励'
            name='integral'
            rules={[
              { required: true, message: '请输入每日签到奖励' },
              { pattern: /^[0-9]*$/g, message: '请输入整数' },
            ]}
          >
            <InputNumber min={1} max={10000} placeholder='请输入每日签到奖励' addonAfter={'积分'} />
          </Form.Item>
          <Form.Item label='连续签到' wrapperCol={{ offset: 1, span: 20 }}>
            <Button
              type={'primary'}
              icon={<PlusOutlined />}
              style={{ marginBottom: '16px' }}
              onClick={() => setAddEditShow(true)}
            >
              添加连续签到奖励
            </Button>
            <Table
              size={'small'}
              bordered
              rowKey='id'
              columns={[
                {
                  title: '连续签到天数',
                  dataIndex: 'numberOfDays',
                  align: 'center',
                  width: '100px',
                  render: (text: string) => `${text}天`,
                },
                {
                  title: '奖励积分',
                  dataIndex: 'bonusPoints',
                  align: 'center',
                  width: '100px',
                  render: (text: string) => `${text}分`,
                },
                {
                  title: '操作',
                  dataIndex: 'action',
                  align: 'center',
                  width: '100px',
                  fixed: 'right',
                  render: (_value, record) => (
                    <>
                      <Button
                        type={'link'}
                        onClick={() => {
                          setEditData(record);
                          setAddEditShow(true);
                        }}
                      >
                        编辑
                      </Button>
                      <Button
                        type={'link'}
                        danger
                        onClick={() =>
                          handleDelete(record as unknown as InterDataType<SignInListType>[0])
                        }
                      >
                        删除
                      </Button>
                    </>
                  ),
                },
              ]}
              dataSource={signInfoList}
            />
          </Form.Item>
        </Form>
      </div>
      <div
        className='rewards-action'
        style={{ width: '100%', display: 'flex', justifyContent: 'center' }}
      >
        <Button type={'primary'} onClick={handleSubmit}>
          保存
        </Button>
      </div>
      <AddOrEditModal
        open={addEditShow}
        title={editData ? '编辑' : '添加'}
        data={editData}
        onCancel={() => {
          setAddEditShow(false);
          setEditData(undefined);
        }}
        onSubmit={(e) => {
          setSignInfoList([...(signInfoList || []), e]);
          setAddEditShow(false);
          setEditData(undefined);
        }}
      />
    </>
  );
};

export default RewardsManageView;
