<template>
  <div class="p-2">
    <el-card shadow="never">
      <div class="form-container">
        <div class="form-header">
          <div class="header-line"></div>
          <span class="header-title">分组设置</span>
        </div>
        
        <el-form ref="groupFormRef" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="分组名称" prop="groupName" class="required-field">
            <el-input v-model="form.groupName" placeholder="请输入分组名称" maxlength="50" style="width: 400px" />
          </el-form-item>
          
          <el-form-item label="开放插件">
            <div class="plugin-container">
              <el-checkbox-group v-model="form.plugins" class="plugin-group">
                <el-checkbox 
                  v-for="menu in functionMenuList" 
                  :key="menu.id" 
                  :label="menu.id"
                >
                  {{ menu.menuName }}
                </el-checkbox>
              </el-checkbox-group>
              <div class="plugin-tip">不勾选则默认包含所有插件</div>
            </div>
          </el-form-item>
          
          <el-form-item label="是否默认" prop="isDefault">
            <el-radio-group v-model="form.isDefault">
              <el-radio value="1">是</el-radio>
              <el-radio value="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="是否开启" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio value="0">是</el-radio>
              <el-radio value="1">否</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" :loading="buttonLoading" @click="submitForm" class="submit-btn">提交</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup name="AgentGroupForm" lang="ts">
import { getGroup, addGroup, updateGroup } from '@/api/system/agentGroup';
import { GroupForm } from '@/api/system/agentGroup/types';
import { listFunctionMenu } from '@/api/system/functionMenu';
import { FunctionMenuVO } from '@/api/system/functionMenu/types';
import { useRoute } from 'vue-router';
import { useRouter } from 'vue-router';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const route = useRoute();
const router = useRouter();

const buttonLoading = ref(false);
const groupFormRef = ref<ElFormInstance>();
const title = ref('');
const functionMenuList = ref<FunctionMenuVO[]>([]);

const initFormData: any = {
  id: undefined,
  groupName: undefined,
  plugins: [],
  isDefault: '0',
  status: '0',
  sort: 0,
  remark: undefined,
  groupType: undefined
};

const form = ref<any>({ ...initFormData });

const rules = ref<ElFormRules>({
  groupName: [
    { required: true, message: '分组名称不能为空', trigger: 'blur' },
    { min: 2, max: 50, message: '分组名称长度应在 2 到 50 个字符之间', trigger: 'blur' }
  ]
});

/** 获取功能菜单列表 */
const getFunctionMenuList = async () => {
  try {
    const res = await listFunctionMenu();
    functionMenuList.value = res.rows || [];
  } catch (error) {
    console.error('Failed to fetch function menu list:', error);
  }
};

/** 获取详情 */
const getDetail = async (id: string | number) => {
  const res = await getGroup(id);
  const data = res.data;
  
  // 将返回的数据赋值给 form
  Object.assign(form.value, data);
  
  // 如果返回了 menus 列表，提取 id 到 plugins
  if (data.menus && data.menus.length > 0) {
    form.value.plugins = data.menus.map((menu: any) => menu.id);
  }
};

/** 提交按钮 */
const submitForm = () => {
  groupFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        // 构建提交数据，将 plugins 转换为 menuIds
        const submitData = {
          ...form.value,
          menuIds: form.value.plugins && form.value.plugins.length > 0 ? form.value.plugins : []
        };
        
        if (form.value.id) {
          await updateGroup(submitData);
          proxy?.$modal.msgSuccess('修改成功');
        } else {
          await addGroup(submitData);
          proxy?.$modal.msgSuccess('新增成功');
        }
        // 关闭当前页面并返回列表页面
        proxy?.$tab.closePage();
        router.push({ path: '/agent/agentGroup' });
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

/** 取消按钮 */
const cancel = () => {
  proxy?.$tab.closePage();
};

/** 初始化 */
onMounted(async () => {
  // 获取功能菜单列表
  await getFunctionMenuList();
  
  const id = route.query.id as string;
  if (id) {
    title.value = '修改代理分组';
    await getDetail(id);
  } else {
    title.value = '新增代理分组';
    form.value = { ...initFormData };
  }
});
</script>

<style scoped lang="scss">
.card-header {
  font-size: 16px;
  font-weight: bold;
}
</style>

