<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    :width="500"
    :visible="visible"
    :confirm-loading="loading"
    :title="'在线充值'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="styleResponsive ? { md: 7, sm: 4, xs: 24 } : { flex: '90px' }"
      :wrapper-col="
        styleResponsive ? { md: 17, sm: 20, xs: 24 } : { flex: '1' }
      "
    >
      <a-form-item label="充值金额" name="payPrice">
        <a-input-number
          placeholder="请输入金额"
          style="width: 280px"
          v-model:value="form.payPrice"
        />
      </a-form-item>
      <a-form-item label="备注" name="comments">
        <a-textarea
          :rows="4"
          style="width: 280px"
          placeholder="请输入备注"
          v-model:value="form.comments"
        />
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { message } from 'ant-design-vue/es';
  import type { FormInstance, Rule } from 'ant-design-vue/es/form';
  import { storeToRefs } from 'pinia';
  import { useThemeStore } from '@/store/modules/theme';
  import useFormData from '@/utils/use-form-data';
  import { recharge, batchRecharge } from '@/api/user/recharge/order';
  import type { User } from '@/api/system/user/model';
  import { RechargeOrder } from '@/api/user/recharge/order/model';

  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  const props = defineProps<{
    selection?: User[];
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: User | null;
  }>();

  //
  const formRef = ref<FormInstance | null>(null);

  // 是否是修改
  const isUpdate = ref(false);

  // 提交状态
  const loading = ref(false);

  // 批量充值数据
  const rechargeOrder = ref<RechargeOrder[]>([]);

  // 表单数据
  const { form, resetFields, assignFields } = useFormData<RechargeOrder>({
    userId: undefined,
    payPrice: undefined,
    organizationId: undefined
  });

  // 表单验证规则
  const rules = reactive<Record<string, Rule[]>>({
    payPrice: [
      {
        required: true,
        type: 'number',
        message: '请要充值的金额',
        trigger: 'blur'
      }
    ],
    comments: [
      {
        required: true,
        message: '请输入备注信息',
        type: 'string',
        trigger: 'blur'
      }
    ]
  });

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        rechargeOrder.value = [];
        props.selection?.map((d) => {
          rechargeOrder.value?.push({
            rechargeType: 10,
            payPrice: form.payPrice,
            comments: form.comments,
            organizationId: d.organizationId,
            userId: d.userId,
            balance: d.balance
          });
        });
        console.log(rechargeOrder.value);
        // const saveOrUpdate = isUpdate.value ? updateUser : addUser;
        batchRecharge(rechargeOrder.value)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          assignFields({
            ...props.data,
            password: ''
          });
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
        formRef.value?.clearValidate();
      }
    }
  );
</script>
