<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="项目类型名称" prop="typeName">
              <el-input v-model="queryParams.typeName" placeholder="请输入项目类型名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
<!--            <el-form-item label="备件标识" prop="spareFlag">-->
<!--              <el-select v-model="queryParams.spareFlag" placeholder="请选择备件标识" clearable>-->
<!--                <el-option v-for="dict in spare_flag" :key="dict.value" :label="dict.label" :value="dict.value" />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
            <el-form-item label="顶级标识" prop="topFlag">
              <el-select v-model="queryParams.topFlag" placeholder="请选择顶级标识" clearable>
                <el-option v-for="dict in top_flag" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['oa/erp:projectType:add']"> 新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table
        ref="projectTypeTableRef"
        v-loading="loading"
        :data="projectTypeList"
        row-key="typeName"
        border
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
<!--        <el-table-column label="父级ID" align="center" prop="parentId" />-->
        <el-table-column label="项目类型名称" align="left" prop="typeName" />
<!--        <el-table-column label="排序号" align="center" prop="sortOrder" />-->
        <el-table-column label="备件标识" align="center" prop="spareFlag">
          <template #default="scope">
            <dict-tag :options="spare_flag" :value="scope.row.spareFlag" />
          </template>
        </el-table-column>
        <el-table-column label="顶级标识" align="center" prop="topFlag">
          <template #default="scope">
            <dict-tag :options="top_flag" :value="scope.row.topFlag" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['oa/erp:projectType:edit']" />
            </el-tooltip>
            <el-tooltip content="新增" placement="top">
              <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['oa/erp:projectType:add']" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['oa/erp:projectType:remove']" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加或修改项目类型信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="projectTypeFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="父级ID" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="projectTypeOptions"
            :props="{ value: 'projectTypeId', label: 'typeName', children: 'children' }"
            value-key="projectTypeId"
            placeholder="请选择父级ID"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="项目类型名称" prop="typeName">
          <el-input v-model="form.typeName" placeholder="请输入项目类型名称" />
        </el-form-item>
<!--        <el-form-item label="排序号" prop="sortOrder">-->
<!--          <el-input v-model="form.sortOrder" placeholder="请输入排序号" />-->
<!--        </el-form-item>-->
        <el-form-item label="备件标识" prop="spareFlag">
          <el-radio-group v-model="form.spareFlag">
            <el-radio v-for="dict in spare_flag" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="顶级标识" prop="topFlag">
          <el-radio-group v-model="form.topFlag">
            <el-radio v-for="dict in top_flag" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ProjectType" lang="ts">
import { listProjectType, getProjectType, delProjectType, addProjectType, updateProjectType } from '@/api/oa/erp/projectType';
import { ProjectTypeVO, ProjectTypeQuery, ProjectTypeForm } from '@/api/oa/erp/projectType/types';

type ProjectTypeOption = {
  projectTypeId: number;
  typeName: string;
  children?: ProjectTypeOption[];
};

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { top_flag, spare_flag } = toRefs<any>(proxy?.useDict('top_flag', 'spare_flag'));

const projectTypeList = ref<ProjectTypeVO[]>([]);
const projectTypeOptions = ref<ProjectTypeOption[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(true);
const isExpandAll = ref(true);
const loading = ref(false);

const queryFormRef = ref<ElFormInstance>();
const projectTypeFormRef = ref<ElFormInstance>();
const projectTypeTableRef = ref<ElTableInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ProjectTypeForm = {
  projectTypeId: undefined,
  parentId: undefined,
  typeName: undefined,
  sortOrder: undefined,
  spareFlag: undefined,
  remark: undefined,
  topFlag: undefined
};

const data = reactive<PageData<ProjectTypeForm, ProjectTypeQuery>>({
  form: { ...initFormData },
  queryParams: {
    parentId: undefined,
    typeName: undefined,
    sortOrder: undefined,
    spareFlag: undefined,
    topFlag: undefined,
    params: {}
  },
  rules: {
    projectTypeId: [{ required: true, message: '项目类型ID不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询项目类型信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listProjectType(queryParams.value);
  const data = proxy?.handleTree<ProjectTypeVO>(res.data, 'projectTypeId', 'parentId');
  if (data) {
    projectTypeList.value = data;
    loading.value = false;
  }
};

/** 查询项目类型信息下拉树结构 */
const getTreeselect = async () => {
  const res = await listProjectType();
  projectTypeOptions.value = [];
  const data: ProjectTypeOption = { projectTypeId: 0, typeName: '顶级节点', children: [] };
  data.children = proxy?.handleTree<ProjectTypeOption>(res.data, 'projectTypeId', 'parentId');
  projectTypeOptions.value.push(data);
};

// 取消按钮
const cancel = () => {
  reset();
  dialog.visible = false;
};

// 表单重置
const reset = () => {
  form.value = { ...initFormData };
  projectTypeFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = (row?: ProjectTypeVO) => {
  reset();
  getTreeselect();
  if (row != null && row.projectTypeId) {
    form.value.parentId = row.projectTypeId;
  } else {
    form.value.parentId = 0;
  }
  dialog.visible = true;
  dialog.title = '添加项目类型信息';
};

/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  toggleExpandAll(projectTypeList.value, isExpandAll.value);
};

/** 展开/折叠操作 */
const toggleExpandAll = (data: ProjectTypeVO[], status: boolean) => {
  data.forEach((item) => {
    projectTypeTableRef.value?.toggleRowExpansion(item, status);
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status);
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row: ProjectTypeVO) => {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  const res = await getProjectType(row.projectTypeId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改项目类型信息';
};

/** 提交按钮 */
const submitForm = () => {
  projectTypeFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.projectTypeId) {
        await updateProjectType(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addProjectType(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row: ProjectTypeVO) => {
  await proxy?.$modal.confirm('是否确认删除项目类型信息编号为"' + row.projectTypeId + '"的数据项？');
  loading.value = true;
  await delProjectType(row.projectTypeId).finally(() => (loading.value = false));
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

onMounted(() => {
  getList();
});
</script>
