<script lang="ts" setup>
import { reactive, ref, watch } from 'vue';

import SysOriginSelect from '#/components/sys-origin-select.vue';
import {
  getPayFactoryConfig,
  savePayFactoryConfig,
} from '#/api/legacy/pay';

import {
  Button,
  Form,
  FormItem,
  Input,
  Modal,
  Select,
  Switch,
  TextArea,
  message,
} from 'antdv-next';

const props = withDefaults(
  defineProps<{
    open: boolean;
    row?: Record<string, any>;
  }>(),
  {
    row: () => ({}),
  },
);

const emit = defineEmits<{
  close: [];
  success: [];
}>();

const loading = ref(false);
const saving = ref(false);
const form = reactive<Record<string, any>>({
  enabled: true,
  env: 'PROD',
  factoryCode: '',
  gatewayBaseUrl: '',
  id: '',
  merAccount: '',
  merNo: '',
  notifyUrl: '',
  platformRsaPublicKey: '',
  rsaPrivateKey: '',
  sysOrigin: '',
});

const envOptions = [
  { label: 'PROD', value: 'PROD' },
  { label: 'TEST', value: 'TEST' },
  { label: '通用', value: '' },
];

watch(
  () => props.open,
  (open) => {
    if (!open) {
      return;
    }
    const row = props.row || {};
    Object.assign(form, {
      enabled: true,
      env: 'PROD',
      factoryCode: row.factoryCode || '',
      gatewayBaseUrl: '',
      id: '',
      merAccount: '',
      merNo: '',
      notifyUrl: '',
      platformRsaPublicKey: '',
      rsaPrivateKey: '',
      sysOrigin: '',
    });
    if (form.factoryCode) {
      void loadConfig();
    }
  },
  { immediate: true },
);

function resetConfigFields() {
  Object.assign(form, {
    enabled: true,
    gatewayBaseUrl: '',
    id: '',
    merAccount: '',
    merNo: '',
    notifyUrl: '',
    platformRsaPublicKey: '',
    rsaPrivateKey: '',
  });
}

async function loadConfig() {
  if (!form.factoryCode) {
    return;
  }
  loading.value = true;
  try {
    const scope = {
      env: form.env || '',
      factoryCode: form.factoryCode,
      sysOrigin: form.sysOrigin || '',
    };
    const result = await getPayFactoryConfig(scope);
    resetConfigFields();
    Object.assign(form, scope, result || {});
  } finally {
    loading.value = false;
  }
}

function validateForm() {
  const requiredFields: Array<[string, string]> = [
    ['merAccount', '请输入商户标识'],
    ['merNo', '请输入商户编号'],
    ['gatewayBaseUrl', '请输入网关地址'],
    ['rsaPrivateKey', '请输入商户私钥'],
    ['platformRsaPublicKey', '请输入平台公钥'],
    ['notifyUrl', '请输入回调地址'],
  ];
  for (const [key, text] of requiredFields) {
    if (!String(form[key] || '').trim()) {
      message.warning(text);
      return false;
    }
  }
  return true;
}

async function handleSubmit() {
  if (!validateForm()) {
    return;
  }
  saving.value = true;
  try {
    await savePayFactoryConfig({ ...form });
    message.success('保存成功');
    emit('success');
    emit('close');
  } finally {
    saving.value = false;
  }
}
</script>

<template>
  <Modal
    :confirm-loading="saving"
    :open="open"
    destroy-on-close
    title="MiFaPay 配置"
    width="760px"
    @cancel="emit('close')"
    @ok="handleSubmit"
  >
    <Form layout="vertical">
      <div class="scope-row">
        <FormItem label="厂商Code">
          <Input v-model:value="form.factoryCode" disabled />
        </FormItem>
        <FormItem label="环境">
          <Select
            v-model:value="form.env"
            :options="envOptions"
            @change="loadConfig"
          />
        </FormItem>
        <FormItem label="来源系统">
          <SysOriginSelect
            v-model:value="form.sysOrigin"
            allow-clear
            placeholder="通用"
            @change="loadConfig"
          />
        </FormItem>
        <FormItem label=" ">
          <Button :loading="loading" @click="loadConfig">读取配置</Button>
        </FormItem>
      </div>

      <div class="grid">
        <FormItem label="商户标识 merAccount">
          <Input v-model:value="form.merAccount" />
        </FormItem>
        <FormItem label="商户编号 merNo">
          <Input v-model:value="form.merNo" />
        </FormItem>
      </div>

      <FormItem label="网关地址 gatewayBaseUrl">
        <Input v-model:value="form.gatewayBaseUrl" />
      </FormItem>

      <FormItem label="商户RSA私钥">
        <TextArea v-model:value="form.rsaPrivateKey" :rows="5" />
      </FormItem>

      <FormItem label="平台RSA公钥">
        <TextArea v-model:value="form.platformRsaPublicKey" :rows="5" />
      </FormItem>

      <FormItem label="回调地址 notifyUrl">
        <Input v-model:value="form.notifyUrl" />
      </FormItem>

      <FormItem label="启用">
        <Switch v-model:checked="form.enabled" />
      </FormItem>
    </Form>
  </Modal>
</template>

<style scoped>
.grid {
  column-gap: 12px;
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
}

.scope-row {
  column-gap: 12px;
  display: grid;
  grid-template-columns: 180px 130px minmax(180px, 1fr) 96px;
}
</style>
