import { addUserPaymentRecord } from '@/api/sys-user-payment';
import {
  Form,
  type FormInstance,
  FormItem,
  InputNumber,
  Message,
  Modal,
  Option,
  Select,
  Textarea
} from '@arco-design/web-vue';
import { computed, defineComponent, ref } from 'vue';

export default defineComponent({
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    userId: {
      required: true,
      type: String,
      default: ''
    }
  },
  emits: {
    'update:visible': (_visible: boolean) => true
  },
  setup(props, { emit }) {
    const formData = ref<{
      amount: number;
      transactionType: string;
      remark: string;
    }>({
      amount: 0,
      transactionType: '',
      remark: ''
    });
    const formDataRef = ref<FormInstance>();
    const visible = computed(() => props.visible);
    return () => (
      <Modal
        title='充值'
        visible={visible.value}
        onBeforeOk={(done: (closed: boolean) => void) => {
          formDataRef.value?.validate(errors => {
            if (errors) {
              done(false);
            } else {
              addUserPaymentRecord({
                userId: props.userId,
                amount: formData.value.amount || 0,
                transactionType: formData.value.transactionType,
                remark: formData.value.remark
              })
                .then(() => {
                  formData.value.amount = 0;
                  Message.success('充值成功');
                  done(true);
                  emit('update:visible', false);
                })
                .catch(() => {
                  done(false);
                });
            }
          });
        }}
        onCancel={() => {
          formData.value.amount = 0;
          emit('update:visible', false);
        }}
      >
        <Form ref={formDataRef} model={formData}>
          <FormItem label='充值金额' field='amount' required>
            <InputNumber v-model={formData.value.amount} precision={2} />
          </FormItem>
          <FormItem label='场景选择' field='transactionType' required>
            <Select v-model={formData.value.transactionType}>
              <Option label='充值' value='deposit' />
              <Option label='扣除' value='Manual Adjustment' />
            </Select>
          </FormItem>
          <FormItem label='备注' field='remark'>
            <Textarea v-model={formData.value.remark} />
          </FormItem>
        </Form>
      </Modal>
    );
  }
});
