<template>
  <a-modal
    ref="formDataRef"
    v-model:visible="visible"
    :ok-loading="loading"
    @before-ok="handleOk"
    @cancel="handleCancel"
  >
    <template #title>
      {{ isNull(props.rule) || props.rule.id === 0 ? '新增' : '编辑' }}规则
    </template>
    <a-form ref="formDataRef" :model="formData">
      <a-form-item field="name" label="名称" required>
        <a-input v-model="formData.name" />
      </a-form-item>
      <a-form-item field="roadUid" label="通道" required>
        <a-select v-model="formData.roadUid">
          <a-option
            v-for="(item, index) in state.roadInfos"
            :key="index"
            :label="item.roadName"
            :value="item.roadUid"
          />
        </a-select>
      </a-form-item>
      <a-form-item field="merchantUid" label="商户" required>
        <a-select v-model="formData.merchantUid">
          <a-option
            v-for="(item, index) in state.merchantInfos"
            :key="index"
            :label="item.merchantName"
            :value="item.merchantUid"
          />
        </a-select>
      </a-form-item>
      <a-form-item field="amount" label="金额(元)" required>
        <a-input-number v-model="formData.amount" />
      </a-form-item>
      <a-form-item field="faceAmount" label="面额(元)" required>
        <a-input-number v-model="formData.faceAmount" />
      </a-form-item>
      <a-form-item field="amountRule" label="金额规则" required>
        <a-input-tag v-model="formData.amountRule" />
      </a-form-item>
      <a-form-item field="delayDurationMin" label="延迟时间(秒)" required>
        <a-space>
          <a-input-number
            v-model="formData.delayDurationMin"
            placeholder="最小延迟时间"
          />
          <a-input-number
            v-model="formData.delayDurationMax"
            placeholder="最大延迟时间"
          />
        </a-space>
      </a-form-item>
      <a-form-item field="strategy" label="策略" required>
        <a-select v-model="formData.strategy">
          <a-option :value="1" label="策略1：创建空白订单" />
          <a-option :value="2" label="策略2：创建延迟订单" />
          <a-option :value="3" label="策略3：随机" />
        </a-select>
      </a-form-item>
      <a-form-item field="enable" label="是否启用" required>
        <a-switch
          v-model="formData.enable"
          :checked-value="1"
          :unchecked-value="0"
        >
          <template #checked-icon>
            <icon-check />
          </template>
          <template #unchecked-icon>
            <icon-close />
          </template>
        </a-switch>
      </a-form-item>
      <a-form-item field="extraReturnInfo" label="销卡信息">
        <a-input v-model="formData.extraReturnInfo" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { apiClient } from '@/api';
import {
  KamiApiMerchantV1StealCreateReq,
  KamiApiMerchantV1MerchantHiddenConfigEntity,
  KamiApiRoadV1RoadSimpleInfo,
  KamiInternalModelEntityV1MerchantInfo
} from '@/api/generated';
import useLoading from '@/hooks/loading';
import { isNull, isUndefined } from '@/utils/is';
import { FormInstance, Message } from '@arco-design/web-vue';
import { onMounted, PropType, reactive, ref, watch } from 'vue';

const props = defineProps({
  rule: {
    type: Object as PropType<
      Required<KamiApiMerchantV1MerchantHiddenConfigEntity>
    >,
    default: () => ({})
  }
});

const generateFormData = (): KamiApiMerchantV1StealCreateReq => {
  return {
    name: '',
    roadUid: null,
    merchantUid: null,
    amount: 0,
    faceAmount: 0,
    delayDurationMin: 0,
    delayDurationMax: 0,
    enable: 0,
    amountRule: [],
    strategy: null,
    extraReturnInfo: ''
  };
};

const visible = defineModel<boolean>('visible', {
  type: Boolean,
  default: false
});

const state = reactive<{
  roadInfos: KamiApiRoadV1RoadSimpleInfo[];
  merchantInfos: KamiInternalModelEntityV1MerchantInfo[];
}>({
  roadInfos: [],
  merchantInfos: []
});
const formData = ref<KamiApiMerchantV1StealCreateReq>(generateFormData());
const formDataRef = ref<FormInstance>();

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

const handleOk = (done: (closed: boolean) => void) => {
  formDataRef.value.validate().then(async res => {
    if (res) return done(false);
    // 面额不能大于金额
    if (formData.value.faceAmount > formData.value.amount) {
      Message.error({
        content: '面额不能大于金额'
      });
      return done(false);
    }
    try {
      setLoading(true);
      if (isNull(props.rule) || isUndefined(props.rule)) {
        await apiClient.apiMerchantConfigStealRuleCreatePost({
          kamiApiMerchantV1StealCreateReq: formData.value
        });
      } else {
        await apiClient.apiMerchantConfigStealRuleUpdatePost({
          kamiApiMerchantV1StealUpdateReq: {
            id: props.rule.id,
            ...formData.value
          }
        });
      }
      done(true);
      visible.value = false;
      formData.value = generateFormData();
    } catch (error) {
      done(false);
    } finally {
      setLoading(false);
    }
  });
};
const handleCancel = () => {
  visible.value = false;
  formData.value = generateFormData();
};
watch(
  () => props.rule,
  () => {
    if (!isNull(props.rule) && !isUndefined(props.rule)) {
      formData.value = { ...props.rule };
    } else {
      formData.value = generateFormData();
    }
  }
);
onMounted(() => {
  apiClient.apiRoadSimpleGetAllGet().then(res => {
    state.roadInfos = res.data.list;
  });
  apiClient
    .apiMerchantListAllGet()
    .then(res => (state.merchantInfos = res.data.list));
});
</script>
