<script lang="ts" setup>
import type { LicenseApi } from '#/api/license/license';

import { computed, reactive, ref, watch } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import {
  createLicense,
  getLicense,
  updateLicense,
} from '#/api/license/license';
import { $t } from '#/locales';
import { DICT_TYPE, getDictOptions } from '#/utils';

import { useFormSchema } from '../data';

const emit = defineEmits(['success']);
const neSwitchOptions = getDictOptions(DICT_TYPE.LIC_NE_SWITCH, 'number');
const formData = ref<LicenseApi.License>();

const state = reactive({
  indeterminate: false,
  checkAll: false,
  checkedList: [] as number[],
});

const getTitle = computed(() => {
  return formData.value?.id
    ? $t('ui.actionTitle.edit', ['License'])
    : $t('ui.actionTitle.create', ['License']);
});

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    // formItemClass: 'col-span-2',
    labelWidth: 80,
  },
  layout: 'horizontal',
  schema: useFormSchema(),
  showDefaultActions: false,
  // 大屏一行显示3个，中屏一行显示2个，小屏一行显示1个
  wrapperClass: 'grid-cols-1 md:grid-cols-2',
});

const onCheckAllChange = (e: any) => {
  Object.assign(state, {
    checkedList: e.target.checked
      ? neSwitchOptions.map((option) => option.value)
      : [],
    indeterminate: false,
  });
};

watch(
  () => state.checkedList,
  (val) => {
    state.indeterminate = val.length > 0 && val.length < neSwitchOptions.length;
    state.checkAll = val.length === neSwitchOptions.length;
  },
);

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    modalApi.lock();
    // 提交表单
    const data = (await formApi.getValues()) as LicenseApi.License;
    data.neSwitch = state.checkedList;
    try {
      await (formData.value?.id ? updateLicense(data) : createLicense(data));
      // 关闭并提示
      await modalApi.close();
      emit('success');
      message.success($t('ui.actionMessage.operationSuccess'));
    } finally {
      modalApi.unlock();
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      formData.value = undefined;
      return;
    }
    // 加载数据
    let data = modalApi.getData<LicenseApi.License>();
    if (!data) {
      return;
    }
    if (data.id) {
      modalApi.lock();
      try {
        data = await getLicense(data.id);
      } finally {
        modalApi.unlock();
      }
    }
    // 处理数据
    data.expirationTime = data.expirationTime
      ? data.expirationTime.toString()
      : '';
    // 设置到 values
    formData.value = data;
    state.checkedList = data.neSwitch || [];
    await formApi.setValues(formData.value);
  },
});
</script>

<template>
  <Modal :title="getTitle" class="w-[800px]">
    <Form class="mx-4">
      <template #neSwitch="slotProps">
        <a-row>
          <div>
            <a-checkbox
              v-model:checked="state.checkAll"
              :indeterminate="state.indeterminate"
              @change="onCheckAllChange"
            >
              {{ $t('license.checkAll') }}
            </a-checkbox>
          </div>
          <a-divider style="margin: 10px 0" />
          <a-checkbox-group
            v-bind="slotProps"
            v-model:value="state.checkedList"
            :options="neSwitchOptions"
          />
        </a-row>
      </template>
    </Form>
  </Modal>
</template>
