<template>
  <el-container>
    <el-main>
      <el-form v-loading="loading" :model="form.model" :rules="form.rules" ref="formRef" :label-width="formLabelWidth">
        <!-- <el-form-item label="父级" prop="parent_id">
          <el-cascader
            ref="parentCascader"
            v-model="form.model.parent_id"
            :options="access.select"
            :props="{
              label: 'title',
              value: 'id',
              checkStrictly: true,
              emitPath: false,
            }"
            clearable
            placeholder="请选择"
            disabled
          ></el-cascader>
        </el-form-item> -->
        <el-form-item :label="t('modules.auth.permissionType')" prop="type">
          <el-radio-group v-model="form.model.type" @change="changeType">
            <el-radio label="1">{{ t('menu.menu') }}</el-radio>
            <el-radio label="2">{{ t('menu.page') }}</el-radio>
            <el-radio label="4">{{ t('menu.action') }}</el-radio>
            <!-- <el-radio label="3">页面</el-radio> -->
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="t('common.title')" prop="title">
          <el-input v-model="form.model.title" :placeholder="t('common.enterName')"></el-input>
        </el-form-item>
        <el-form-item :label="t('common.identifier')" prop="name">
          <el-input v-model="form.model.name" :placeholder="t('common.enterUniqueIdentifier')"></el-input>
        </el-form-item>
        <el-form-item :label="t('modules.auth.url')" prop="url">
          <el-input v-model="form.model.url" :placeholder="t('common.enterShortPath')"></el-input>
        </el-form-item>
        <el-form-item v-if="form.model.type != 'api'" :label="t('modules.auth.icon')" prop="icon">
          <sa-uploader v-model="form.model.icon" mode="input" fileType="image"
            :text="t('common.selectIcon')"></sa-uploader>
        </el-form-item>
        <!-- <el-form-item v-if="form.model.type != 'api'" label="跳转地址" prop="url">
          <el-input v-model="form.model.url" placeholder="请输入跳转地址"></el-input>
        </el-form-item> -->
        <el-form-item :label="t('common.weight')" prop="weigh">
          <el-input v-model="form.model.weigh" :placeholder="t('common.enterWeight')" type="number"></el-input>
        </el-form-item>
        <el-form-item :label="t('common.status')" prop="status">
          <div>
            <el-radio-group v-model="form.model.status">
              <el-radio label="normal">{{ t('common.normal') }}</el-radio>
              <el-radio label="disabled">{{ t('common.disabled') }}</el-radio>
            </el-radio-group>
            <div class="tip">
              <div>{{ t('common.normal') }}:{{ t('modules.auth.normalTip') }}</div>
              <div>{{ t('common.disabled') }}:{{ t('modules.auth.disabledTip') }}</div>
            </div>
          </div>
        </el-form-item>
        <el-form-item v-if="form.model.type == 'page' && !modal.params.id" :label="t('common.includePermissions')">
          <div class="sa-template-wrap">
            <div class="title sa-flex">
              <div class="key">{{ t('common.name') }}</div>
              <div class="value">{{ t('common.identifier') }}</div>
              <div class="oper">{{ t('common.operation') }}</div>
            </div>
            <sa-draggable v-model="form.model.api" :animation="300" handle=".sortable-drag" item-key="element">
              <template #item="{ element, index }">
                <div class="item">
                  <el-form-item class="key" :prop="'api.' + index + '.title'" :rules="templateRules.title">
                    <el-input :placeholder="t('common.enterName')" v-model="element.title"></el-input>
                  </el-form-item>
                  <el-form-item class="value" :prop="'api.' + index + '.name'" :rules="templateRules.name">
                    <el-input :placeholder="t('common.enterIdentifier')" v-model="element.name"></el-input>
                  </el-form-item>
                  <el-form-item class="oper">
                    <el-button @click="deleteTemplate(index)" type="danger" plain>{{ t('common.delete') }}</el-button>
                    <sa-svg class="sa-m-l-8 sortable-drag" name="sa-round"></sa-svg>
                  </el-form-item>
                </div>
              </template>
            </sa-draggable>
            <el-button @click="addTemplate()" class="sa-m-l-16" type="primary" plain icon="Plus">{{ t('common.add')
            }}</el-button>
            <el-button v-if="form.model.api.length == 0" @click="addCurd()" class="sa-m-l-16" type="success" plain
              icon="Plus">CRUD</el-button>
          </div>
        </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 { onMounted, reactive, ref, unref } from 'vue';
import { doUnique } from '@/sheep/utils/index.js';
import admin from '@/app/admin/api';
import SaDraggable from 'vuedraggable';
import { cloneDeep } from 'lodash';
import { useI18n } from 'vue-i18n';
import { useFormConfig } from '@/hooks/useFormConfig';
import { ElMessage } from 'element-plus';

