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

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

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

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

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

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

const emit = defineEmits(['success']);
const neListOptions = getDictOptions(DICT_TYPE.LIC_NE_LIST, 'number');

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

const getTitle = computed(() => {
  if (formData.value?.id) {
    if (formData.value?.action === 1) {
      return $t('license.applyAction', ['License']);
    }
    return $t('ui.actionTitle.edit', ['License']);
  } else {
    return $t('ui.actionTitle.create', ['License']);
  }
});

const getConfirmText = computed(() => {
  return formData.value?.action === 1
    ? $t('license.apply')
    : $t('page.action.confirm');
});

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
      ? neListOptions.map((option) => option.value)
      : [],
    indeterminate: false,
  });
};

watch(
  () => state.checkedList,
  (val) => {
    state.indeterminate = val.length > 0 && val.length < neListOptions.length;
    state.checkAll = val.length === neListOptions.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.neList = state.checkedList;
    const action = formData.value?.action || 0;
    try {
      if (formData.value?.id) {
        await (action === 1 ? applyLicense(data) : updateLicense(data));
      } else {
        await createLicense(data);
      }
      // 关闭并提示
      await modalApi.close();
      emit('success');
      if (action === 1) {
        message.success($t('license.applySuccess'), 3);
      } else {
        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 {
        const action = data.action || 0; // 确保 action 字段存在
        formData.value = { ...data, action };
        data = await getLicense(data.id);
        data = { ...data, action }; // 保持 action 字段
      } finally {
        modalApi.unlock();
      }
    }
    // 处理数据
    data.expiryDate = data.expiryDate ? data.expiryDate.toString() : '';
    // 设置到 values
    formData.value = data;
    state.checkedList = data.neList || [];
    await formApi.setValues(formData.value);
  },
});
</script>

<template>
  <Modal :title="getTitle" class="w-[800px]" :confirm-text="getConfirmText">
    <Form class="mx-4">
      <template #neList="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="neListOptions"
          />
        </a-row>
      </template>
    </Form>
  </Modal>
</template>
