<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" :style="{ marginTop: '10px', height: '60px' }">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="文件名称" prop="name">
              <el-input v-model="queryParams.name" 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-button type="primary" plain icon="Plus" @click="handleAdd"
                         v-hasPermi="['device:datasetsFile:add']">
                新增
              </el-button>
              <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
                         v-hasPermi="['device:datasetsFile:remove']">删除
              </el-button>
              <el-button type="warning" plain icon="Refresh" @click="handleSync()"
                         v-hasPermi="['device:datasetsFile:add']">同步
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <div class="table-content">
        <el-table v-loading="loading" :data="difyDatasetsFileList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="ID" align="left" prop="id" v-if="true" width="175"/>
          <el-table-column label="知识库" align="left" prop="datasetsName" width="180" :show-overflow-tooltip="true"/>
          <el-table-column label="文件ID" align="center" prop="difyId" width="200" :show-overflow-tooltip="true"/>
          <el-table-column label="文件名称" align="left" prop="name" :show-overflow-tooltip="true"/>
          <el-table-column label="索引状态" align="center" prop="indexingStatus" width="90"/>
          <el-table-column label="排序" align="center" prop="position" width="60"/>
          <el-table-column label="Tokens" align="center" prop="tokens"  width="80"/>
          <el-table-column label="字符数" align="center" prop="wordCount"  width="80"/>
          <el-table-column label="创建时间" align="left" prop="createTime" width="160"/>
          <el-table-column label="更新时间" align="left" prop="updateTime" width="160" />
          <el-table-column label="文件地址" align="left" prop="fileUrl" width="180" :show-overflow-tooltip="true"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
            <template #default="scope">
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                           v-hasPermi="['device:datasetsFile:remove']"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                  v-model:limit="queryParams.pageSize" @pagination="getList"/>
    </el-card>
    <!-- 添加或修改Dify知识库文件对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="700px" append-to-body>
      <el-form ref="difyDatasetsFileFormRef" :model="form" :rules="rules" label-width="70px">
        <el-form-item label="文件上传" prop="ossId">
          <file-upload v-model="form.ossId"/>
        </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="DifyDatasetsFile" lang="ts">
import {
  addDifyDatasetsFile,
  delDifyDatasetsFile,
  getDifyDatasetsFile,
  listDifyDatasetsFile,
  updateDifyDatasetsFile,
  syncDatasetsFiles
} from '@/api/smsb/device/datasets_file';
import {DifyDatasetsFileForm, DifyDatasetsFileQuery, DifyDatasetsFileVO} from '@/api/smsb/device/datasets_file_type';

const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const route = useRoute();
const difyDatasetsFileList = ref<DifyDatasetsFileVO[]>([]);
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 datasetsId = ref<string>();
const queryFormRef = ref<ElFormInstance>();
const difyDatasetsFileFormRef = ref<ElFormInstance>();

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

const initFormData: DifyDatasetsFileForm = {
  fileUrl: undefined,
  ossId: undefined,
  datasetsId: undefined,
}
const data = reactive<PageData<DifyDatasetsFileForm, DifyDatasetsFileQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    params: {}
  },
  rules: {}
});

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

/** 查询Dify知识库文件列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.datasetDifyId = datasetsId.value;
  const res = await listDifyDatasetsFile(queryParams.value);
  difyDatasetsFileList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

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

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

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "文件上传";
}

const handleSync = async () => {
  await proxy?.$modal.confirm('是否确认同步知识库文件列表数据？').finally(() => loading.value = false);
  loading.value = true;
  await syncDatasetsFiles(datasetsId.value);
  proxy?.$modal.msgSuccess("同步成功");
  await getList();
  loading.value = false;
}

/** 修改按钮操作 */
const handleUpdate = async (row?: DifyDatasetsFileVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getDifyDatasetsFile(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改Dify知识库文件";
}

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

/** 删除按钮操作 */
const handleDelete = async (row?: DifyDatasetsFileVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除已选择的数据项？').finally(() => loading.value = false);
  await delDifyDatasetsFile(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('device/difyDatasetsFile/export', {
    ...queryParams.value
  }, `difyDatasetsFile_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  datasetsId.value = route.query && (route.query.datasetsId as string)
  getList();
});
</script>
