<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" label-width="100px">
            <el-form-item label="供应商编号" prop="supplierNo">
              <el-input v-model="queryParams.supplierNo" placeholder="供应商编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="供应商名称" prop="enterpriseName">
              <el-input v-model="queryParams.enterpriseName" placeholder="供应商名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="供应商类型" prop="supplierType">
              <el-select v-model="queryParams.supplierType" placeholder="请选择供应商类型" clearable>
                <el-option v-for="item in supplierTypeList" :key="item.typeId" :label="item.typeName" :value="item.typeId" />
              </el-select>
            </el-form-item>
            <el-form-item label="供应品牌" prop="operatingBrand">
              <el-input v-model="queryParams.operatingBrand" placeholder="供应品牌" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="供应类别" prop="operatingCategory">
              <el-select v-model="queryParams.operatingCategory" placeholder="请选择供应类别" clearable>
                <el-option v-for="item in productCategoryList" :key="item.id" :label="item.categoryName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="供应区域" prop="province">
              <el-input v-model="queryParams.province" placeholder="供应区域（省）" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="供应区域" prop="city">
              <el-input v-model="queryParams.city" placeholder="供应区域（市）" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="产品经理" prop="productManager">
              <el-select v-model="queryParams.productManager" placeholder="请选择产品经理" clearable>
                <el-option v-for="item in comStaffList" :key="item.staffId" :label="item.staffName" :value="item.staffId" />
              </el-select>
            </el-form-item>
            <el-form-item label="采购人员" prop="buyer">
              <el-select v-model="queryParams.buyer" placeholder="请选择采购人员" clearable>
                <el-option v-for="item in comStaffList" :key="item.staffId" :label="item.staffName" :value="item.staffId" />
              </el-select>
            </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>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5" >
           供应商信息列表
          </el-col>
          
          
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="infoList" class="no-resize-table" @selection-change="handleSelectionChange">
        <el-table-column label="供应商编号" align="center" prop="supplierNo" width="150" fixed="left" />
        <el-table-column label="供应商名称" align="left" prop="enterpriseName" width="250" fixed="left" />
        <el-table-column label="供应商类型" align="center" prop="supplierTypeName" width="200">
        </el-table-column>
        
        <el-table-column label="产品经理" align="center" prop="productManager" width="150" />
        <el-table-column label="采购人员" align="center" prop="buyer" width="150" />
        <el-table-column label="上架产品数" align="center" prop="listedNum" width="150" />
        <el-table-column label="供应品牌" align="center" prop="brandName" width="200" />
        <el-table-column label="供应区域（省）" align="left" prop="province" width="250" />
        <el-table-column label="供应区域（市）" align="left" prop="city" width="300" />
        
        
        
        <el-table-column label="审核状态" align="center" prop="supplyStatus" width="150">
          <template #default="scope">
            <span>{{ getStatusDisplayName(scope.row.supplyStatus) }}</span>
          </template>
        </el-table-column>  
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250" fixed="right">
          <template #default="scope">
            
            <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['customer:info:edit']">编辑</el-button>
            <el-button link type="primary" @click="handleStopCooperation(scope.row)" v-hasPermi="['customer:info:edit']">恢复合作</el-button>
          </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>
  </div>
</template>

<script setup name="None" lang="ts">
import { getInfoList, getInfo, delInfo, addInfo, updateInfo, getComSupTyList, getProductCategoryList, getComStaffList } from '@/api/customer/info';
import { InfoVO, InfoQuery, InfoForm } from '@/api/customer/info/types';
import { getSupplierStatusOptions, getSupplierStatusDisplayName } from '@/enums/supplierStatus';
import { getSupplierCooperationStatusDisplayName } from '@/enums/supplierCooperationStatus';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const infoList = ref<InfoVO[]>([]);
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 supplierTypeList = ref<{ typeId: string; typeName: string }[]>([]);
const productCategoryList = ref<{ categoryNo: string; categoryName: string; id?: number }[]>([]);
const comStaffList = ref<{ staffId: string; staffName: string }[]>([]);

const queryFormRef = ref<ElFormInstance>();

const data = reactive<{ queryParams: InfoQuery }>({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    supplierNo: undefined,
    enterpriseName: undefined,
    supplierType: undefined,
    operatingBrand: undefined,
    operatingCategory: undefined,
    province: undefined,
    city: undefined,
    productManager: undefined,
    buyer: undefined,
    supplyStatus: '2', // 固定为2
    params: {}
  }
});

const { queryParams } = toRefs(data);

