<template>
  <div class="p-2 w-full">
    <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" class="w-full">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="120px">
            <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="supplierName">
              <el-input v-model="queryParams.supplierName" placeholder="供应商名称" clearable @keyup.enter="handleQuery" />
            </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="supplyBrand">
              <el-input v-model="queryParams.supplyBrand" placeholder="可供货品牌" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="授权品牌" prop="brandName">
              <el-input v-model="queryParams.brandName" 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-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never" class="w-full">
      <template #header>
        供应能力查询信息列表
      </template>

      <el-table v-loading="loading" border :data="supplierauthorizeList" class="supplierauthorize-table" table-layout="fixed" highlight-current-row @current-change="handleCurrentChange" style="width: 100%">
        <el-table-column label="供应商编号" align="left" prop="supplierNo" width="110" fixed="left" />
        <el-table-column label="供应商名称" align="left" prop="supplierName" width="250" fixed="left" />
        <el-table-column label="供货区域（省）" align="center" prop="province" min-width="180">
          <template #default="scope">
            <el-tooltip :content="scope.row.province || ''" placement="top" :show-after="300">
              <span class="ellipsis">{{ formatProvinceDisplay(scope.row.province) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="供货区域（市）" align="center" prop="city" min-width="300">
          <template #default="scope">
            <el-tooltip :content="scope.row.city || ''" placement="top" :show-after="300">
              <span class="ellipsis">{{ formatCityDisplay(scope.row.city) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="供货类目" align="center" prop="supplyProCate" min-width="140" />
        <el-table-column label="可供货品牌" align="center" prop="brandName" min-width="140" />
        <el-table-column label="有授权品牌" align="center" prop="authBrand" min-width="140" />
        
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120" fixed="right">
          <template #default="scope">
            <div class="op-actions">
              <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>
              <el-button link type="primary" @click="handleEdit(scope.row)" v-hasPermi="['supplier:supplierauthorize:edit']">编辑</el-button>
            </div>
          </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="Supplierauthorize" lang="ts">
import { listSupplierauthorize, getSupplierauthorize, delSupplierauthorize, addSupplierauthorize, updateSupplierauthorize } from '@/api/supplier/supplierauthorize';
import { SupplierauthorizeVO, SupplierauthorizeQuery, SupplierauthorizeForm } from '@/api/supplier/supplierauthorize/types';

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

const supplierauthorizeList = ref<SupplierauthorizeVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const currentId = ref<string | number | undefined>(undefined);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

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

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

const initFormData: SupplierauthorizeForm = {
  supplierNo: undefined,
  supplierId: undefined,
  authorizeNo: undefined,
  brandNo: undefined,
  brandName: undefined,
  brandEnglishName: undefined,
  brandLogo: undefined,
  authorizeType: undefined,
  authorizationCategory: undefined,
  brandLicensor: undefined,
  authorizationRelationshipFile: undefined,
  authorizationStartTime: undefined,
  authorizationEndTime: undefined,
  authorizedArea: undefined,
  brandHoldType: undefined,
  authorizeLevel: undefined,
  authorizedStatus: undefined,
  authorizationRelationshipFileName: undefined,
  brandRegistrant: undefined,
  reviewFeedback: undefined,
}
const data = reactive<PageData<SupplierauthorizeForm, SupplierauthorizeQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    supplierNo: undefined,
    brandName: undefined,
    authorizeType: undefined,
    authorizationCategory: undefined,
    brandLicensor: undefined,
    authorizationRelationshipFile: undefined,
    authorizationStartTime: undefined,
    authorizationEndTime: undefined,
    authorizedArea: undefined,
    brandHoldType: undefined,
    authorizeLevel: undefined,
    authorizedStatus: undefined,
    authorizationRelationshipFileName: undefined,
    brandRegistrant: undefined,
    reviewFeedback: undefined,
    params: {
    }
  },
  rules: {
  }
});

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

/** 查询供应能力查询列表 */
const getList = async () => {
  loading.value = true;
  const res = await listSupplierauthorize(queryParams.value);
  supplierauthorizeList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

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

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

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

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

/** 当前行变更 */
const handleCurrentChange = (currentRow?: SupplierauthorizeVO) => {
  currentId.value = currentRow?.id;
  single.value = !currentId.value;
  multiple.value = !currentId.value;
}

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

/** 编辑按钮操作 */
const handleEdit = (row: SupplierauthorizeVO) => {
  router.push({
    path: '/customer/info/detail',
    query: {
      id: row.supplierId,
      mode: 'edit'
    }
  });
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加供应能力查询";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: SupplierauthorizeVO) => {
  reset();
  const _id = row?.id || currentId.value;
  if (!_id) return;
  const res = await getSupplierauthorize(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改供应能力查询";
}

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

/** 删除按钮操作 */
const handleDelete = async (row?: SupplierauthorizeVO) => {
  const _id = row?.id || currentId.value;
  if (!_id) return;
  await proxy?.$modal.confirm('是否确认删除供应能力查询编号为"' + _id + '"的数据项？').finally(() => loading.value = false);
  await delSupplierauthorize(_id);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

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

/** 格式化省份显示：只显示第一个省份，其余用...表示 */
const formatProvinceDisplay = (province: string) => {
  if (!province) return '';
  const provinces = province.split(',').filter(p => p.trim());
  if (provinces.length === 0) return '';
  if (provinces.length === 1) return provinces[0];
  if (provinces.length <= 3) return provinces.join(',');
  return `${provinces.slice(0, 3).join(',')}...`;
};

/** 格式化城市显示：显示前10个城市，其余用...表示 */
const formatCityDisplay = (city: string) => {
  if (!city) return '';
  const cities = city.split(',').filter(c => c.trim());
  if (cities.length === 0) return '';
  if (cities.length <= 10) return cities.join(',');
  return `${cities.slice(0, 10).join(',')}...`;
};

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

<style scoped>

.ellipsis {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  vertical-align: middle;
}

.supplierauthorize-table :deep(.el-table__cell) {
  padding-top: 14px;
  padding-bottom: 14px;
}

.supplierauthorize-table :deep(.cell) {
  line-height: 24px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.op-actions {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 6px;
}

</style>
