<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">
<!--            <el-form-item label="检测项类别主键" prop="categoryId">-->
<!--              <el-input v-model="queryParams.categoryId" placeholder="请输入检测项类别主键" clearable @keyup.enter="handleQuery" />-->
<!--            </el-form-item>-->
<!--            <el-form-item label="父级ID" prop="parentId">-->
<!--              <el-input v-model="queryParams.parentId" placeholder="请输入父级ID" clearable @keyup.enter="handleQuery" />-->
<!--            </el-form-item>-->
<!--            <el-form-item label="祖级列表" prop="ancestors">-->
<!--              <el-input v-model="queryParams.ancestors" placeholder="请输入祖级列表" clearable @keyup.enter="handleQuery" />-->
<!--            </el-form-item>-->
            <el-form-item label="检测项类别编码" prop="categoryCode" label-width="120px">
              <el-input v-model="queryParams.categoryCode" placeholder="请输入检测项类别编码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="检测项类别名称" prop="categoryName" label-width="120px">
              <el-input v-model="queryParams.categoryName" placeholder="请输入检测项类别名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="检测类型" prop="typeId" label-width="120px">
<!--              <el-input v-model="queryParams.typeId" placeholder="请输入检测单类型" clearable @keyup.enter="handleQuery" />-->
              <el-select v-model="queryParams.typeId" placeholder="请选择检测类型">
                <el-option v-for="item in qcInspectionTypeList" :key="item.typeId" :label="item.typeName" :value="item.typeId" />
              </el-select>
            </el-form-item>
<!--            <el-form-item label="描述" prop="description">-->
<!--              <el-input v-model="queryParams.description" 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 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="['qms:qcInspectionItemCategory: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="qcInspectionItemCategoryTableRef"
        v-loading="loading"
        :data="qcInspectionItemCategoryList"
        row-key="categoryId"
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
<!--        <el-table-column label="检测项类别主键" align="center" prop="categoryId" />-->
<!--        <el-table-column label="父级ID" align="center" prop="parentId" />-->
<!--        <el-table-column label="祖级列表" align="center" prop="ancestors" />-->
        <el-table-column label="检测项类别编码" align="center" prop="categoryCode" />
        <el-table-column label="检测项类别名称" align="center" prop="categoryName" />
        <el-table-column label="检测类型" align="center" prop="typeName" />
        <el-table-column label="描述" align="center" prop="description" />
        <el-table-column label="操作" align="center" 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="['qms:qcInspectionItemCategory:edit']" />
            </el-tooltip>
            <el-tooltip content="新增" placement="top">
              <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['qms:qcInspectionItemCategory:add']" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['qms:qcInspectionItemCategory: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="qcInspectionItemCategoryFormRef" :model="form" :rules="rules" label-width="120px">
<!--        <el-form-item label="检测项类别主键" prop="categoryId">-->
<!--          <el-input v-model="form.categoryId" placeholder="请输入检测项类别主键" />-->
<!--        </el-form-item>-->
        <el-form-item label="父级" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="qcInspectionItemCategoryOptions"
            :props="{ value: 'categoryId', label: 'categoryName', children: 'children' }"
            value-key="categoryId"
            placeholder="请选择父级"
            check-strictly
          />
        </el-form-item>
<!--        <el-form-item label="祖级列表" prop="ancestors">-->
<!--          <el-input v-model="form.ancestors" placeholder="请输入祖级列表" />-->
<!--        </el-form-item>-->
        <el-form-item label="检测项类别编码" prop="categoryCode">
          <el-input v-model="form.categoryCode" placeholder="请输入检测项类别编码" />
        </el-form-item>
        <el-form-item label="检测项类别名称" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入检测项类别名称" />
        </el-form-item>
        <el-form-item label="检测类型" prop="typeId">
          <!-- <el-input v-model="form.typeId" placeholder="请输入检测单类型" /> -->
          <el-select v-model="form.typeId" placeholder="请选择检测类型">
            <el-option v-for="item in qcInspectionTypeList" :key="item.typeId" :label="item.typeName" :value="item.typeId" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" 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="QcInspectionItemCategory" lang="ts">
