<template>
  <div class="edit-popup">
    <popup
        ref="popupRef"
        :title="popupTitle"
        :async="true"
        width="550px"
        @confirm="handleSubmit"
        @close="handleClose"
    >
      <el-form ref="formRef" :model="formData" label-width="120px" :rules="formRules">
        <el-form-item label="当前余额">
          <span>{{ formData.currentAmount }}</span>
        </el-form-item>
        <el-form-item label="资金流向" prop="balanceFlow">
          <el-radio-group v-model="formData.balanceFlow" size="small">
            <el-radio label=1>流入（余额增加）</el-radio>
            <el-radio label=-1>流出（余额减少）</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input
              type="number"
              v-model="formData.amount"
              placeholder="请输入金额"
              clearable
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
              v-model="formData.remark"
              placeholder="请输入修改原因（可选）"
              clearable
          />
        </el-form-item>
      </el-form>
    </popup>
  </div>
</template>
<script lang="ts" setup>
import type {FormInstance} from 'element-plus'
import Popup from '@/components/popup/index.vue'
import feedback from '@/utils/feedback'
import {queryUserMemberInfo, saveBalanceRecord} from '@/api/membership'

const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const popupTitle = computed(() => {
  return '修改余额'
})
const formData = reactive({
  amount: null,
  currentAmount: 0,
  balanceFlow: null,
  bizScene: '余额修改',
  brandId: null,
  operator: '',
  remark: '',
  userId: null
})

const formRules = {
  amount: [
    {
      required: true,
      message: '请输入金额',
      trigger: ['blur']
    }
  ],
  balanceFlow: [
    {
      required: true,
      message: '请选择资金流向',
      trigger: ['blur']
    }
  ]
}

const handleSubmit = async () => {
  await formRef.value?.validate()
  formData.operator = localStorage.getItem('username') || ''
  formData.amount = Number(formData.amount || 0) * 100
  formData.balanceFlow = Number(formData.balanceFlow || 1)
  await saveBalanceRecord(formData)
  feedback.msgSuccess('操作成功')
  popupRef.value?.close()
  emit('success')
}

const open = () => {
  popupRef.value?.open()
}

const getDetail = async (row: Record<string, any>) => {
  const data = await queryUserMemberInfo({
    userId: row.userId,
    brandId: row.brandId,
    genQrCode: 0
  })
  formData.userId = data.single.userId
  formData.brandId = data.single.brandId
  formData.currentAmount = data.single.accountAmount
}

const handleClose = () => {
  emit('close')
}

defineExpose({
  open,
  getDetail
})
</script>
