<script setup lang="ts">
import type { FormInstance } from 'element-plus';

import { onMounted, ref } from 'vue';

import { EasyFlowFormModal } from '@easyflow/common-ui';

import {
  ElCheckbox,
  ElCheckboxGroup,
  ElDatePicker,
  ElForm,
  ElFormItem,
  ElMessage,
} from 'element-plus';

import { api } from '#/api/request';
import DictSelect from '#/components/dict/DictSelect.vue';
import { $t } from '#/locales';

// 定义权限接口
interface ResourcePermission {
  id: number;
  title: string;
  requestInterface: string;
}

// 定义表单数据接口
interface Entity {
  apiKey: string;
  status: number | string;
  deptId: number | string;
  expiredAt: Date | null | string;
  permissionIds: (number | string)[]; // 绑定值：权限 ID 数组
  knowledgeShareEnabled: boolean;
  workflowApiEnabled: boolean;
  id?: number; // 编辑时的主键
}

const emit = defineEmits(['reload']);

// 表单实例
const saveForm = ref<FormInstance>();
// 对话框状态
const dialogVisible = ref(false);
const isAdd = ref(true);
// 表单数据（初始化默认值）
const entity = ref<Entity>({
  apiKey: '',
  status: '',
  deptId: '',
  expiredAt: null,
  permissionIds: [],
  knowledgeShareEnabled: false,
  workflowApiEnabled: false,
});
// 加载状态
const btnLoading = ref(false);
// 资源权限列表
const resourcePermissionList = ref<ResourcePermission[]>([]);

// 表单校验规则（必填项校验）
const rules = ref({
  status: [
    {
      required: true,
      message: $t('message.pleaseSelect', { name: $t('sysApiKey.status') }),
      trigger: 'change',
    },
  ],
  expiredAt: [
    {
      required: true,
      message: $t('message.pleaseSelect', { name: $t('sysApiKey.expiredAt') }),
      trigger: 'change',
    },
  ],
});

async function openDialog(row: Partial<Entity> = {}) {
  saveForm.value?.resetFields();
  isAdd.value = !row.id;
  if (!row.id) {
    entity.value = createDefaultEntity(row);
    dialogVisible.value = true;
    return;
  }
  btnLoading.value = true;
  try {
    const res = await api.get('/api/v1/sysApiKey/detail', {
      params: { id: row.id },
    });
    if (res.errorCode !== 0) {
      ElMessage.error(res.message || $t('message.getDataError'));
      return;
    }
    entity.value = createDefaultEntity(res.data || row);
    dialogVisible.value = true;
  } catch {
    ElMessage.error($t('message.getDataError'));
  } finally {
    btnLoading.value = false;
  }
}

// 获取资源权限列表
function getResourcePermissionList() {
  api
    .get('/api/v1/sysApiKeyResourcePermission/list')
    .then((res) => {
      if (res.errorCode === 0) {
        resourcePermissionList.value = res.data;
      } else {
        ElMessage.error(res.message || $t('message.getDataError'));
      }
    })
    .catch(() => {
      ElMessage.error($t('message.getDataError'));
    });
}

function createDefaultEntity(row: Partial<Entity> = {}): Entity {
  const permissionIds = row.permissionIds || [];
  const knowledgeShareEnabled = Boolean(row.knowledgeShareEnabled);
  const workflowApiEnabled = Boolean(row.workflowApiEnabled);
  return {
    apiKey: '',
    status: '',
    deptId: '',
    expiredAt: null,
    ...row,
    permissionIds,
    knowledgeShareEnabled,
    workflowApiEnabled,
  };
}

function renderPermissionLabel(item: ResourcePermission) {
  if (item.requestInterface === '/public-api/bot/chat') {
    return '聊天助手调用';
  }
  if (
    item.requestInterface === '/v1/chat/completions' ||
    item.requestInterface === '/public-api/openai/v1/chat/completions'
  ) {
    return '统一模型调用';
  }
  return item.title;
}