import { listQcInspectionItemCategory, getQcInspectionItemCategory, delQcInspectionItemCategory, addQcInspectionItemCategory, updateQcInspectionItemCategory } from '@/api/qms/qcInspectionItemCategory';
import { QcInspectionItemCategoryVO, QcInspectionItemCategoryQuery, QcInspectionItemCategoryForm } from '@/api/qms/qcInspectionItemCategory/types';
import {getQcInspectionTypeList} from "@/api/qms/qcInspectionType";
import { QcInspectionTypeVO } from '@/api/qms/qcInspectionType/types';
import type { TreeInstance } from 'element-plus';
import { watch } from "vue";

type QcInspectionItemCategoryOption = {
  categoryId: number;
  categoryName: string;
  children?: QcInspectionItemCategoryOption[];
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;;


const qcInspectionItemCategoryList = ref<QcInspectionItemCategoryVO[]>([]);
const qcInspectionItemCategoryOptions = ref<QcInspectionItemCategoryOption[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(true);
const isExpandAll = ref(true);
const loading = ref(false);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const qcInspectionItemCategoryFormRef = ref<ElFormInstance>();
// const qcInspectionItemCategoryTableRef = ref<ElTableInstance>();
const inspectionTypeTreeRef = ref<TreeInstance>();
const inspectionTypeName = ref('');

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


const initFormData: QcInspectionItemCategoryForm = {
    categoryId: undefined,
    parentId: undefined,
    ancestors: undefined,
    categoryCode: undefined,
    categoryName: undefined,
    typeId: undefined,
    description: undefined,
}

const data = reactive<PageData<QcInspectionItemCategoryForm, QcInspectionItemCategoryQuery>>({
  form: {...initFormData},
  queryParams: {
    categoryId: undefined,
    parentId: undefined,
    ancestors: undefined,
    categoryCode: undefined,
    categoryName: undefined,
    typeId: undefined,
    description: undefined,
    params: {
    }
  },
  rules: {
    // categoryId: [
    //   { required: true, message: "检测项类别主键不能为空", trigger: "blur" }
    // ],
    parentId: [
      { required: true, message: "父级不能为空", trigger: "blur" }
    ],
  }
});

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

/** 查询检测项类别列表 */
const getList = async () => {
  loading.value = true;
  const res = await listQcInspectionItemCategory(queryParams.value);
  const data = proxy?.handleTree<QcInspectionItemCategoryVO>(res.data, "categoryId", "parentId");
  if (data) {
    qcInspectionItemCategoryList.value = data;
    loading.value = false;
  }
}

/** 查询检测项类别下拉树结构 */
const getTreeselect = async () => {
  const res = await listQcInspectionItemCategory();
  qcInspectionItemCategoryOptions.value = [];
  const data: QcInspectionItemCategoryOption = { categoryId: 0, categoryName: '顶级节点', children: [] };
  data.children = proxy?.handleTree<QcInspectionItemCategoryOption>(res.data, "categoryId", "parentId");
  qcInspectionItemCategoryOptions.value.push(data);
}

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

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

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

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

/** 新增按钮操作 */
const handleAdd = (row?: QcInspectionItemCategoryVO) => {
  reset();
  getTreeselect();
  if (row != null && row.categoryId) {
    form.value.parentId = row.categoryId;
  } else {
    form.value.parentId = 0;
  }
  dialog.visible = true;
  dialog.title = "添加检测项类别";
}

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

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

/** 修改按钮操作 */
const handleUpdate = async (row: QcInspectionItemCategoryVO) => {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  const res = await getQcInspectionItemCategory(row.categoryId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改检测项类别";
}

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

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

//获取检测类型列表（不分页，获取全部）
let qcInspectionTypeList = ref([]);
const getInspectionTypeList = async () => {
  const res = await getQcInspectionTypeList(null);
  qcInspectionTypeList.value = proxy?.handleTree(res.data, "typeId", "parentId") || [];
}

/** 节点筛选 */
const filterNode = (value: string, data: QcInspectionTypeVO) => {
  if (!value) return true;
  return data.typeName.includes(value);
};

/** 节点单击事件 */
const handleNodeClick = (data: QcInspectionTypeVO) => {
  queryParams.value.typeId = data.typeId;
  handleQuery();
};

watch(inspectionTypeName, val => {
  inspectionTypeTreeRef.value?.filter(val);
});


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