<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue';
import type { OptionValue } from 'naive-ui/es/transfer/src/interface';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import OperateDrawer from '@/components/common/operate-drawer.vue';
import { $t } from '@/locales';
import { fetchGetAllGroupConfigList } from '@/service/api';
import {systemVariableTypeOptions} from '@/constants/business';
import {fetchEditVariable,fetchAddVariable} from "@/service/api/system-variable";

defineOptions({
  name: 'SystemVariableOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.SystemVariable.SystemVariable | null;
}

const valueRef = ref();
const groupConfigs = ref();
const updatePass = ref<number>(0);

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

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

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: $t('page.system_variable.addVariable'),
    edit: $t('page.system_variable.editVariable')
  };
  return titles[props.operateType];
});

type Model = Pick<
  Api.SystemVariable.SystemVariable,
  'id' | 'variableName' | 'variableKey' | 'variableValue' | 'variableType' | 'description'
>;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    variableName: '',
    variableKey: '',
    variableValue: '',
    variableType: 1,
    description: ''
  };
}

type RuleRecord = Partial<Record<keyof Model, App.Global.FormRule[]>>;

const rules: Record<RuleKey, App.Global.FormRule> = {

    variableName: defaultRequiredRule,
    variableKey: defaultRequiredRule,
    variableValue: defaultRequiredRule,
    variableType: defaultRequiredRule,
    description: defaultRequiredRule

};

function handleUpdateModelWhenEdit() {
  if (props.operateType === 'add') {
    Object.assign(model, createDefaultModel());
    return;
  }

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  // request
  if (props.operateType === 'add') {
    const {
      variableKey,
      variableName,
      variableValue,
      variableType,
      description } = model;
    const { error } = await fetchAddVariable({
      variableKey,
      variableName,
      variableValue,
      variableType,
      description
    });
    if (error) return;
    window.$message?.success($t('common.addSuccess'));
  }

  if (props.operateType === 'edit') {
    const { id, variableKey,variableName,variableValue,variableType,description } = model;
    const { error } = await fetchEditVariable({
      id,
      variableKey,
      variableName,
      variableValue,
      variableType,
      description
    });
    if (error) return;
    window.$message?.success($t('common.updateSuccess'));
  }

  closeDrawer();
  emit('submitted');
}

const getAllGroupConfigList = async () => {
  const res = await fetchGetAllGroupConfigList([]);
  groupConfigs.value = res.data?.map(option => ({
    value: `${option.groupName}@${option.namespaceId}`,
    label: `${option.groupName}(${option.namespaceName})`
  }));
};

onMounted(() => {
  // 加载组列表数据
  getAllGroupConfigList();
});

watch(visible, () => {
  if (visible.value) {
    handleUpdateModelWhenEdit();
    restoreValidation();
  }
});

</script>

<template>
  <OperateDrawer v-model="visible" :title="title" @submitted="handleSubmit">
    <NForm ref="formRef" :model="model" :rules="rules">
      <NFormItem :label="$t('page.system_variable.variableName')" >
        <NInput
          v-model:value="model.variableName"
          :placeholder="$t('page.system_variable.form.variableName')" />
      </NFormItem>
      <NFormItem :label="$t('page.system_variable.variableType')" path="variableType">
        <NRadioGroup v-model:value="model.variableType" name="initScene">
          <NSpace>
            <NRadio
              v-for="item in systemVariableTypeOptions"
              :key="item.value"
              :value="item.value"
              :label="$t(item.label)"
            />
          </NSpace>
          <example-expression />
        </NRadioGroup>
<!--        <NPopover trigger="hover"-->
<!--        >-->
<!--          <template #trigger>-->
<!--            <NButton text>-->
<!--              <SvgIcon icon="ant-design:info-circle-outlined" class="text-18px color-blue" />-->
<!--            </NButton>-->
<!--          </template>-->
<!--          输入$提示变量信息-->
<!--        </NPopover>-->
      </NFormItem>
      <NFormItem :label="$t('page.system_variable.variableKey')" path="variableKey">
        <NInput v-model:value="model.variableKey" :placeholder="$t('page.system_variable.form.variableKey')" />
      </NFormItem>
      <NFormItem :label="$t('page.system_variable.variableValue')" path="variableValue">
        <NInput v-model:value="model.variableValue" :placeholder="$t('page.system_variable.form.variableValue')" />
      </NFormItem>
      <NFormItem :label="$t('page.system_variable.description')" path="description">
        <NInput v-model:value="model.description" :placeholder="$t('page.system_variable.form.description')" />
      </NFormItem>
    </NForm>
    <template #footer>
      <NSpace :size="16">
        <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
        <NButton type="primary" @click="handleSubmit">{{ $t('common.save') }}</NButton>
      </NSpace>
    </template>
  </OperateDrawer>
</template>

<style scoped></style>
