<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:datasets:add']">
                新增
              </el-button>
              <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
                         v-hasPermi="['device:datasets:remove']">删除
              </el-button>
<!--              <el-button type="warning" plain icon="Refresh" @click="handleSync()"
                         v-hasPermi="['device:datasets: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="difyDatasetsList" @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="产品库ID" align="left" prop="difyId" width="180" :show-overflow-tooltip = "true"/>
          <el-table-column label="产品库" align="left" prop="name" width="200" :show-overflow-tooltip="true"/>
          <el-table-column label="描述" align="left" prop="description" :show-overflow-tooltip="true"/>
          <el-table-column label="索引模式" align="center" prop="indexingTechnique" width="80">
            <template #default="scope">
              <span>{{ scope.row.indexingTechnique === 'high_quality' ? '高质量' : '经济' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="权限" align="center" prop="permission" width="80"/>
          <el-table-column label="提供类型" align="center" prop="provider" width="80">
            <template #default="scope">
              <span>{{ scope.row.provider === 'vendor' ? '上传文件' : ' 外部产品库' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="数据源" align="center" prop="dataSourceType" width="120"/>
          <el-table-column label="文字数量" align="center" prop="wordCount" width="80"/>
          <el-table-column label="文档数量" align="center" prop="documentCount" width="80"/>
          <el-table-column label="APP数量" align="center" prop="appCount" 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="center" class-name="small-padding fixed-width" width="150">
            <template #default="scope">
              <!--              <el-tooltip content="文件列表" placement="top">
                              <el-button link type="primary" icon="Document" @click="handleToFileList(scope.row)"
                                         v-hasPermi="['device:datasetsFile:list']"></el-button>
                            </el-tooltip>-->
              <el-tooltip content="下发" placement="top">
                <el-button link type="primary" icon="Position" @click="handlePush(scope.row)"
                           v-hasPermi="['device:datasets:edit']"></el-button>
              </el-tooltip>
              <el-tooltip content="产品条目" placement="top">
                <el-button link type="primary" icon="View" @click="handleEntryList(scope.row)"
                           v-hasPermi="['device:datasets:query']"></el-button>
              </el-tooltip>
              <el-tooltip content="刷新" placement="top">
                <el-button link type="primary" icon="Refresh" @click="handleSync()"
                           v-hasPermi="['device:datasets:add']">
                </el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                           v-hasPermi="['device:datasets: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>
    <!-- 添加或修改产品库管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="700px" append-to-body>
      <el-form ref="difyDatasetsFormRef" :model="form" :rules="rules" label-width="50px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入产品库名称"/>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" :rows="5" 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>

    <!-- 产品条目下发 -->
    <el-dialog :title="pushDialog.title" v-model="pushDialog.visible" width="900px" append-to-body>
      <div>
        <el-transfer
          v-model="selectedEntry"
          filterable
          :filter-method="filterEntry"
          filter-placeholder="请输入产品名称"
          :data="entryList"
          :props="{ key: 'key', label: 'label' }"
          :titles="['可选条目', '已选条目']"
          :button-texts="['移除', '添加']"
        />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitEntry">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 产品条目列表 -->
    <el-dialog :title="viewDialog.title" v-model="viewDialog.visible" width="1200px" append-to-body>
      <div class="table-content">
        <el-table v-loading="entryLoading" :data="productList">
          <el-table-column label="产品名称" align="left" prop="name" width="250" :show-overflow-tooltip="true"/>
          <el-table-column label="产品简介" align="left" prop="note" :show-overflow-tooltip="true"/>
          <el-table-column label="产品图片" align="left" width="100">
            <template #default="scope">
              <image-preview :src="scope.row.imgUrl" style="width: 40px; height: 40px; cursor: pointer"/>
            </template>
          </el-table-column>
          <el-table-column label="创建人" align="left" prop="createUser" width="100" :show-overflow-tooltip="true"/>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="DifyDatasets" lang="ts">
import {
  addDifyDatasets,
  delDifyDatasets,
  getDifyDatasets,
  listDifyDatasets,
  pushProductEntry,
  syncDifyDatasets,
  updateDifyDatasets
} from '@/api/smsb/device/datasets';
import {DifyDatasetsForm, DifyDatasetsQuery, DifyDatasetsVO} from '@/api/smsb/device/datasets_type';
import {listAllProduct, listProductByDatasetsId} from "@/api/smsb/device/difyDatasetsProduct_index";
import {DifyDatasetsProductVO} from "@/api/smsb/device/difyDatasetsProduct_types";

const {proxy} = getCurrentInstance() as ComponentInternalInstance;

const difyDatasetsList = ref<DifyDatasetsVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const entryLoading = 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 selectedEntry = ref([]);
const entryList = ref([]);
const productList = ref<DifyDatasetsProductVO>([]);
const queryFormRef = ref<ElFormInstance>();
const difyDatasetsFormRef = ref<ElFormInstance>();
const datasetsId = ref<number | string>();

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

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

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

const initFormData: DifyDatasetsForm = {
  id: undefined,
  name: undefined,
  description: undefined,
  indexingTechnique: undefined,
  permission: undefined,
  provider: undefined,
  dataSourceType: undefined,
  wordCount: undefined,
  documentCount: undefined,
  appCount: undefined,
  difyId: undefined,
  tag: 2,
}
const data = reactive<PageData<DifyDatasetsForm, DifyDatasetsQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    tag: 2,
    params: {}
  },
  rules: {
    name: [{ required: true, message: '产品库名称不能为空', trigger: 'blur' }],
  }
});

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

/** 查询产品库管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDifyDatasets(queryParams.value);
  difyDatasetsList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}
const handleEntryList = async (row?: DifyDatasetsVO) => {
  entryLoading.value = true;
  viewDialog.visible = true;
  viewDialog.title = '产品条目';
  const datasetsId = row.id;
  const res = await listProductByDatasetsId(datasetsId);
  productList.value = res.data;
  entryLoading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
  pushDialog.visible = false;
  viewDialog.visible = false;
  selectedEntry.value = [];
}

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

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: DifyDatasetsVO[]) => {
  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 syncDifyDatasets();
  proxy?.$modal.msgSuccess("同步成功");
  await getList();
  loading.value = false;
}


/** 修改按钮操作 */
const handleUpdate = async (row?: DifyDatasetsVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getDifyDatasets(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改产品库";
}
const handlePush = async (row?: DifyDatasetsVO) => {
  datasetsId.value = row.id;
  console.log("datasetsId1 = " + datasetsId.value);

  pushDialog.visible = true;
  pushDialog.title = "产品条目下发";
  const res = await listAllProduct();
  const rspList = res.data || [];
  // 清空现有数据
  entryList.value = [];
  selectedEntry.value = [];
  // 使用map更简洁地转换数据格式
  entryList.value = rspList.map(item => ({
    key: item.id,
    label: item.name,
    disabled: false // 如果需要禁用某些项，可以在这里设置
  }));
}
const filterEntry = (query, item) => {
  if (!query) return true; // 没有查询条件时返回所有项
  return item.label.toLowerCase().includes(query.toLowerCase());
}
const submitEntry = async () => {
  buttonLoading.value = true;
  console.log("datasetsId = " + datasetsId.value);
  console.log("selectedEntry = " + selectedEntry.value)
  if (selectedEntry.value.length < 1) {
    proxy?.$modal.msgError("请至少选择一个产品！");
  }
  const pushProductParam = {
    id: datasetsId.value,
    entryIds: selectedEntry.value
  }
  await pushProductEntry(pushProductParam).finally(() => buttonLoading.value = false);
  proxy?.$modal.msgSuccess("操作成功");
  pushDialog.visible = false;
}
/** 提交按钮 */
const submitForm = () => {
  difyDatasetsFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateDifyDatasets(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addDifyDatasets(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

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

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

onMounted(() => {
  getList();
});
</script>
<style lang="scss" scoped>
/* 自定义穿梭框样式 */
:deep(.el-transfer-panel) {
  width: 300px !important;
}

</style>