const { t } = useI18n();

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

const apiCrud = [
  {
    title: '查看',
    name: 'list',
  },
  {
    title: '详情',
    name: 'detail',
  },
  {
    title: '新建',
    name: 'add',
  },
  {
    title: '编辑',
    name: 'edit',
  },
  {
    title: '删除',
    name: 'delete',
  },
];

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

// 添加 编辑 form
let formRef = ref(null);
const form = reactive({
  model: {
    parent_id: props.modal.params.parent_id || '',
    title: '',
    type: '1',
    name: '',
    eName: '',
    icon: '',
    url: '',
    status: 'normal',
    weigh: '',
    api: [],
  },
  rules: {
    title: [{ required: true, message: t('common.enterName'), trigger: 'blur' }],
    name: [{ required: true, message: t('common.enterIdentifier'), trigger: 'blur' }],
  },
});
// api 表单规则
const templateRef = ref(null);
const templateRules = {
  title: [{ required: true, message: t('common.enterName'), trigger: 'blur' }],
  name: [{ required: true, message: t('common.enterIdentifier'), trigger: 'blur' }],
};

const loading = ref(false);

// 数据转换函数：将新接口数据转换为表单需要的格式
function transformDetailData(data) {
  return {
    parent_id: data.parentId || null,
    title: data.name || '', // 使用name作为title
    type: data.type, // 转换type格式
    name: data.composingKey || '', // 使用composingKey作为标识
    icon: data.logo || '',
    url: data.url || '', // 跳转地址
    status: getFormStatus(data.status), // 转换status格式
    weigh: data.seq || 0, // 使用seq作为权重
    api: [], // API权限暂时为空，可根据需要扩展
  };
}

// 转换status字段：数字转换为字符串
function getFormStatus(status) {
  const statusMap = {
    0: 'normal', // 正常
    1: 'disabled', // 禁用
  };
  return statusMap[String(status)] || 'normal';
}

// 获取详情
async function getDetail(id) {
  loading.value = true;
  try {
    const response = await admin.auth.access.detail(id);

    if (response.success && response.data) {
      // 转换数据格式
      form.model = transformDetailData(response.data);
    } else {
      console.error('获取权限详情失败:', response.message);
    }
  } catch (error) {
    console.error('获取权限详情异常:', error);
  }

  loading.value = false;
}
function changeType(e) {
  if (e != 'page') form.model.api = [];
}

// 添加权限
function addTemplate() {
  form.model.api.push({
    title: '',
    name: '',
  });
}
function addCurd() {
  form.model.api = [].concat(form.model.api, apiCrud);
}
function deleteTemplate(index) {
  form.model.api.splice(index, 1);
}

// 转换提交数据：将表单数据转换为后端需要的格式
function transformSubmitData(formData) {
  const isAdd = props.modal.params.type == 'add' || props.modal.params.type == 'append';

  return {
    id: isAdd ? 0 : props.modal.params.id || 0, // 新增时ID为0，编辑时传递原ID
    parentId: formData.parent_id || '',
    name: formData.title || '', // 使用title作为name
    eName: formData.eName || '', // 使用title作为eName
    logo: formData.icon || '',
    composingKey: formData.name || '', // 使用name作为composingKey
    type: formData.type, // 转换type格式
    status: getSubmitStatus(formData.status), // 转换status格式
    seq: formData.weigh || 0, // 使用weigh作为seq
    url: formData.url || '', // 跳转地址
    isAction: formData.type === 'api' ? '1' : '0', // 是否为动作
    children: [], // 子节点为空数组
    createTime: '', // 创建时间由后端处理
    createUserId: '', // 创建用户由后端处理
    updateTime: '', // 更新时间由后端处理
    updateUserId: '', // 更新用户由后端处理
  };
}

// 转换status字段：字符串转换为数字
function getSubmitStatus(status) {
  const statusMap = {
    normal: 0, // 正常
    disabled: 1, // 禁用
  };
  return statusMap[status] || 0;
}

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

    // 转换提交数据格式
    let submitForm = transformSubmitData(form.model);

    const { code, data } =
      props.modal.params.type == 'add' || props.modal.params.type == 'append'
        ? await admin.auth.access.add(submitForm)
        : await admin.auth.access.edit(submitForm);
    ElMessage.success(props.modal.params.type == 'add' ? t('message.createSuccess') : t('message.updateSuccess'));
    code == '200' && emit('modalCallBack', { event: 'confirm', data });
  });
}

onMounted(async () => {
  if (props.modal.params.type == 'edit') {
    await getDetail(props.modal.params.id);
  }
});
</script>
