<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="searchParams" :inline="true" class="search-form" >
      
      <el-form-item label="品牌名称">
        <el-select
          v-model="searchParams.brandName"
          placeholder="请选择品牌"
          clearable
          filterable
          remote
          :remote-method="searchBrand"
          :loading="brandLoading"
          style="width: 200px;"
          @visible-change="handleBrandDropdownVisible"
        >
          <el-option
            v-for="brand in brandList"
            :key="brand.id"
            :label="brand.brandName"
            :value="brand.brandName"
          />
          <el-option v-if="brandLoading" disabled value="">
            <div style="text-align: center;">加载中...</div>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="品牌编号">
        <el-input v-model="searchParams.brandNo" placeholder="请输入品牌编号" clearable style="width: 200px;" />
      </el-form-item>
      <el-form-item label="省">
        <el-select
          v-model="searchParams.province"
          placeholder="请选择省"
          clearable
          filterable
          style="width: 200px;"
          @change="handleProvinceChange"
          @clear="handleProvinceClear"
        >
          <el-option
            v-for="p in provinceOptions"
            :key="p.value"
            :label="p.label"
            :value="p.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="市">
        <el-select
          v-model="searchParams.city"
          placeholder="请选择市"
          clearable
          filterable
          :disabled="!searchParams.province"
          style="width: 200px;"
        >
          <el-option
            v-for="c in cityOptions"
            :key="c.value"
            :label="c.label"
            :value="c.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
        <el-button icon="Refresh" @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 产品线管理列表以及分页卡片 -->
    <el-card shadow="never" class="table-card">
      <template #header>
        <div class="table-header-content">
          <span class="table-title">品牌授权信息列表</span>
          
        </div>
      </template>

      <!-- 授权详情信息列表 -->
      <el-table v-loading="loading" :data="authorizationList" border style="width: 100%">
        <el-table-column prop="supplierName" label="供应商名称" align="center" />
        <el-table-column prop="brandName" label="品牌名称" align="center" />
        <el-table-column label="一级类目" align="center">
          <template #default="scope">
            <span>{{ scope.row.categorysMap?.oneLevelName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="二级类目" align="center">
          <template #default="scope">
            <span>{{ scope.row.categorysMap?.twoLevelName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="三级类目" align="center">
          <template #default="scope">
            <span>{{ scope.row.categorysMap?.threeLevelName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="authorizationEndTime" label="资质到期日期" align="center">
          <template #default="scope">
            <span>{{ scope.row.authorizationEndTime ? formatDate(scope.row.authorizationEndTime) : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="授权区域(省)" align="center">
          <template #default="scope">
            <el-tooltip
              :content="formatAuthorizedProvinces(scope.row)"
              placement="top"
              :disabled="formatAuthorizedProvinces(scope.row) === '-'"
            >
              <span class="cell-ellipsis">{{ formatAuthorizedProvinces(scope.row) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="授权区域(市)" align="center">
          <template #default="scope">
            <el-tooltip
              :content="formatAuthorizedCities(scope.row)"
              placement="top"
              :disabled="formatAuthorizedCities(scope.row) === '-'"
            >
              <span class="cell-ellipsis">{{ formatAuthorizedCities(scope.row) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="authorizedStatus" label="状态" align="center">
          <template #default="scope">
            <span>{{ getAuthorizedStatusText(scope.row.authorizedStatus) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template #default="scope">
            <div class="flex items-center justify-center gap-1 whitespace-nowrap">
              <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>
              <el-button link type="primary" @click="handleAudit(scope.row)">审核</el-button>
              <el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog
      v-model="auditDialogVisible"
      title="审核"
      width="560px"
      :close-on-click-modal="false"
    >
      <el-form :model="auditForm" label-width="90px">
        <el-form-item label="审核结果">
          <el-select v-model="auditForm.authorizedStatus" placeholder="请选择" style="width: 100%;">
            <el-option v-for="item in authorizedStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核意见">
          <el-input v-model="auditForm.reviewFeedback" type="textarea" :rows="4" placeholder="请输入审核意见" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="auditSubmitLoading" @click="handleAuditSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, computed, getCurrentInstance, toRefs } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useUserStore } from '@/store/modules/user';
import { getAuthorizeDetailList, examSupplierauthorize } from '@/api/supplier/supplierauthorize';
import { listBrand } from '@/api/product/brand';
import { ElMessage } from 'element-plus';

defineOptions({
  name: 'Author2015618489107828737'
});

const router = useRouter();
const route = useRoute();

const editPath = '/supplierexam/edit';
const detailPath = '/supplierexam/detail';

const { proxy } = getCurrentInstance() as any;
const { authorized_status } = toRefs<any>(proxy?.useDict('authorized_status'));

const authorizedStatusOptions = computed(() => {
  return (authorized_status.value || []).filter((d: any) => String(d?.value) !== '0');
});

const auditDialogVisible = ref(false);
const auditSubmitLoading = ref(false);
const auditId = ref<string | number>('');
const auditForm = ref({
  authorizedStatus: '1',
  reviewFeedback: ''
});

const userStore = useUserStore();
const authorizationList = ref<any[]>([]);
const loading = ref(false);

const supplierNo = computed(() => {
  const q = route.query as Record<string, any>;
  return q.supplierNo || q.no || (userStore as any).supplierNo;
});

// 授权区域（省/市）回显：使用 element-china-area-data
const areaOptions = ref<any[]>([]);
const provinceOptions = ref<any[]>([]);
const cityOptions = ref<any[]>([]);

// 品牌相关
const brandList = ref<any[]>([]);
const brandLoading = ref(false);
const brandPagination = ref({
  pageNum: 1,
  pageSize: 100
});
const hasMoreBrands = ref(true);
const isSearchMode = ref(false); // 是否在搜索模式

// 搜索参数
const searchParams = ref({
  brandNo: '',
  brandName: '',
  province: '', // 省ID（2位）
  city: ''      // 市ID（4位）
});

// 分页参数
const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
});

/** 获取品牌列表 */
const getBrandList = async (reset = false) => {
  if (reset) {
    brandPagination.value.pageNum = 1;
    brandList.value = [];
  }

  try {
    brandLoading.value = true;
    const res = await listBrand({
      pageNum: brandPagination.value.pageNum,
      pageSize: brandPagination.value.pageSize
    });
    
    const newBrands = res.rows || [];
    if (reset) {
      brandList.value = newBrands;
    } else {
      brandList.value = [...brandList.value, ...newBrands];
    }
    
    // 判断是否还有更多数据
    hasMoreBrands.value = newBrands.length === brandPagination.value.pageSize;
    
    console.log('品牌列表:', brandList.value);
  } catch (e) {
    console.error('获取品牌列表失败:', e);
  } finally {
    brandLoading.value = false;
  }
};

/** 搜索品牌 */
const searchBrand = async (query: string) => {
  if (!query) {
    isSearchMode.value = false;
    await getBrandList(true);
    return;
  }
  
  isSearchMode.value = true;
  try {
    brandLoading.value = true;
    const res = await listBrand({
      brandName: query,
      pageNum: 1,
      pageSize: 100
    });
    brandList.value = res.rows || [];
    hasMoreBrands.value = false; // 搜索模式下不支持加载更多
  } catch (e) {
    console.error('搜索品牌失败:', e);
  } finally {
    brandLoading.value = false;
  }
};

/** 下拉框显示/隐藏 */
const handleBrandDropdownVisible = async (visible: boolean) => {
  if (visible && brandList.value.length === 0) {
    await getBrandList(true);
    // 添加滚动监听
    await nextTick();
    addScrollListener();
  } else if (!visible) {
    // 移除滚动监听
    removeScrollListener();
  }
};

/** 添加滚动监听 */
const addScrollListener = () => {
  const dropdown = document.querySelector('.el-select-dropdown__wrap');
  if (dropdown) {
    dropdown.addEventListener('scroll', handleScroll);
  }
};

/** 移除滚动监听 */
const removeScrollListener = () => {
  const dropdown = document.querySelector('.el-select-dropdown__wrap');
  if (dropdown) {
    dropdown.removeEventListener('scroll', handleScroll);
  }
};

/** 处理滚动事件 */
const handleScroll = async (e: Event) => {
  const target = e.target as HTMLElement;
  const scrollTop = target.scrollTop;
  const scrollHeight = target.scrollHeight;
  const clientHeight = target.clientHeight;
  
  // 滚动到底部，且不在搜索模式，且还有更多数据，且不在加载中
  if (scrollTop + clientHeight >= scrollHeight - 10 && 
      !isSearchMode.value && 
      hasMoreBrands.value && 
      !brandLoading.value) {
    await loadMoreBrands();
  }
};

/** 加载更多品牌 */
const loadMoreBrands = async () => {
  brandPagination.value.pageNum++;
  await getBrandList(false);
};

const toProvinceCityOptions = (options: any[]) => {
  return (options || []).map((province) => {
    const provinceValue6 = String(province.value ?? '');
    const provinceValue = provinceValue6.length >= 2 ? provinceValue6.slice(0, 2) : provinceValue6;

    const cities = (province.children || []).map((city: any) => {
      const cityValue6 = String(city.value ?? '');
      const cityValue = cityValue6.length >= 4 ? cityValue6.slice(0, 4) : cityValue6;
      const { children, ...rest } = city;
      return {
        ...rest,
        value: cityValue
      };
    });

    return {
      ...province,
      value: provinceValue,
      children: cities
    };
  });
};

/** 根据value查找区域名称 */
const findRegionNameById = (id: string | number, regions: any[]): string => {
  const targetId = String(id ?? '').trim();
  if (!targetId) return '';
  const region = (regions || []).find((r: any) => String(r.value) === targetId);
  return region?.label || '';
};

const isProvinceCode = (val: any) => {
  const s = String(val ?? '').trim();
  return /^\d{2}$/.test(s);
};

const isCityCode = (val: any) => {
  const s = String(val ?? '').trim();
  return /^\d{4}$/.test(s);
};

const normalizeCityDisplayName = (provinceName: string, cityName: string) => {
  const p = String(provinceName || '');
  const c = String(cityName || '');
  if (!c) return '';
  if (c === '市辖区') {
    return p.endsWith('市') ? p : `${p}市`;
  }
  return c;
};

/** 从行数据中提取授权区域ID列表（兼容 authorizedArea / province / city） */
const getRowAreaIds = (row: any): string[] => {
  if (row?.authorizedArea) {
    return String(row.authorizedArea)
      .split(',')
      .map((s) => String(s ?? '').trim())
      .filter(Boolean);
  }

  const ids: string[] = [];
  const p = String(row?.province ?? '').trim();
  const c = String(row?.city ?? '').trim();
  if (p) ids.push(p);
  if (c) ids.push(c);
  return ids;
};

/** 授权区域(省)回显 */
const formatAuthorizedProvinces = (row: any) => {
  const ids = getRowAreaIds(row);
  const provinceIds = ids.filter((id) => isProvinceCode(id));
  const provinceNames = provinceIds
    .map((pid) => findRegionNameById(pid, areaOptions.value))
    .filter(Boolean);
  return provinceNames.length ? Array.from(new Set(provinceNames)).join('，') : '-';
};

/** 授权区域(市)回显 */
const formatAuthorizedCities = (row: any) => {
  const ids = getRowAreaIds(row);
  const cityIds = ids.filter((id) => isCityCode(id));
  if (!cityIds.length) return '-';

  const provinceMap = new Map<string, Set<string>>();
  cityIds.forEach((cid) => {
    const provinceId = String(cid).slice(0, 2);
    const provinceName = findRegionNameById(provinceId, areaOptions.value);
    if (!provinceName) return;

    const province = areaOptions.value.find((p: any) => String(p.value) === String(provinceId));
    const cityName = province ? findRegionNameById(cid, province.children || []) : '';
    const displayCityName = normalizeCityDisplayName(provinceName, cityName);
    if (!displayCityName) return;

    if (!provinceMap.has(provinceName)) {
      provinceMap.set(provinceName, new Set());
    }
    provinceMap.get(provinceName)!.add(displayCityName);
  });

  const allCities: string[] = [];
  provinceMap.forEach((cities) => {
    allCities.push(...Array.from(cities));
  });
  return allCities.length ? allCities.join('，') : '-';
};

/** 初始化授权区域选项数据 */
const initAreaOptions = async () => {
  try {
    const mod: any = await import('element-china-area-data');
    areaOptions.value = toProvinceCityOptions(mod?.regionData as any);
    provinceOptions.value = areaOptions.value || [];
  } catch (e) {
    console.error('获取授权区域数据失败:', e);
  }
};

const refreshCityOptions = () => {
  const pid = String(searchParams.value.province ?? '').trim();
  if (!pid) {
    cityOptions.value = [];
    return;
  }
  const province = provinceOptions.value.find((p: any) => String(p.value) === pid);
  cityOptions.value = province?.children || [];
};

const handleProvinceChange = () => {
  searchParams.value.city = '';
  refreshCityOptions();
};

const handleProvinceClear = () => {
  searchParams.value.city = '';
  refreshCityOptions();
};

/** 获取授权详情列表 */
const getAuthorizationList = async () => {
  if (!supplierNo.value) {
    console.warn('supplierNo 为空，授权详情将按当前条件尝试查询');
  }

  try {
    loading.value = true;
    console.log('获取授权详情列表，供应商编号:', supplierNo.value);
    const res = await getAuthorizeDetailList({ 
      supplierNo: supplierNo.value,
      brandNo: searchParams.value.brandNo,
      brandName: searchParams.value.brandName,
      province: searchParams.value.province,
      city: searchParams.value.city,
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize
    });
    authorizationList.value = res.rows || [];
    pagination.value.total = res.total || 0;
    console.log('授权详情列表:', authorizationList.value);
  } catch (e) {
    console.error('获取授权详情列表失败:', e);
    ElMessage.error('获取授权详情列表失败');
  } finally {
    loading.value = false;
  }
};

/** 搜索 */
const handleSearch = () => {
  pagination.value.pageNum = 1;
  getAuthorizationList();
};

/** 重置 */
const handleReset = () => {
  searchParams.value = {
    brandNo: '',
    brandName: '',
    province: '',
    city: ''
  };
  refreshCityOptions();
  pagination.value.pageNum = 1;
  getAuthorizationList();
};

/** 添加授权 */
const handleAdd = () => {
  router.push({ path: editPath });
};

/** 查看 */
const handleView = (row: any) => {
  router.push({ path: detailPath, query: { id: row.id } });
};

/** 审核 */
const handleAudit = (row: any) => {
  auditId.value = row?.id;
  auditForm.value = {
    authorizedStatus: '1',
    reviewFeedback: ''
  };
  auditDialogVisible.value = true;
};

const handleAuditSubmit = async () => {
  if (!auditId.value) {
    ElMessage.error('缺少ID');
    return;
  }
  try {
    auditSubmitLoading.value = true;
    await examSupplierauthorize({
      id: auditId.value,
      authorizedStatus: auditForm.value.authorizedStatus,
      reviewFeedback: auditForm.value.reviewFeedback
    } as any);
    ElMessage.success('审核成功');
    auditDialogVisible.value = false;
    await getAuthorizationList();
  } catch (e) {
    console.error('审核失败:', e);
    ElMessage.error('审核失败');
  } finally {
    auditSubmitLoading.value = false;
  }
};

/** 编辑 */
const handleEdit = (row: any) => {
  router.push({ path: editPath, query: { id: row.id, action: 'edit' } });
};

/** 分页大小改变 */
const handleSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  getAuthorizationList();
};

/** 当前页改变 */
const handleCurrentChange = (page: number) => {
  pagination.value.pageNum = page;
  getAuthorizationList();
};

/** 格式化日期 */
const formatDate = (date: string | Date) => {
  if (!date) return '-';
  const d = new Date(date);
  // 使用本地时区格式化日期，避免时区问题
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

/** 获取授权状态文本 */
const getAuthorizedStatusText = (status: string) => {
  const target = String(status ?? '');
  const matched = (authorized_status.value || []).find((d: any) => String(d?.value) === target);
  return matched?.label || '未知';
};

onMounted(async () => {
  // 并行加载品牌列表和授权详情列表
  await Promise.all([
    getBrandList(true),
    initAreaOptions(),
    getAuthorizationList()
  ]);
});
</script>

<style scoped>
.app-container {
  padding: 20px;
  background: #f0f2f5;
  min-height: calc(100vh - 84px);
}

.search-form {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.table-card {
  margin-top: 0px;
}

.table-header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #999;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding-top: 20px;
}

.cell-ellipsis {
  display: block;
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
