<template>
  <a-modal
    :visible="props.visible"
    :ok-loading="loading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <template #title>添加商户</template>
    <a-form :model="formData">
      <a-form-item field="merchantName" label="商户名称" required>
        <a-input v-model="formData.merchantName" />
      </a-form-item>
      <a-form-item field="loginAccount" label="商户手机号" required>
        <a-input v-model="formData.loginAccount" />
      </a-form-item>
      <a-form-item field="loginPassword" label="登录密码" required>
        <a-input-password v-model="formData.loginPassword" allow-clear />
      </a-form-item>
      <a-form-item label="激活状态" field="status" required>
        <a-switch
          v-model="formData.status"
          size="small"
          checked-value="active"
          unchecked-value="unactive"
        >
          <template #checked>激活</template>
          <template #unchecked>冻结</template>
        </a-switch>
      </a-form-item>
      <a-form-item field="remark" label="备注">
        <a-textarea v-model="formData.remark" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import {
  MerchantConfigAddRecord,
  addMerchantConfig
} from '@/api/merchant-list';
import useLoading from '@/hooks/loading';
import { ref } from 'vue';

const generateFormData = () => {
  return {
    merchantName: '',
    loginAccount: '',
    loginPassword: '',
    remark: '',
    status: 'active'
  };
};

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
});
const formData = ref<MerchantConfigAddRecord>(generateFormData());

const { loading, setLoading } = useLoading(false);

const emit = defineEmits(['update:visible']);
const handleOk = async () => {
  try {
    setLoading(true);
    await addMerchantConfig(formData.value);
    emit('update:visible', false);
    formData.value = generateFormData();
  } finally {
    setLoading(false);
  }
};
const handleCancel = () => {
  emit('update:visible', false);
  formData.value = generateFormData();
};
</script>
