<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="catalogName">
              <el-input v-model="queryParams.catalogName" 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="['catalog:textbook: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="catalogTextbookTableRef" v-loading="loading" :data="catalogTextbookList" row-key="catalogId"
        :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column label="教材名称" align="center" prop="catalogName" />
        <el-table-column label="类型" align="center" prop="type">
          <template #default="scope">
            <el-tag v-if="scope.row.type === 1" type="success">暂定</el-tag>
            <el-tag v-if="scope.row.type === 2" type="success">学段</el-tag>
            <el-tag v-if="scope.row.type === 3" type="success">年级</el-tag>
            <el-tag v-if="scope.row.type === 4" type="success">学科</el-tag>
            <el-tag v-if="scope.row.type === 5" type="success">版本</el-tag>
            <el-tag v-if="scope.row.type === 6" type="success">教材</el-tag>
            <el-tag v-if="scope.row.type === 7" type="success">目录</el-tag>
          </template>
        </el-table-column>
        <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="['catalog:textbook:edit']" />
            </el-tooltip>
            <el-tooltip content="新增" placement="top">
              <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)"
                v-hasPermi="['catalog:textbook:add']" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['catalog:textbook: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="catalogTextbookFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="父目录id" prop="parentId">
          <el-tree-select v-model="form.parentId" :data="catalogTextbookOptions"
            :props="{ value: 'catalogId', label: 'catalogName', children: 'children' }" value-key="catalogId"
            placeholder="请选择父目录id" check-strictly />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="教材名称" prop="catalogName">
          <el-input v-model="form.catalogName" 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="CatalogTextbook" lang="ts">
import { listCatalogTextbook, getCatalogTextbook, delCatalogTextbook, addCatalogTextbook, updateCatalogTextbook } from "@/api/resource/catalogTextbook";
import { CatalogTextbookVO, CatalogTextbookQuery, CatalogTextbookForm } from '@/api/resource/catalogTextbook/types';

type CatalogTextbookOption = {
  catalogId: number;
  catalogName: string;
  children?: CatalogTextbookOption[];
}

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


const catalogTextbookList = ref<CatalogTextbookVO[]>([]);
const catalogTextbookOptions = ref<CatalogTextbookOption[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(true);
const isExpandAll = ref(true);
const loading = ref(false);

const queryFormRef = ref<ElFormInstance>();
const catalogTextbookFormRef = ref<ElFormInstance>();
const catalogTextbookTableRef = ref<ElTableInstance>()

const typeOptions = [
  {
    value: 2,
    label: '学段',
  },
  {
    value: 3,
    label: '年级',
  },
  {
    value: 4,
    label: '学科',
  },
  {
    value: 5,
    label: '版本',
  },
  {
    value: 6,
    label: '教材',
  },
  {
    value: 7,
    label: '目录',
  },
  {
    value: 1,
    label: '暂定',
  }
]

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


const initFormData: CatalogTextbookForm = {
  catalogId: undefined,
  parentId: undefined,
  ancestors: undefined,
  catalogName: undefined,
  orderNum: undefined,
  type: undefined,
}

const data = reactive<PageData<CatalogTextbookForm, CatalogTextbookQuery>>({
  form: { ...initFormData },
  queryParams: {
    parentId: undefined,
    ancestors: undefined,
    catalogName: undefined,
    orderNum: undefined,
    type: undefined,
    params: {
    }
  },
  rules: {
    parentId: [
      { required: true, message: "父目录id不能为空", trigger: "blur" }
    ],
    catalogName: [
      { required: true, message: "教材名称不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "类型不能为空", trigger: "change" }
    ],
  }
});

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

/** 查询目录-同步教材列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCatalogTextbook(queryParams.value);
  const data = proxy?.handleTree<CatalogTextbookVO>(res.data, "catalogId", "parentId");
  if (data) {
    catalogTextbookList.value = data;
    loading.value = false;
  }
}

/** 查询目录-同步教材下拉树结构 */
const getTreeselect = async () => {
  const res = await listCatalogTextbook();
  catalogTextbookOptions.value = [];
  const data: CatalogTextbookOption = { catalogId: 0, catalogName: '顶级节点', children: [] };
  data.children = proxy?.handleTree<CatalogTextbookOption>(res.data, "catalogId", "parentId");
  catalogTextbookOptions.value.push(data);
}

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

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

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

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

/** 新增按钮操作 */
const handleAdd = (row?: CatalogTextbookVO) => {
  reset();
  getTreeselect();
  if (row != null && row.catalogId) {
    form.value.parentId = row.catalogId;
  } else {
    form.value.parentId = 0;
  }
  dialog.visible = true;
  dialog.title = "添加目录-同步教材";
}

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

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

/** 修改按钮操作 */
const handleUpdate = async (row: CatalogTextbookVO) => {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  const res = await getCatalogTextbook(row.catalogId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改目录-同步教材";
}

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

/** 删除按钮操作 */
const handleDelete = async (row: CatalogTextbookVO) => {
  await proxy?.$modal.confirm('是否确认删除目录-同步教材编号为"' + row.catalogId + '"的数据项？');
  loading.value = true;
  await delCatalogTextbook(row.catalogId).finally(() => loading.value = false);
  await getList();
  proxy?.$modal.msgSuccess("删除成功");
}

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