<script lang="ts" setup>
import { computed, ref, useTemplateRef } from 'vue';
import type { FormInst, FormRules } from 'naive-ui';
import type { Treaty } from '@elysiajs/eden';
import { client, safeClient } from '@/service/api';

defineOptions({ name: 'EditSpotRobotConfig' });

type Data = Treaty.Data<typeof client.api.admin.spot_robot_trader.configs.get>['data'][number];

const props = defineProps<{
  data: Data;
}>();

const emit = defineEmits<{
  (e: 'close'): void;
}>();

const formRef = useTemplateRef<FormInst | null>('formRef');
const { data: assets } = safeClient(client.api.admin.assets.get({ query: { pageIndex: 1, pageSize: 100 } }));
const { data: users } = safeClient(client.api.admin.users.get({ query: { pageIndex: 1, pageSize: 200 } }));
const { data: tradingPairs } = safeClient(
  client.api.admin.trading_pairs.get({ query: { pageIndex: 1, pageSize: 100 } })
);

const assetOptions = computed(
  () =>
    assets.value?.data.map(asset => ({
      label: `${asset.code} - ${asset.name}`,
      value: asset.code
    })) || []
);

const form = ref({
  baseAsset: props.data.baseAsset,
  quoteAsset: props.data.quoteAsset,
  robotUserId: props.data.robotUserId,
  symbol: props.data.symbol,
  baseTopUpAmount: props.data.baseTopUpAmount ? Number(props.data.baseTopUpAmount) : 0,
  enabled: props.data.enabled,
  operatorUserId: props.data.operatorUserId || '',
  buyPriceMax: props.data.buyPriceMax ? Number(props.data.buyPriceMax) : 0,
  buyPriceMin: props.data.buyPriceMin ? Number(props.data.buyPriceMin) : 0,
  buyPriceStep: props.data.buyPriceStep ? Number(props.data.buyPriceStep) : 0
});

const rules: FormRules = {
  baseAsset: [
    {
      required: true,
      message: '请输入基础资产',
      trigger: ['blur', 'input']
    }
  ],
  quoteAsset: [
    {
      required: true,
      message: '请输入计价资产',
      trigger: ['blur', 'input']
    }
  ],
  robotUserId: [
    {
      required: true,
      message: '请输入机器人用户ID',
      trigger: ['blur', 'input']
    }
  ],
  symbol: [
    {
      required: true,
      message: '请输入交易对',
      trigger: ['blur', 'input']
    }
  ],
  baseTopUpAmount: [
    {
      required: true,
      type: 'number',
      message: '请输入基础资产单次充值金额',
      trigger: ['blur', 'change']
    }
  ],
  buyPriceMax: [
    {
      required: true,
      type: 'number',
      message: '请输入买入价格上限',
      trigger: ['blur', 'change']
    }
  ],
  buyPriceMin: [
    {
      required: true,
      type: 'number',
      message: '请输入买入价格下限',
      trigger: ['blur', 'change']
    }
  ],
  buyPriceStep: [
    {
      required: true,
      type: 'number',
      message: '请输入买入价格步长',
      trigger: ['blur', 'change']
    }
  ]
};

async function handleSubmit() {
  formRef.value?.validate(async errors => {
    if (!errors) {
      const { data } = await safeClient(() =>
        client.api.admin.spot_robot_trader.config.put({
          id: props.data.id,
          baseAsset: form.value.baseAsset,
          operatorUserId: form.value.operatorUserId,
          quoteAsset: form.value.quoteAsset,
          robotUserId: form.value.robotUserId,
          symbol: form.value.symbol,
          baseTopUpAmount: String(form.value.baseTopUpAmount),
          enabled: form.value.enabled,
          buyPriceMax: String(form.value.buyPriceMax),
          buyPriceMin: String(form.value.buyPriceMin),
          buyPriceStep: String(form.value.buyPriceStep)
        })
      );
      if (data) {
        window.$message?.success('现货机器人配置更新成功');
        emit('close');
      }
    }
  });
}
</script>

<template>
  <NForm
    ref="formRef"
    :model="form"
    :rules="rules"
    label-width="140px"
    label-placement="left"
    require-mark-placement="left"
  >
    <NFormItem label="基础资产" path="baseAsset">
      <NSelect v-model:value="form.baseAsset" :options="assetOptions" placeholder="请选择基础资产" filterable />
    </NFormItem>

    <NFormItem label="计价资产" path="quoteAsset">
      <NSelect v-model:value="form.quoteAsset" :options="assetOptions" placeholder="请选择计价资产" filterable />
    </NFormItem>

    <NFormItem label="机器人用户ID" path="robotUserId">
      <NSelect
        v-model:value="form.robotUserId"
        :options="users?.data.map(user => ({ label: `${user.nickname || user.user.name}`, value: user.userId })) || []"
        placeholder="请选择机器人用户"
        filterable
      />
    </NFormItem>

    <NFormItem label="交易对" path="symbol">
      <NSelect
        v-model:value="form.symbol"
        :options="tradingPairs?.data.map(tp => ({ label: tp.symbol, value: tp.symbol })) || []"
        placeholder="请选择交易对"
        filterable
      />
    </NFormItem>

    <NFormItem label="基础资产单次充值金额" path="baseTopUpAmount">
      <NInputNumber
        v-model:value="form.baseTopUpAmount"
        :min="0"
        :step="0.01"
        :precision="8"
        placeholder="请输入充值金额"
        class="w-full"
      />
    </NFormItem>

    <NFormItem label="买入价格上限" path="buyPriceMax">
      <NInputNumber
        v-model:value="form.buyPriceMax"
        :min="0"
        :step="0.01"
        :precision="8"
        placeholder="请输入买入价格上限"
        class="w-full"
      />
    </NFormItem>

    <NFormItem label="买入价格下限" path="buyPriceMin">
      <NInputNumber
        v-model:value="form.buyPriceMin"
        :min="0"
        :step="0.01"
        :precision="8"
        placeholder="请输入买入价格下限"
        class="w-full"
      />
    </NFormItem>

    <NFormItem label="买入价格步长" path="buyPriceStep">
      <NInputNumber
        v-model:value="form.buyPriceStep"
        :min="0"
        :step="0.01"
        :precision="8"
        placeholder="请输入买入价格步长"
        class="w-full"
      />
    </NFormItem>

    <NFormItem label="是否启用" path="enabled">
      <NSwitch v-model:value="form.enabled">
        <template #checked>启用</template>
        <template #unchecked>禁用</template>
      </NSwitch>
    </NFormItem>

    <NSpace justify="end" class="mt-4">
      <NButton @click="$emit('close')">取消</NButton>
      <NButton type="primary" @click="handleSubmit">更新配置</NButton>
    </NSpace>
  </NForm>
</template>

<style lang="css" scoped></style>
