<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 label="创建" prop="createUser">
              <el-input v-model="queryParams.createUser" 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="['system:difyDatasetsProduct:add']">新增
              </el-button>
            </el-form-item>
<!--            <el-form-item>
              <el-button type="primary" plain icon="Plus" @click="handleAdd"
                         v-hasPermi="['system:difyDatasetsProduct:add']">新增
              </el-button>
              <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
                         v-hasPermi="['system:difyDatasetsProduct:edit']">修改
              </el-button>
              <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
                         v-hasPermi="['system:difyDatasetsProduct:remove']">删除
              </el-button>
              <el-button type="warning" plain icon="Download" @click="handleExport"
                         v-hasPermi="['system:difyDatasetsProduct:export']">导出
              </el-button>
            </el-form-item>-->
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <el-table v-loading="loading" :data="difyDatasetsProductList" @selection-change="handleSelectionChange">
<!--        <el-table-column type="selection" width="55" align="left"/>-->
        <el-table-column label="" align="left" prop="" width="10"/>
        <el-table-column label="产品ID" align="left" prop="id" v-if="true" width="180"/>
        <el-table-column label="产品名称" align="left" prop="name" width="120"/>
        <el-table-column label="产品简介" align="left" prop="note" width="350">
          <template #default="{ row }">
            <div @click="toggleExpand(row)" style="cursor: pointer">
              <div v-if="row.expanded">
                {{ row.note }}
              </div>
              <div v-else>
                {{ row.note.substring(0, 52) + (row.note.length > 52 ? '...' : '') }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="产品属性" align="center" width="100">
          <template #default="scope">
            <dict-tag :options="smsb_product_properties" :value="scope.row.property" />
          </template>
        </el-table-column>
        <el-table-column label="关键词" align="left" prop="keyword" width="150" :show-overflow-tooltip="true"/>
        <el-table-column label="产品价格" align="center" prop="price" width="100"/>

        <el-table-column label="排序" align="center" prop="sort" width="100"/>
        <el-table-column label="产品图片" align="center" width="100">
          <!--          &lt;!&ndash; 使用作用域插槽获取当前行数据 &ndash;&gt;-->
          <template #default="scope">
            <!--            &lt;!&ndash; 将 imgUrl 传递给自定义组件 &ndash;&gt;-->
            <image-preview :src="scope.row.imgUrl" style="width: 40px; height: 40px; cursor: pointer" />
          </template>
        </el-table-column>
        <el-table-column label="产品视频" align="left" prop="videoUrl" width="150" :show-overflow-tooltip="true"/>
        <el-table-column label="创建人" align="left" prop="createUser" width="120" :show-overflow-tooltip="true"/>
        <el-table-column label="备注" align="left" prop="remark" :show-overflow-tooltip="true"/>
        <el-table-column label="操作" align="left" class-name="small-padding fixed-width" width="100">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                         v-hasPermi="['system:difyDatasetsProduct:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                         v-hasPermi="['system:difyDatasetsProduct:remove']"></el-button>
            </el-tooltip>
          </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>

    <!-- 添加或修改Dify产品推荐对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="difyDatasetsProductFormRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-form-item label="产品名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入名称" style="width: 300px"/>
          </el-form-item>
          <el-form-item label="产品序号" prop="sort">
            <el-input-number v-model="form.sort" controls-position="right" placeholder="请输入序号" :min="1"
                             :max="100000" style="width: 180px" :maxlength="6"/>
          </el-form-item>
        </el-row>
        <el-form-item label="关键词" prop="keyword">
          <el-input v-model="form.keyword" placeholder="请输入关键词"/>
        </el-form-item>
        <el-form-item label="产品属性" prop="property">
          <el-select v-model="form.property" placeholder="请选择属性">
            <el-option v-for="dict in smsb_product_properties" :key="dict.value" :label="dict.label"
                       :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品价格" prop="price">
<!--          -->
          <el-input-number v-model="form.price" placeholder="请输入价格" controls-position="right" style="width: 300px"/>
<!--          <el-input v-model="form.price" placeholder="请输入价格"/>-->
        </el-form-item>
        <el-form-item label="产品图片" prop="imgUrl">
          <component-upload-image :limit=1 v-model="form.imgUrl"></component-upload-image>
        </el-form-item>
        <el-form-item label="产品视频" prop="videoUrl">
          <el-input v-model="form.videoUrl" placeholder="请输入视频地址"/>
        </el-form-item>
        <el-form-item label="产品简介" prop="note">
          <el-input v-model="form.note" type="textarea" :rows="5" placeholder="请输入内容" :maxlength="500"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :rows="3"/>
        </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="DifyDatasetsProduct" lang="ts">
import {
  listDifyDatasetsProduct,
  getDifyDatasetsProduct,
  delDifyDatasetsProduct,
  addDifyDatasetsProduct,
  updateDifyDatasetsProduct
} from '@/api/smsb/device/difyDatasetsProduct_index';
import {
  DifyDatasetsProductVO,
  DifyDatasetsProductQuery,
  DifyDatasetsProductForm
} from '@/api/smsb/device/difyDatasetsProduct_types';
import ComponentUploadImage from '@/components/ImageUpload/index.vue';
import ImageSlot from '@/components/ImagePreview/index.vue';

const {proxy} = getCurrentInstance() as ComponentInternalInstance;

const difyDatasetsProductList = ref<DifyDatasetsProductVO[]>([]);
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 difyDatasetsProductFormRef = ref<ElFormInstance>();

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

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

const initFormData: DifyDatasetsProductForm = {
  id: undefined,
  name: undefined,
  note: undefined,
  sort: undefined,
  imgUrl: undefined,
  createUser: undefined,
  keyword: undefined,
  property: undefined,
  price: undefined,
  videoUrl: undefined,
}
const data = reactive<PageData<DifyDatasetsProductForm, DifyDatasetsProductQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    note: undefined,
    sort: undefined,
    imgUrl: undefined,
    createUser: undefined,
    keyword: undefined,
    property: undefined,
    price: undefined,
    videoUrl: undefined,
    params: {}
  },
  rules: {
    id: [
      {required: true, message: "主键ID不能为空", trigger: "blur"}
    ],
    name: [
      {required: true, message: "名称不能为空", trigger: "blur"}
    ],
    note: [
      {required: true, message: "简介不能为空", trigger: "blur"}
    ],
    sort: [
      {required: true, message: "产品序号不能为空", trigger: "blur"}
    ],
    imgUrl: [
      {required: true, message: "产品图片不能为空", trigger: "blur"}
    ],
    createUser: [
      {required: false, message: "创建人不能为空", trigger: "blur"}
    ],
    keyword: [
      {required: true, message: "关键词不能为空", trigger: "blur"}
    ],
    property: [
      {required: true, message: "产品属性不能为空", trigger: "blur"}
    ],
    price: [
      {required: false, message: "产品价格不能为空", trigger: "blur"}
    ],
    videoUrl: [
      {required: false, message: "产品视频不能为空", trigger: "blur"}
    ],
  }
});

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

/** 查询Dify产品推荐列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDifyDatasetsProduct(queryParams.value);
  difyDatasetsProductList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

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

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

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: DifyDatasetsProductVO[]) => {
  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 handleUpdate = async (row?: DifyDatasetsProductVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getDifyDatasetsProduct(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改产品条目";
}

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

/** 删除按钮操作 */
const handleDelete = async (row?: DifyDatasetsProductVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除产品条目编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delDifyDatasetsProduct(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

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

const toggleExpand = (row) => {
  row.expanded = !row.expanded;
};

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