<template>
  <div class="system-edit-menu-container">
    <el-dialog title="修改部门" v-model="state.isShowDialog" width="769px" draggable>
      <el-form :model="state.ruleForm" ref="ruleFormRef" label-width="80px">
        <el-row :gutter="35">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="部门名称" prop="orgName"
              :rules="[{ required: true, message: '请输入部门名称', trigger: 'blur' }]">
              <el-input v-model="state.ruleForm.orgName" placeholder="请输入部门名称" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="上级部门" prop="parentId"
              :rules="[{ required: true, message: '请选择上级部门', trigger: 'change' }]">
              <el-cascader :options="state.OrgData" filterable
                :props="{ checkStrictly: true, value: 'id', label: 'orgName', emitPath: false }" placeholder="请选择上级部门"
                clearable class="w100" v-model="state.ruleForm.parentId" ref="cascaderRef"
                @change="getselKnowledgeList">
                <template #default="{ node, data }">
                  <span>{{ data.orgName }}</span>
                  <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="是否启用" prop="name" :rules="[{ required: false, message: '请输入角色状态', trigger: 'blur' }]">
              <el-switch v-model="state.ruleForm.isEnable" inline-prompt active-text="启" inactive-text="禁"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel" class="default-button">取 消</el-button>
          <el-button type="primary" @click="onSubmit(ruleFormRef)" v-waves="'light'" :loading="state.loading">修 改
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="systemEditOrg">
import { reactive, ref } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import { storeToRefs } from 'pinia';
import { useUserInfo } from '/@/stores/userInfo';
import { getOrgList, updateOrg, getOrgById } from "/@/api/system/organize";

// 定义接口来定义对象的类型
interface OrgFormState {
  isShowDialog: boolean;
  ruleForm: {
    orgName: string;
    orgCode: string;
    parentId: string;
    parentName: string;
    isEnable: boolean,
    children: Array<any>;
  };
  OrgData: Array<any>;
  loading: boolean;
}

// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList']);

// 定义变量内容
const ruleFormRef = ref<FormInstance>()
const state = reactive<OrgFormState>({
  isShowDialog: false,
  ruleForm: {
    orgName: '',
    orgCode: '',
    parentId: '',
    parentName: '',
    isEnable: true,
    children: []
  },
  OrgData: [], // 上级部门数据
  loading: false,
});
const storesUserInfo = useUserInfo();
const { userInfos } = storeToRefs(storesUserInfo);
// 打开弹窗
const openDialog = (row: any) => {
  if (userInfos.value.authBtnList.includes('100503')) { // 校验是否有权限 获取部门详情
    getOrgList().then((res: any) => {
      state.OrgData = res?.result ?? [];
    })
    ruleFormRef.value?.resetFields();
    getOrgById(row.id).then((res: any) => {
      state.ruleForm = res.result;
      state.isShowDialog = true;
    })
  } else {
    ElMessage.warning('您没有权限获取部门详情');
  }
};
// 关闭弹窗
const closeDialog = () => {
  state.isShowDialog = false;
};
// 取消
const onCancel = () => {
  closeDialog();
};
const cascaderRef = ref();
// 获取选择name值
const getselKnowledgeList = () => {
  let currentNode = cascaderRef.value.getCheckedNodes();
  state.ruleForm.parentName = currentNode[0]?.label ?? '';
}
// 修改
const onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      updateOrg(state.ruleForm).then(() => {
        emit("updateList");
        closeDialog(); // 关闭弹窗
        ElMessage.success('修改成功');
      })

    } else {
      console.log('error submit!', fields)
    }
  })
  // setBackEndControlRefreshRoutes() // 刷新菜单，未进行后端接口测试
};
// 暴露变量
defineExpose({
  openDialog,
  closeDialog
});
</script>
