<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="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" icon="Plus" @click="handleAdd" v-hasPermi="['product:pool:add']">新增</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">


      <el-table v-loading="loading" border :data="poolList">
        
        <el-table-column label="分类商品池名称" align="center" prop="name" />
        <el-table-column label="产品池类型" align="center" prop="type">
          <template #default="scope">
            {{ getPoolTypeLabel(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column label="商品数量" align="center" prop="productCount" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
        <el-table-column label="待申请" align="center" prop="waitApplyCount" />
        <el-table-column label="待审核" align="center" prop="waitReviewCount" />
        <el-table-column label="已通过" align="center" prop="approvedCount" />
        <el-table-column label="已驳回" align="center" prop="rejectedCount" />
        <el-table-column label="操作" align="center" width="260">
          <template #default="scope">
            <el-link type="primary" @click="handleModifyPool(scope.row)" v-hasPermi="['product:pool:edit']">修改分类商品池售卖</el-link>
            <el-divider direction="vertical" />
            <el-link type="primary" @click="handlePoolManage(scope.row)" v-hasPermi="['product:pool:edit']">商品池管理</el-link>
          </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>
    <!-- 添加或修改产品池对话框 -->
    <el-dialog title="项目/平台商品信息" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="poolFormRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="项目/平台名称:" prop="name">
          <el-input v-model="form.name" placeholder="办公设备精选池" />
        </el-form-item>
        <el-form-item label="产品池类型:" prop="type">
          <el-select v-model="form.type" placeholder="请选择产品池类型" style="width: 100%">
            <el-option
              v-for="item in poolTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态:" prop="isShow">
          <el-switch 
            v-model="form.isShow" 
            active-value="1" 
            inactive-value="0"
            active-text="启用"
          />
        </el-form-item>
        <el-form-item label="描述:" prop="remark">
          <el-input 
            v-model="form.remark" 
            type="textarea" 
            placeholder="请输入内容" 
            maxlength="200"
            show-word-limit
            :rows="4"
          />
        </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="Pool" lang="ts">
import { listPool, getPool, delPool, addPool, updatePool } from '@/api/product/pool';
import { PoolVO, PoolQuery, PoolForm } from '@/api/product/pool/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

/** 产品池类型选项 */
const poolTypeOptions = [
  { label: '普通产品池', value: 0 },
  { label: '精选产品池', value: 1 },
  { label: '协议产品池', value: 2 },
  { label: '项目产品池', value: 3 },
  { label: '分类产品池', value: 4 }
];

/** 获取产品池类型标签 */
const getPoolTypeLabel = (type: number) => {
  const option = poolTypeOptions.find(item => item.value === type);
  return option ? option.label : '未知类型';
};

const poolList = ref<PoolVO[]>([]);
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 poolFormRef = ref<ElFormInstance>();

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

const initFormData: PoolForm = {
  id: undefined,
  poolNo: undefined,
  itemId: undefined,
  categoryId: undefined,
  type: 0,
  name: undefined,
  isShow: '1',
  productReviewStatus: undefined,
  reviewReason: undefined,
  remark: undefined,
}
const data = reactive<PageData<PoolForm, PoolQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    poolNo: undefined,
    itemId: undefined,
    categoryId: undefined,
    type: undefined,
    name: undefined,
    isShow: undefined,
    productReviewStatus: undefined,
    reviewReason: undefined,
    platformCode: undefined,
    params: {
    }
  },
  rules: {
    name: [
      { required: true, message: "项目/平台名称不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "产品池类型不能为空", trigger: "change" }
    ],
    isShow: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
  }
});

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

/** 查询产品池列表 */
const getList = async () => {
  loading.value = true;
  const res = await listPool(queryParams.value);
  poolList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

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

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

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

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

/** 状态切换 */
const handleStatusChange = async (row: PoolVO) => {
  const text = row.isShow === '1' ? '启用' : '停用';
  try {
    await proxy?.$modal.confirm('确认要"' + text + '""' + row.name + '"吗？');
    await updatePool(row);
    proxy?.$modal.msgSuccess(text + '成功');
    await getList();
  } catch {
    row.isShow = row.isShow === '1' ? '0' : '1';
  }
}

/** 修改分类商品池售卖 */
const handleModifyPool = async (row: PoolVO) => {
  reset();
  const res = await getPool(row.id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
}

/** 商品池管理 */
const handlePoolManage = (row: PoolVO) => {
  proxy?.$router.push({
    path: '/product/poolLink',
    query: { poolId: row.id, poolName: row.name }
  });
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
}

/** 修改按钮操作 */
const handleUpdate = async (row?: PoolVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getPool(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
}

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

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

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

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