<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 label="申请时间" prop="applyTime">
              <el-date-picker
                v-model="applyTimeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                @change="handleApplyTimeChange"
              />
            </el-form-item>
            <el-form-item label="审核时间" prop="reviewTime">
              <el-date-picker
                v-model="reviewTimeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                @change="handleReviewTimeChange"
              />
            </el-form-item>
            <el-form-item label="创建人" prop="createBy">
              <el-input v-model="queryParams.createBy" placeholder="请输入创建人" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="审核人" prop="reviewBy">
              <el-input v-model="queryParams.reviewBy" 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">
      <template #header>
        <div class="card-header">
          <span>产品池信息列表</span>
        </div>
      </template>

      <el-table v-loading="loading" border :data="poolList">
        <el-table-column label="产品池名称" align="center" prop="name" min-width="200" />
        <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="createBy" />
        <el-table-column label="审核人" align="center" prop="reviewBy" /> -->
        <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="300" fixed="right">
          <template #default="scope">
            <!-- 待审核：查看、去审核 -->
            <template v-if="queryParams.productReviewStatus === '1'">
              <el-link type="primary" @click="handleView(scope.row)">查看</el-link>
              <el-divider direction="vertical" />
              <el-link type="primary" @click="handleReview(scope.row)">去审核</el-link>
            </template>
            <!-- 已驳回：查看 -->
            <template v-else-if="queryParams.productReviewStatus === '3'">
              <el-link type="primary" @click="handleView(scope.row)">查看</el-link>
            </template>
            <!-- 已通过：查看 -->
            <template v-else-if="queryParams.productReviewStatus === '2'">
              <el-link type="primary" @click="handleView(scope.row)">查看</el-link>
            </template>
            <!-- 待申请：查看、申请入池单、修改入池 -->
            <template v-else-if="queryParams.productReviewStatus === '0'">
              <el-link type="primary" @click="handleView(scope.row)">查看</el-link>
              <el-divider direction="vertical" />
              <el-link type="primary" @click="handleApply(scope.row)">申请入池单</el-link>
              <el-divider direction="vertical" />
              <el-link type="primary" @click="handleModify(scope.row)">修改入池</el-link>
            </template>
          </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="viewDialog.visible" width="600px" append-to-body>
      <el-form ref="viewFormRef" :model="viewForm" label-width="120px">
        <el-form-item label="产品池编号:">
          <span>{{ viewForm.poolNo }}</span>
        </el-form-item>
        <el-form-item label="产品池名称:">
          <span>{{ viewForm.name }}</span>
        </el-form-item>
        <el-form-item label="审核状态:">
          <dict-tag :options="product_review_status" :value="viewForm.productReviewStatus" />
        </el-form-item>
        <el-form-item label="创建人:">
          <span>{{ viewForm.createBy }}</span>
        </el-form-item>
        <el-form-item label="审核人:">
          <span>{{ viewForm.reviewBy }}</span>
        </el-form-item>
        <el-form-item label="审核原因:" v-if="viewForm.reviewReason">
          <span>{{ viewForm.reviewReason }}</span>
        </el-form-item>
        <el-form-item label="备注:" v-if="viewForm.remark">
          <span>{{ viewForm.remark }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewDialog.visible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PoolReview" lang="ts">
import { listPool, getPool, updatePool } from '@/api/product/pool';
import { PoolVO, PoolQuery, PoolReviewForm } from '@/api/product/pool/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 字典数据
const { product_review_status } = toRefs<any>(proxy?.useDict('product_review_status'));

/** 产品池类型选项 */
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 route = useRoute();

const poolList = ref<PoolVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);

// 时间范围
const applyTimeRange = ref<[string, string]>();
const reviewTimeRange = ref<[string, string]>();

const queryFormRef = ref<ElFormInstance>();
const viewFormRef = ref<ElFormInstance>();

// 查看对话框
const viewDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});


const initFormData: PoolQuery = {
  pageNum: 1,
  pageSize: 10,
  itemId: undefined,
  categoryId: undefined,
  type: undefined,
  name: undefined,
  productReviewStatus: undefined,
  createBy: undefined,
  reviewBy: undefined,
  params: {}
}

const data = reactive<PageData<PoolReviewForm, PoolQuery>>({
  form: {},
  queryParams: {...initFormData},
  rules: {}
});

const { queryParams } = toRefs(data);

// 查看表单
const viewForm = ref<PoolVO>({
  id: '',
  poolNo: '',
  itemId: '',
  categoryId: '',
  type: 0,
  name: '',
  isShow: '',
  productReviewStatus: '',
  reviewReason: '',
  remark: ''
});

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

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

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

/** 申请时间范围变化 */
const handleApplyTimeChange = (value: [string, string]) => {
  if (value) {
    queryParams.value.params = queryParams.value.params || {};
    queryParams.value.params.beginApplyTime = value[0];
    queryParams.value.params.endApplyTime = value[1];
  } else {
    if (queryParams.value.params) {
      delete queryParams.value.params.beginApplyTime;
      delete queryParams.value.params.endApplyTime;
    }
  }
}

/** 审核时间范围变化 */
const handleReviewTimeChange = (value: [string, string]) => {
  if (value) {
    queryParams.value.params = queryParams.value.params || {};
    queryParams.value.params.beginReviewTime = value[0];
    queryParams.value.params.endReviewTime = value[1];
  } else {
    if (queryParams.value.params) {
      delete queryParams.value.params.beginReviewTime;
      delete queryParams.value.params.endReviewTime;
    }
  }
}

/** 新增入池单 */
const handleAdd = () => {
  proxy?.$router.push({
    path: '/product/poolLink',
    query: { type: 'add' }
  });
}

/** 查看详情 */
const handleView = async (row: PoolVO) => {
  const res = await getPool(row.id);
  viewForm.value = res.data;
  viewDialog.visible = true;
}

/** 去审核 */
const handleReview = (row: PoolVO) => {
  proxy?.$router.push({
    name: 'PoolReviewDetail',
    query: { poolId: row.id, poolName: row.name, type: 'edit', productReviewStatus: route.query.productReviewStatus as string }
  });
}

/** 提交审核 */
const submitReview = () => {
  viewFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        await updatePool({
          id: viewForm.value.id,
          itemId: viewForm.value.itemId,
          categoryId: viewForm.value.categoryId,
          type: viewForm.value.type,
          productReviewStatus: viewForm.value.productReviewStatus,
          reviewReason: viewForm.value.reviewReason
        } as any);
        proxy?.$modal.msgSuccess("审核成功");
        viewDialog.visible = false;
        await getList();
      } finally {
        buttonLoading.value = false;
      }
    }
  });
}

/** 申请入池单 */
const handleApply = async (row: PoolVO) => {
  try {
    await proxy?.$modal.confirm('确认要申请该产品池入池吗？');
    await updatePool({
      id: row.id,
      itemId: row.itemId,
      categoryId: row.categoryId,
      type: row.type,
      productReviewStatus: '1' // 更新为待审核
    } as any);
    proxy?.$modal.msgSuccess("申请成功");
    await getList();
  } catch {
    // 取消操作
  }
}

/** 修改入池 */
const handleModify = (row: PoolVO) => {
  proxy?.$router.push({
    path: '/product/poolLink',
    query: { poolId: row.id, poolName: row.name, type: 'edit', productReviewStatus: route.query.productReviewStatus as string }
  });
}

onMounted(() => {
  // 从路由获取审核状态
  if (route.query.productReviewStatus) {
    queryParams.value.productReviewStatus = route.query.productReviewStatus as string;
  }
  getList();
});
</script>

<style scoped lang="scss">
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