// 保存表单
function save() {
  saveForm.value?.validate((valid) => {
    if (valid) {
      btnLoading.value = true;
      const url = isAdd.value
        ? 'api/v1/sysApiKey/save'
        : 'api/v1/sysApiKey/update';
      api
        .post(url, entity.value)
        .then((res) => {
          btnLoading.value = false;
          if (res.errorCode === 0) {
            ElMessage.success(res.message || $t('message.saveOkMessage'));
            emit('reload');
            closeDialog();
          } else {
            ElMessage.error(res.message || $t('message.saveFailMessage'));
          }
        })
        .catch(() => {
          btnLoading.value = false;
          ElMessage.error($t('message.saveFailMessage'));
        });
    }
  });
}

// 关闭对话框
function closeDialog() {
  saveForm.value?.resetFields();
  // 重置表单数据
  entity.value = {
    apiKey: '',
    status: '',
    deptId: '',
    expiredAt: null,
    permissionIds: [],
    knowledgeShareEnabled: false,
    workflowApiEnabled: false,
  };
  isAdd.value = true;
  dialogVisible.value = false;
}

onMounted(() => {
  getResourcePermissionList();
});

defineExpose({
  openDialog,
});
</script>

<template>
  <EasyFlowFormModal
    v-model:open="dialogVisible"
    :title="isAdd ? $t('button.add') : $t('button.edit')"
    :before-close="closeDialog"
    :confirm-loading="btnLoading"
    :confirm-text="$t('button.save')"
    :submitting="btnLoading"
    width="50%"
    @confirm="save"
  >
    <ElForm
      ref="saveForm"
      :model="entity"
      status-icon
      :rules="rules"
      label-position="top"
      class="easyflow-modal-form easyflow-modal-form--compact form-container"
    >
      <!-- 状态选择 -->
      <ElFormItem prop="status" :label="$t('sysApiKey.status')">
        <DictSelect
          v-model="entity.status"
          dict-code="dataStatus"
          style="width: 100%"
        />
      </ElFormItem>

      <ElFormItem prop="expiredAt" :label="$t('sysApiKey.expiredAt')">
        <ElDatePicker
          v-model="entity.expiredAt"
          type="datetime"
          :placeholder="
            $t('message.pleaseSelect', { name: $t('sysApiKey.expiredAt') })
          "
          style="width: 100%"
        />
      </ElFormItem>

      <ElFormItem
        prop="permissions"
        :label="$t('sysApiKey.permissions')"
        class="permission-form-item"
      >
        <div class="permission-section">
          <ElCheckboxGroup
            v-model="entity.permissionIds"
            class="permission-checkbox-group"
          >
            <ElCheckbox
              v-for="item in resourcePermissionList"
              :key="item.id"
              :value="item.id"
              class="permission-checkbox"
            >
              {{ renderPermissionLabel(item) }}
            </ElCheckbox>
          </ElCheckboxGroup>
          <ElCheckbox
            v-model="entity.knowledgeShareEnabled"
            class="permission-checkbox"
          >
            {{ $t('sysApiKey.knowledgeSharePermission') }}
          </ElCheckbox>
          <ElCheckbox
            v-model="entity.workflowApiEnabled"
            class="permission-checkbox"
          >
            {{ $t('sysApiKey.workflowApiPermission') }}
          </ElCheckbox>
        </div>
      </ElFormItem>
    </ElForm>
  </EasyFlowFormModal>
</template>

<style scoped>
.form-container {
  max-height: 60vh;
  padding-right: 10px;
  overflow-y: auto;
}

.permission-form-item .el-form-item__content {
  display: block;
}

.permission-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
  width: 100%;
}

.permission-checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 16px;
  align-items: flex-start;
}

.permission-checkbox {
  display: flex;
  align-items: flex-start;
  margin: 0;
}

.form-container::-webkit-scrollbar {
  width: 6px;
}

.form-container::-webkit-scrollbar-thumb {
  background-color: #e5e7eb;
  border-radius: 3px;
}
</style>
