<template>
  <el-container>
    <el-main>
      <el-form :model="form.model" :rules="form.rules" ref="formRef" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.model.name" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色说明">
          <el-input
            type="textarea"
            maxlength="200"
            show-word-limit
            v-model="form.model.description"
            placeholder="请输入角色说明"
          ></el-input>
        </el-form-item>
        <el-form-item label="权限信息">
          <sa-access
            type="select"
            :isChangeParentId="isChangeParentId"
            :role_id="form.model.parent_id"
            :multiple="true"
            v-model="form.model.rules"
          >
          </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">保存</el-button>
      <el-button v-if="modal.params.type == 'edit'" type="primary" @click="confirm">更新</el-button>
    </el-footer>
  </el-container>
</template>
<script setup>
  import { reactive, ref, unref, onMounted } from 'vue';
  import { ElMessage } from 'element-plus';
  import { roleMockData } from '@/sheep/mock/role';
  import SaAccess from '../access/components/sa-access.vue';
  import { cloneDeep } from 'lodash';

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

  // 添加 编辑 form
  const formRef = ref(null);
  const form = reactive({
    model: {
      parent_id: '',
      name: '',
      description: '',
      status: 'normal',
      rules: [],
    },
    rules: {
      name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
    },
  });

  const isChangeParentId = ref(false);

  // 获取详情
  async function getDetail(id) {
    try {
      const result = roleMockData.getDetail(id);
      if (result.code == '200') {
        form.model = { ...result.data };

        // 确保rules是数组格式，用于sa-access组件
        if (!form.model.rules || !Array.isArray(form.model.rules)) {
          form.model.rules = [];
        }

        console.log('角色详情数据:', form.model);
      } else {
        ElMessage.error(result.msg);
      }
    } catch (error) {
      console.error('获取详情失败:', error);
      ElMessage.error('获取详情失败');
    }
  }

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

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

        // 处理权限数据，从rules数组中提取权限信息
        if (submitForm.rules && submitForm.rules.length > 0) {
          const permissions = [];
          const extractPermissions = (rules) => {
            rules.forEach((rule) => {
              if (rule.title && rule.checked) {
                permissions.push(rule.title);
              }
              if (rule.children && rule.children.length > 0) {
                extractPermissions(rule.children);
              }
            });
          };
          extractPermissions(submitForm.rules);
          submitForm.permissions = permissions;
          submitForm.permissions_text = permissions.join('、');
        }

        const result =
          props.modal.params.type == 'add'
            ? roleMockData.create(submitForm)
            : roleMockData.update(props.modal.params.id, submitForm);

        if (result.code == '200') {
          ElMessage.success(props.modal.params.type == 'add' ? '创建成功' : '更新成功');
          emit('modalCallBack', { event: 'confirm' });
        } else {
          ElMessage.error(result.msg);
        }
      } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error('提交失败');
      }
    });
  }

  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>