/** 查询供应商信息列表 */
const getList = async () => {
  loading.value = true;
  // 确保 supplyStatus 始终为 2
  queryParams.value.supplyStatus = '2';
  const res = await getInfoList(queryParams.value);
  infoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  // 重置后仍然保持 supplyStatus = 2
  queryParams.value.supplyStatus = '2';
  handleQuery();
}

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

/** 新增按钮操作 */
const handleAdd = () => {
  // 新增逻辑
}

/** 修改按钮操作 */
const handleUpdate = async (row?: InfoVO) => {
  const router = proxy?.$router;
  const _id = row?.id || ids.value[0];
  router?.push({
    path: '/customer/info/detail',
    query: {
      id: _id,
      mode: 'edit'
    }
  });
}

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

/** 查看按钮操作 */
const handleView = (row: InfoVO) => {
  const router = proxy?.$router;
  router?.push({
    path: '/customer/info/detail',
    query: {
      id: row.id
    }
  });
}

/** 恢复合作按钮操作 */
const handleStopCooperation = async (row: InfoVO) => {
  await proxy?.$modal.confirm('是否确认恢复与供应商"' + row.enterpriseName + '"的合作？');
  try {
    // 只传id和supplyStatus
    await updateInfo({ 
      id: row.id,
      supplyStatus: '1' 
    });
    proxy?.$modal.msgSuccess("恢复合作成功");
    await getList();
  } catch (e) {
    console.error('恢复合作失败:', e);
  }
}

/** 获取供应商类型列表 */
const getSupplierTypeList = async () => {
  try {
    const res = await getComSupTyList();
    supplierTypeList.value = res.data || res;
  } catch (e) {
    console.error('获取供应商类型失败', e);
  }
}

/** 获取产品分类列表 */
const getProductCategoryData = async () => {
  try {
    const res = await getProductCategoryList();
    productCategoryList.value = res.data;
  } catch (e) {
    console.error('获取产品分类失败', e);
  }
}

/** 根据typeId获取typeName */
const getSupplierTypeName = (typeId: string) => {
  const item = supplierTypeList.value.find(t => t.typeId === typeId);
  return item ? item.typeName : typeId;
}

/** 根据状态码获取状态显示名称 */
const getStatusDisplayName = (statusCode: number) => {
  return getSupplierStatusDisplayName(statusCode);
}

/** 根据合作状态码获取合作状态显示名称 */
const getCooperationStatusDisplayName = (statusCode: number) => {
  return getSupplierCooperationStatusDisplayName(statusCode);
}

onMounted(async () => {
  getSupplierTypeList();
  getProductCategoryData();
  
  try {
    const staffRes = await getComStaffList({ pageNum: 1, pageSize: 100000 });
    comStaffList.value = staffRes.rows || [];
  } catch (e) {
    console.error('人员接口调用失败:', e);
  }
  
  getList();
  
  // 禁用表格列宽调整
  nextTick(() => {
    const table = document.querySelector('.no-resize-table');
    if (table) {
      table.addEventListener('mousedown', (e: any) => {
        const target = e.target as HTMLElement;
        // 阻止在表头边界处的鼠标按下事件
        if (target.classList.contains('el-table__column-resize-proxy') || 
            target.closest('.el-table__column-resize-proxy')) {
          e.preventDefault();
          e.stopPropagation();
          return false;
        }
      }, true);
    }
  });
});
</script>

<style scoped>
:deep(.el-form-item__label) {
  text-align: left !important;
}

:deep(.el-form-item) {
  margin-right: 30px;
  margin-bottom: 20px;
}

/* 禁用表格列宽拖动 */
.no-resize-table :deep(th.el-table__cell) {
  user-select: none !important;
  resize: none !important;
  cursor: default !important;
}

.no-resize-table :deep(.el-table__header-wrapper th) {
  cursor: default !important;
}

.no-resize-table :deep(.el-table__header-wrapper .el-table__cell:hover) {
  cursor: default !important;
}

.no-resize-table :deep(.el-table__header-wrapper) {
  cursor: default !important;
}

/* 隐藏列宽调整的分隔线悬停效果 */
.no-resize-table :deep(th.el-table__cell:hover) {
  cursor: default !important;
}

.no-resize-table :deep(.el-table__header th.el-table__cell) {
  border-right: 1px solid #EBEEF5;
}

/* 禁用拖动事件 */
.no-resize-table :deep(.el-table__header-wrapper) {
  pointer-events: auto;
}

.no-resize-table :deep(.el-table__header th) {
  pointer-events: auto;
}

.no-resize-table :deep(.el-table__header .cell) {
  pointer-events: auto;
}
</style>
