<template>
  <div class="h-full flex flex-col p-2">
    <pageheader title="报修项目"></pageheader>
    <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" :inline="true" label-width="100px" :model="queryParams">
            <el-form-item label="维修项目名" prop="projectName">
              <el-input v-model="queryParams.projectName" placeholder="请输入维修项目名" clearable @keyup.enter="handleQuery" />
            </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 class="flex-1" shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-button style="width: 100px" type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['repairProject:repairProject:add']"
            >新增维修类</el-button
          >
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete()"
            v-hasPermi="['repairProject:repairProject:remove']"
            >删除</el-button
          >
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table
        :tree-props="{ children: 'children' }"
        v-loading="loading"
        border
        row-key="id"
        :data="repairProjectList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="expand">
          <template #default="props">
            <div
              v-if="props.row.children.length >= 0"
              :class="{
                'm-4': props.row.children.length >= 0
              }"
            >
              <el-table :data="props.row.children">
                <el-table-column label="维修项目名" align="center" prop="projectName" />
                <el-table-column label="维修类型" align="center" prop="projectType">
                  <template #default="scope">
                    <dict-tag :options="com_repair_project_types" :value="scope.row.projectType"></dict-tag>
                  </template>
                </el-table-column>
                <el-table-column label="状态" align="center" prop="status">
                  <template #default="scope">
                    <dict-tag :options="com_repair_project_status" :value="scope.row.status"></dict-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
                  <template #default="scope">
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
                    <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="维修类名" align="center" prop="projectName" />
        <el-table-column label="项目类型" align="center" prop="projectType">
          <template #default="scope">
            <dict-tag :options="com_repair_project_types" :value="scope.row.projectType || ''"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="com_repair_project_status" :value="scope.row.status || ''"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="350" align="center" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['repairProject:repairProject:edit']">修改</el-button>
            <el-button link type="primary" @click="handleDelete(scope.row)" v-hasPermi="['repairProject:repairProject:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" /> -->
    </el-card>
    <!-- 添加或修改报修维修项目管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="repairProjectFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="维修项目名" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入维修项目名" />
        </el-form-item>
        <el-form-item label="父级项目id" prop="parentId">
          <el-input v-model="form.parentId" placeholder="请输入父级项目id" />
        </el-form-item>
        <el-form-item label="项目层级 0，1" prop="projectLevel">
          <el-input v-model="form.projectLevel" placeholder="请输入项目层级 0，1" />
        </el-form-item>
        <el-form-item label="排序 " prop="sortOrder">
          <el-input v-model="form.sortOrder" placeholder="请输入排序 " />
        </el-form-item>
        <el-form-item label="创建时间" prop="cretaeTime">
          <el-date-picker clearable v-model="form.cretaeTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="创建者" prop="createBy">
          <el-input v-model="form.createBy" placeholder="请输入创建者" />
        </el-form-item>
        <el-form-item label="更新时间" prop="updateTime">
          <el-date-picker clearable v-model="form.updateTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择更新时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="更新者" prop="updateBy">
          <el-input v-model="form.updateBy" 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="RepairProject" lang="ts">
import {
  listRepairProject,
  getRepairProject,
  delRepairProject,
  addRepairProject,
  updateRepairProject,
  gettreelistRepairProject
} from '@/api/system/RepairProject/index';
import { RepairProjectVO, RepairProjectQuery, RepairProjectForm } from '@/api/system/RepairProject/type';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { com_repair_project_status } = toRefs<any>(proxy?.useDict('com_repair_project_status'));
const { com_repair_project_types } = toRefs<any>(proxy?.useDict('com_repair_project_types'));

const router = useRouter();
const repairProjectList = ref<RepairProjectVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const repairProjectFormRef = ref<ElFormInstance>();

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

const initFormData: RepairProjectForm = {
  id: undefined,
  projectName: undefined,
  parentId: undefined,
  projectType: undefined,
  projectLevel: undefined,
  sortOrder: undefined,
  status: undefined,
  cretaeTime: undefined,
  createBy: undefined,
  updateTime: undefined,
  updateBy: undefined
};
const data = reactive<PageData<RepairProjectForm, RepairProjectQuery>>({
  form: { ...initFormData },
  queryParams: {
    projectName: undefined,
    parentId: undefined,
    projectType: undefined,
    projectLevel: undefined,
    sortOrder: undefined,
    status: undefined
  },
  rules: {}
});

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

/** 查询报修维修项目管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listRepairProject(queryParams.value);
  let arr = [];
  arr = res.rows.filter((item) => {
    item.children = [];
    if (item.projectLevel === 0) {
      return {
        ...item
      };
    }
  });
  res.rows.map((item) => {
    if (item.projectLevel === 1) {
      const index = arr.findIndex((ite) => ite.id === item.parentId);
      if (index !== -1) {
        arr[index].children.push(item);
      }
    }
  });
  repairProjectList.value = arr;
  total.value = res.total;
  loading.value = false;
};

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

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

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: RepairProjectVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  router.push({
    path: '/system/addRepairProjectList'
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row?: RepairProjectVO) => {
  router.push({
    path: '/system/addRepairProjectList',
    query: {
      id: row.id
    }
  });
};

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

/** 删除按钮操作 */
const handleDelete = async (row?: RepairProjectVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('该信息删除后无法恢复，确定要删除吗？').finally(() => (loading.value = false));
  await delRepairProject(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

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

<style lang="scss" scoped>
.el-table {
  height: calc(100% - 80px);
}
</style>
