<template>
  <el-container>
    <el-main>
      <el-form :model="form.model" :rules="form.rules" ref="formRef" :label-width="formLabelWidth">
        <el-form-item :label="t('modules.auth.roleName')" prop="name">
          <el-input v-model="form.model.name" :placeholder="t('modules.auth.roleRequired')"></el-input>
        </el-form-item>
        <el-form-item :label="t('modules.auth.rolePermissions')" prop="permissionIds">
          <sa-access type="select" :isChangeParentId="isChangeParentId"
            :role_id="props.modal.params.type === 'edit' ? props.modal.params.id : null" :multiple="true"
            v-model="form.model.permissionIds">
          </sa-access>
        </el-form-item>
      </el-form>
    </el-main>
    <el-footer class="sa-footer--submit">
      <el-button v-if="modal.params.type == 'add'" type="primary" @click="confirm">{{ t('common.save') }}</el-button>
      <el-button v-if="modal.params.type == 'edit'" type="primary" @click="confirm">{{ t('common.update') }}</el-button>
    </el-footer>
  </el-container>
</template>
<script setup>
import { reactive, ref, unref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { useFormConfig } from '@/hooks/useFormConfig';
import admin from '@/app/admin/api';
import SaAccess from '../access/components/sa-access.vue';
import { cloneDeep } from 'lodash';

const { t } = useI18n();

// 使用表单配置hooks
const { formLabelWidth } = useFormConfig({ enWidth: '140px' });

const emit = defineEmits(['modalCallBack']);
const props = defineProps({
  modal: {
    type: Object,
  },
});

// 添加 编辑 form
const formRef = ref(null);
const form = reactive({
  model: {
    id: null,
    name: '',
    permissionIds: [], // 权限ID数组，用于sa-access组件
  },
  rules: {
    name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
    permissionIds: [
      {
        required: true,
        validator: (rule, value, callback) => {
          if (!value || !Array.isArray(value) || value.length === 0) {
            callback(new Error('请至少选择一个权限'));
          } else {
            callback();
          }
        },
        trigger: 'change'
      }
    ],
  },
});

const isChangeParentId = ref(false);

// 获取详情
async function getDetail(id) {
  try {
    const { code, data } = await admin.auth.role.detail(id);
    if (code == 200) {
      // 设置基本信息
      form.model.id = data.id;
      form.model.name = data.name;
      form.model.status = data.status || 'normal';

      // 处理权限数据：从permissions数组中提取已选中的权限ID
      if (data.permissions && Array.isArray(data.permissions)) {
        const selectedIds = [];
        const extractSelectedIds = (permissions) => {
          permissions.forEach((permission) => {
            if (permission.hasRelevance === '1') {
              selectedIds.push(permission.id.toString());
            }
            if (permission.children && permission.children.length > 0) {
              extractSelectedIds(permission.children);
            }
          });
        };
        extractSelectedIds(data.permissions);
        form.model.permissionIds = selectedIds;
      } else {
        form.model.permissionIds = [];
      }

      console.log('角色详情数据:', form.model);
      console.log('已选中的权限ID:', form.model.permissionIds);
    }
  } catch (error) {
    console.error('获取详情失败:', error);
    ElMessage.error(t('message.fetchDetailFailed'));
  }
}

// 表单关闭时提交
function confirm() {
  // 表单验证
  unref(formRef).validate(async (valid) => {
    if (!valid) return;

    // 额外检查权限是否为空
    if (!form.model.permissionIds || !Array.isArray(form.model.permissionIds) || form.model.permissionIds.length === 0) {
      ElMessage.warning('请至少选择一个权限');
      return;
    }

    try {
      let submitForm = cloneDeep(form.model);
      console.log('提交的表单数据:', submitForm);

      // 处理权限数据：将权限ID数组转换为逗号分隔的字符串
      if (submitForm.permissionIds && Array.isArray(submitForm.permissionIds)) {
        submitForm.permissionIds = submitForm.permissionIds.join(',');
      } else {
        submitForm.permissionIds = '';
      }

      // 新增时不需要传递id字段
      if (props.modal.params.type === 'add') {
        delete submitForm.id;
      }

      console.log('最终提交数据:', submitForm);

      const { code } =
        props.modal.params.type == 'add'
          ? await admin.auth.role.add(submitForm)
          : await admin.auth.role.edit(submitForm);

      if (code == 200) {
        ElMessage.success(props.modal.params.type == 'add' ? t('message.createSuccess') : t('message.updateSuccess'));
        emit('modalCallBack', { event: 'confirm' });
      }
    } catch (error) {
      console.error('提交失败:', error);
      ElMessage.error(t('message.submitFailed'));
    }
  });
}

onMounted(async () => {
  if (props.modal.params.type == 'edit') {
    await getDetail(props.modal.params.id);
  }
});
</script>
<style lang="scss" scoped>
.sa-access {
  height: 500px;

  :deep() {
    .el-main {
      background: transparent;
    }

    .el-scrollbar {
      border-top: 1px solid var(--sa-border);
      border-bottom: 1px solid var(--sa-border);

      &:first-of-type {
        margin-left: 0;
      }
    }
  }
}
</style>
