<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" label-width="100px">
              <el-input v-model="queryParams.name" placeholder="请输入产品池名称" clearable @keyup.enter="handleQuery" style="width:200px" />
            </el-form-item>
            <el-form-item label="申请时间">
              <el-date-picker
                v-model="applyTimeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD"
                style="width:280px"
              />
            </el-form-item>
            <el-form-item label="审核时间">
              <el-date-picker
                v-model="auditTimeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD"
                style="width:280px"
              />
            </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-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <div class="flex items-center justify-between">
          <span>产品池信息列表</span>

          <div class="ml-auto flex gap-2">
              <el-button v-if="productReviewStatus==='0'" type="primary" plain icon="Plus" @click="handleAdd">新增入池单</el-button>
              <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar> -->
          </div>
        </div>


      </template>

      <el-table v-loading="loading" border :data="poolAuditList">
        <el-table-column label="产品池名称" align="center" prop="name" />
        <el-table-column label="创建人" align="center" prop="createByName" />
        <el-table-column label="审核人" align="center" prop="auditByName" />
        <el-table-column label="状态" align="center" prop="productReviewStatus" width="120">
          <template #default="scope">
            <el-tag :type="reviewStatusTagType(scope.row.productReviewStatus)">
              {{ reviewStatusLabel(scope.row.productReviewStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="200">
          <template #default="scope">
            <!-- 审核通过或已驳回：只显示查看入池单 -->
            <template v-if="scope.row.productReviewStatus == '2' || scope.row.productReviewStatus == '3'">
              <el-button link type="primary" @click="handleAudit(scope.row)">查看入池单</el-button>
            </template>
            <!-- 其他状态：显示原有操作 -->
            <template v-else>
              <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>
              <el-button
                v-if="scope.row.productReviewStatus == '0' || scope.row.productReviewStatus === 0"
                link type="primary"
                @click="handleApply(scope.row)"
              >申请入池单</el-button>
              <el-button
                v-if="scope.row.productReviewStatus == '1' || scope.row.productReviewStatus === 1"
                link type="warning"
                @click="handleAudit(scope.row)"
              >去审核</el-button>
              <el-button
                v-if="scope.row.productReviewStatus == '0' || scope.row.productReviewStatus === 0"
                link type="primary"
                @click="handleUpdate(scope.row)"
              >修改入池单</el-button>
            </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="dialog.title" v-model="dialog.visible" width="700px" append-to-body>
      <el-form ref="poolAuditFormRef" :model="form" :rules="viewMode ? {} : rules" label-width="100px">
        <el-form-item label="池名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入池名称" :disabled="viewMode" />
        </el-form-item>
        <!-- 普通/营销产品池：选择产品池 -->
        <el-form-item v-if="poolType === 0 || poolType === 4" label="选择产品池" prop="poolId">
          <el-select v-model="form.poolId" placeholder="请选择产品池" clearable filterable style="width:100%" :disabled="viewMode">
            <el-option v-for="item in poolOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <!-- 协议产品池：选择协议 -->
        <el-form-item v-if="poolType === 2" label="选择协议" prop="protocolId">
          <el-select v-model="form.protocolId" placeholder="请选择协议" clearable filterable style="width:100%" :disabled="viewMode">
            <el-option
              v-for="item in protocolOptions"
              :key="item.id"
              :label="`${item.protocolNo} - ${item.customerName}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <!-- 项目产品池：选择项目 -->
        <el-form-item v-if="poolType === 3" label="选择项目" prop="itemId">
          <el-select v-model="form.itemId" placeholder="请选择项目" clearable filterable style="width:100%" :disabled="viewMode">
            <el-option v-for="item in itemOptions" :key="item.id" :label="item.itemName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :disabled="viewMode" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <template v-if="!viewMode">
            <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </template>
          <template v-else>
            <el-button @click="cancel">关 闭</el-button>
          </template>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PoolAudit" lang="ts">
import { listPoolAudit, getPoolAudit, delPoolAudit, addPoolAudit, updatePoolAudit, applyPoolAudit } from '@/api/product/poolAudit';
import { PoolAuditVO, PoolAuditQuery, PoolAuditForm } from '@/api/product/poolAudit/types';
import { listPool } from '@/api/product/pool';
import { PoolVO } from '@/api/product/pool/types';
import { listInfo } from '@/api/product/protocolInfo';
import { InfoVO } from '@/api/product/protocolInfo/types';
import { listItem } from '@/api/external/item';
import { ItemVO } from '@/api/external/item/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const route = useRoute();
const router = useRouter();

/** 从路由获取产品池类型：0普通,1精选,2协议,3项目,4营销 */
const poolType = computed(() => Number(route.query.type ?? -1));
const productReviewStatus = computed(() => route.query.productReviewStatus as string ?? "0");

/** 下拉选项数据 */
const poolOptions = ref<PoolVO[]>([]);
const protocolOptions = ref<InfoVO[]>([]);
const itemOptions = ref<ItemVO[]>([]);

/** 日期范围 */
const applyTimeRange = ref<[string, string] | null>(null);
const auditTimeRange = ref<[string, string] | null>(null);

/** 查看模式 */
const viewMode = ref(false);

/** 审核状态映射 */
const reviewStatusMap: Record<string, { label: string; type: string }> = {
  '0': { label: '待提交', type: 'info' },
  '1': { label: '待审核', type: 'warning' },
  '2': { label: '审核通过', type: 'success' },
  '3': { label: '审核驳回', type: 'danger' },
};

const reviewStatusLabel = (status: string | number) => {
  return reviewStatusMap[String(status)]?.label ?? '未知';
};

const reviewStatusTagType = (status: string | number): 'info' | 'warning' | 'success' | 'danger' | 'primary' => {
  return (reviewStatusMap[String(status)]?.type ?? 'info') as 'info' | 'warning' | 'success' | 'danger' | 'primary';
};

/** 根据 type 加载对应下拉选项 */
const loadSelectOptions = async () => {
  const type = poolType.value;
  if (type === 0 || type === 4) {
    const res = await listPool({ type } as any);
    poolOptions.value = res.rows ?? [];
  } else if (type === 2) {
    const res = await listInfo();
    protocolOptions.value = res.rows ?? [];
  } else if (type === 3) {
    const res = await listItem();
    itemOptions.value = res.rows ?? [];
  }
};

const poolAuditList = ref<PoolAuditVO[]>([]);
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 poolAuditFormRef = ref<ElFormInstance>();

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

const initFormData: PoolAuditForm = {
  id: undefined,
  name: undefined,
  poolId: undefined,
  itemId: undefined,
  type: poolType.value,
  protocolId: undefined,
  customerId: undefined,
  productReviewStatus: undefined,
  reviewReason: undefined,
  remark: undefined,
}
const data = reactive<PageData<PoolAuditForm, PoolAuditQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    poolId: undefined,
    itemId: undefined,
    type: poolType.value,
    protocolId: undefined,
    customerId: undefined,
    productReviewStatus: productReviewStatus.value,
    reviewReason: undefined,
    createByName: undefined,
    auditByName: undefined,
    params: {
    }
  },
  rules: {
    poolId: [
      { required: true, message: "池id不能为空", trigger: "blur" }
    ],
    itemId: [
      { required: true, message: "项目id不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "产品池类型不能为空", trigger: "change" }
    ],
    protocolId: [
      { required: true, message: "协议id不能为空", trigger: "blur" }
    ],
    customerId: [
      { required: true, message: "客户id不能为空", trigger: "blur" }
    ],
    reviewReason: [
      { required: true, message: "审核原因不能为空", trigger: "blur" }
    ],
    remark: [
      { required: true, message: "备注不能为空", trigger: "blur" }
    ],
  }
});

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

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

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

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

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  // 处理申请时间范围
  if (applyTimeRange.value) {
    queryParams.value.params.beginCreateTime = applyTimeRange.value[0];
    queryParams.value.params.endCreateTime = applyTimeRange.value[1];
  } else {
    queryParams.value.params.beginCreateTime = undefined;
    queryParams.value.params.endCreateTime = undefined;
  }
  // 处理审核时间范围
  if (auditTimeRange.value) {
    queryParams.value.params.beginAuditTime = auditTimeRange.value[0];
    queryParams.value.params.endAuditTime = auditTimeRange.value[1];
  } else {
    queryParams.value.params.beginAuditTime = undefined;
    queryParams.value.params.endAuditTime = undefined;
  }
  getList();
}

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  router.push({ path: '/product/poolLinkAudit' });
}

/** 查看按钮操作 */
const handleView = async (row: PoolAuditVO) => {
  reset();
  viewMode.value = true;
  const res = await getPoolAudit(row.id);
  Object.assign(form.value, res.data);
  await loadSelectOptions();
  dialog.visible = true;
  dialog.title = "查看入池单";
}

/** 修改按钮操作 */
const handleUpdate = (row?: PoolAuditVO) => {
  const _id = row?.id || ids.value[0];
  router.push({ path: '/product/poolLinkAudit', query: { id: _id } });
}

/** 去审核 */
const handleAudit = (row: PoolAuditVO) => {
  router.push({ path: '/product/poolAuditReview', query: { id: row.id } });
}

/** 申请入池单（待提交 -> 待审核） */
const handleApply = async (row: PoolAuditVO) => {
  await proxy?.$modal.confirm(`是否确认申请“${row.name}”入池单？确定后状态将变为待审核。`);
  await applyPoolAudit(row.id);
  proxy?.$modal.msgSuccess("申请入池单成功");
  await getList();
}

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

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

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

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