<script lang="ts" setup>
import type { SelectProps } from 'ant-design-vue';

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,
  reapplyLicense,
} from '#/api/license/license';
import { $t } from '#/locales';
import { DICT_TYPE, getDictOptions } from '#/utils';

import NeCode from '../components/ne-code.vue';
import { formData, useFormSchema } from '../data';

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

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

const neCodeRef = ref();

const getTitle = computed(() => {
  return formData.value?.id
    ? $t('license.reapplyAction', ['License'])
    : $t('license.applyAction', ['License']);
});

const getConfirmText = computed(() => {
  return formData.value?.id ? $t('license.reapply') : $t('license.apply');
});

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    // formItemClass: 'col-span-2',
    labelWidth: 80,
  },
  layout: 'horizontal',
  // fieldMappingTime: [['field4', ['phoneType', 'phoneNumber'], null]],
  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();
    try {
      await neCodeRef.value[0].validate();
    } catch {
      return;
    }
    if (!valid) {
      return;
    }
    modalApi.lock();
    // 提交表单
    const data = (await formApi.getValues()) as LicenseApi.License;
    data.neList = state.checkedList;
    data.neCodeList = state.neCodeList;
    try {
      await (formData.value?.id ? reapplyLicense(data) : createLicense(data));
      // 关闭并提示
      await modalApi.close();
      emit('success');
      message.success($t('license.applySuccess'), 3);
    } 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.setState({ loading: true });
      data = await getLicense(data.id);
    }
    // 处理数据
    data.expiryDate = data.expiryDate ? data.expiryDate.toString() : '';
    // 设置到 values
    formData.value = data;
    state.checkedList = data.neList || [];
    state.neCodeList = data.neCodeList || [
      { neList: [], activationCode: '', id: 1 },
    ];
    await formApi.setValues(formData.value);
    modalApi.setState({ loading: false });
  },
});

const options = ref<SelectProps['options']>([
  {
    label: '一体化',
    options: getDictOptions(DICT_TYPE.LIC_NE_ALL, 'number'),
  },
  {
    label: '5G',
    options: getDictOptions(DICT_TYPE.LIC_NE_5G, 'number'),
  },
  {
    label: '4G',
    options: getDictOptions(DICT_TYPE.LIC_NE_4G, 'number'),
  },
  {
    label: '2/3G',
    options: getDictOptions(DICT_TYPE.LIC_NE_23G, 'number'),
  },
  {
    label: '增值业务',
    options: getDictOptions(DICT_TYPE.LIC_NE_ADD, 'number'),
  },
]);

let nextId = 2;

const removeNeCode = (item: LicenseApi.NeCode) => {
  const index = state.neCodeList.indexOf(item);
  if (index !== -1) {
    state.neCodeList.splice(index, 1);
  }
};
const addNeCode = () => {
  state.neCodeList.push({
    neList: [],
    activationCode: '',
    id: nextId++,
  });
};
const availableOptions = (groupIdx: number) => {
  // 其他分组已选标签
  const otherSelected = new Set(
    state.neCodeList
      .filter((_, idx) => idx !== groupIdx)
      .flatMap((g) => g.neList),
  );
  const aaaa = options.value?.map((item) => ({
    ...item,
    options: item.options.filter(
      (option: any) => !otherSelected.has(option.value),
    ),
  }));
  return aaaa;
};
</script>

<template>
  <Modal :title="getTitle" class="w-2/3" :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>
      <template #neCodeList="slotProps">
        <NeCode
          v-bind="slotProps"
          @add-ne-code="addNeCode"
          @remove-ne-code="removeNeCode"
          :ne-code-list="state.neCodeList"
          :available-options="availableOptions"
          ref="neCodeRef"
          v-model:value="state.neCodeList"
        />
      </template>
    </Form>
  </Modal>
</template>
