<script setup lang="ts">
import { ref, watch } from "vue";
import { useRequest } from "vue-request";
import { myRequest } from "@/requests/request.ts";
import { userinfo } from "@/store/store.ts";
import { ElMessage } from "element-plus";
import { formatError } from "@/utils/utils.ts";

const szData = ref({ type: true, card: "", amount: 0 });

const { data: cardList } = useRequest<{
  data: { balance: number; type: boolean; card: string }[];
}>(() => myRequest(`/api/yeb`, userinfo.token));
const { runAsync: updateCard, loading } = useRequest(
  () =>
    myRequest(
      `/api/yeb/sz`,
      userinfo.token,
      { ...szData.value, amount: Number(szData.value.amount) },
      "post",
    ),
  { manual: true },
);

const update = () => {
  updateCard()
    .then(() => {
      szData.value.amount = 0;
      ElMessage.success("成功");
    })
    .catch((err) => ElMessage.error(formatError(err)));
};

watch(cardList, () => {
  szData.value.card = cardList.value?.data[0]?.card || "";
});
</script>

<template>
  <el-form :model="szData" class="sz">
    <el-form-item prop="szType">
      <el-radio-group v-model="szData.type">
        <el-radio :value="false">收入</el-radio>
        <el-radio :value="true">支出</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item prop="card">
      <el-select v-model="szData.card">
        <el-option
          v-for="item in cardList?.data"
          :label="item.card"
          :value="item.card"
        >
          <el-text :type="item.type ? 'danger' : ''">{{ item.card }}</el-text>
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item prop="amount">
      <el-input
        v-model="szData.amount"
        type="number"
        placeholder="输入当前余额"
        :min="0"
        :max="99999999"
        style="width: calc(100% - 50px)"
      >
        <template #prefix>￥</template>
      </el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="update" :disabled="loading"
        >提交</el-button
      >
    </el-form-item>
  </el-form>
</template>

<style scoped>
.sz {
  background-color: #eeea;
  padding: 20px;
  border-radius: 10px;
}
:global(.el-form-item__content) {
  display: block;
}
</style>
