<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="名称/编码"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="组织状态" prop="state">
          <el-select
            v-model="queryParams.state"
            placeholder="全部"
            clearable
            class="!w-[100px]"
          >
            <el-option :value="0" label="正常" />
            <el-option :value="1" label="禁用" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button class="filter-item" type="primary" @click="handleQuery">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="resetQuery"> <i-ep-refresh />重置 </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          v-hasPerm="['sys:dept:add']"
          type="primary"
          @click="openDialog(undefined, undefined)"
          ><i-ep-plus />新增</el-button
        >
      </template>

      <el-table
        v-loading="loading"
        :data="deptList"
        row-key="id"
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="deptName" align="center" label="组织名称" />
        <el-table-column prop="deptCode" align="center" label="组织编码" />
        <el-table-column prop="orgType" label="组织类型">
          <template #default="scope">
            <el-tag v-if="scope.row.orgType == 0" type="success">公司</el-tag>
            <el-tag v-else type="primary">部门</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态">
          <template #default="scope">
            <el-tag v-if="scope.row.state == 0" type="success">正常</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created" align="center" label="创建时间" />
        <el-table-column label="操作" fixed="right" align="left">
          <template #default="scope">
            <el-button
              v-hasPerm="['sys:dept:add']"
              type="primary"
              link
              size="small"
              @click.stop="openDialog(scope.row.id, undefined)"
              ><i-ep-plus />新增
            </el-button>
            <el-button
              v-hasPerm="['sys:dept:edit']"
              type="primary"
              link
              size="small"
              @click.stop="openDialog(scope.row.parentId, scope.row)"
              ><i-ep-edit />编辑
            </el-button>
            <el-button
              v-hasPerm="['sys:dept:del']"
              type="primary"
              link
              size="small"
              @click.stop="handleDelete(scope.row.id)"
            >
              <i-ep-delete />删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="600px"
      @closed="closeDialog"
    >
      <el-form
        ref="deptFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="上级组织" prop="parentId">
          <el-tree-select
            v-model="formData.parentId"
            placeholder="选择上级组织"
            :data="deptOptions"
            :props="{ value: 'id', label: 'deptName' }"
            filterable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="组织编码" prop="deptCode">
          <el-input
            v-model="formData.deptCode"
            :disabled="dialog.title === '修改组织'"
            placeholder="请输入组织编码"
          />
        </el-form-item>
        <el-form-item label="组织名称" prop="deptName">
          <el-input v-model="formData.deptName" placeholder="请输入组织名称" />
        </el-form-item>
        <el-form-item label="组织类别">
          <el-radio-group v-model="formData.orgType">
            <el-radio :value="0">公司</el-radio>
            <el-radio :value="1">部门</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="组织状态">
          <el-radio-group v-model="formData.state">
            <el-radio :value="0">正常</el-radio>
            <el-radio :value="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit"> 确 定 </el-button>
          <el-button @click="closeDialog"> 取 消 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  deleteDept,
  updateDept,
  addDept,
  queryTreeList,
  treeList,
} from "@/api/system/dept";

defineOptions({
  name: "Dept",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const deptFormRef = ref(ElForm);
const loading = ref(false);
const ids = ref<number[]>([]);
const dialog = reactive({
  title: "",
  visible: false,
});

const queryParams = reactive<any>({});
const deptList = ref([]);

const deptOptions = ref([]);

const formData = reactive<any>({
  status: 1,
  parentId: 0,
  sort: 1,
});

const rules = reactive({
  parentId: [{ required: true, message: "顶级组织不能为空", trigger: "blur" }],
  deptName: [{ required: true, message: "组织名称不能为空", trigger: "blur" }],
  deptCode: [{ required: true, message: "组织编码不能为空", trigger: "blur" }],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  queryTreeList(queryParams).then((data) => {
    deptList.value = data.data;
    loading.value = false;
  });
}

/**重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/** 获取组织下拉数据  */
async function loadDeptOptions() {
  treeList().then((response) => {
    deptOptions.value = [
      {
        id: "0",
        deptName: "顶级组织",
        children: response.data,
      },
    ];
  });
}

/**
 * 打开弹窗
 *
 * @param parentId 父组织ID
 * @param dept 组织
 */
async function openDialog(parentId?: number, dept?: any) {
  await loadDeptOptions();
  dialog.visible = true;
  if (dept !== undefined) {
    dialog.title = "修改组织";
    Object.assign(formData, dept);
  } else {
    dialog.title = "新增组织";
    formData.deptCode = "";
    formData.deptName = "";
    formData.orgType = 0;
    formData.state = 0;
    formData.parentId = parentId ?? "0";
  }
}

/** 表单提交 */
function handleSubmit() {
  deptFormRef.value.validate((valid: any) => {
    if (valid) {
      const deptId = formData.id;
      loading.value = true;
      if (deptId) {
        updateDept(formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        addDept(formData)
          .then(() => {
            ElMessage.success("新增成功");
            closeDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 删除组织 */
function handleDelete(deptId?: number) {
  const deptIds = [deptId || ids.value];

  if (!deptIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  const params = { ids: deptIds };
  ElMessageBox.confirm(`确认删除已选中的数据项?`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteDept(params).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

/** 关闭弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/** 重置表单  */
function resetForm() {
  deptFormRef.value.resetFields();
  deptFormRef.value.clearValidate();

  formData.id = undefined;
  formData.parentId = "0";
  formData.status = 1;
}

onMounted?.(() => {
  handleQuery();
});
</script>
