<template>
  <view class="yd-page-container">
    <!-- 顶部导航栏 -->
    <wd-navbar
      title="供应商管理"
      left-arrow placeholder safe-area-inset-top fixed
      @click-left="handleBack"
    />

    <!-- 搜索组件 -->
    <view @click="searchVisible = true">
      <wd-search :placeholder="searchPlaceholder" hide-cancel disabled />
    </view>

    <!-- 供应商列表 -->
    <view class="px-24rpx">
      <view
        v-for="item in list"
        :key="item.id"
        class="mb-20rpx overflow-hidden rounded-12rpx bg-white shadow-sm"
        @click="handleEdit(item)"
      >
        <view class="p-24rpx">
          <!-- 头部：名称 + 状态 -->
          <view class="mb-16rpx flex items-center justify-between">
            <view class="text-30rpx text-[#333] font-semibold">
              {{ item.name || '-' }}
            </view>
            <view
              class="rounded-8rpx px-16rpx py-4rpx text-24rpx"
              :class="item.status === 0 ? 'bg-[#f6ffed] text-[#52c41a]' : 'bg-[#fff1f0] text-[#f5222d]'"
            >
              {{ item.status === 0 ? '正常' : '停用' }}
            </view>
          </view>
          <!-- 联系人 -->
          <view class="mb-8rpx flex items-center justify-between text-26rpx text-[#666]">
            <text class="text-[#999]">联系人</text>
            <text>{{ item.contact || '-' }}</text>
          </view>
          <!-- 手机号码 -->
          <view class="mb-8rpx flex items-center justify-between text-26rpx text-[#666]">
            <text class="text-[#999]">手机号码</text>
            <text>{{ item.mobile || '-' }}</text>
          </view>
          <!-- 联系电话 -->
          <view class="mb-8rpx flex items-center justify-between text-26rpx text-[#666]">
            <text class="text-[#999]">联系电话</text>
            <text>{{ item.telephone || '-' }}</text>
          </view>
          <!-- 电子邮箱 -->
          <view class="mb-8rpx flex items-center justify-between text-26rpx text-[#666]">
            <text class="text-[#999]">电子邮箱</text>
            <text>{{ item.email || '-' }}</text>
          </view>
          <!-- 备注 -->
          <view class="flex items-center justify-between text-26rpx text-[#666]">
            <text class="text-[#999]">备注</text>
            <text class="ml-16rpx line-clamp-1 text-right" style="max-width: 400rpx;">{{ item.remark || '无备注' }}</text>
          </view>
        </view>
        <!-- 操作按钮 -->
        <view class="flex flex-wrap gap-12rpx px-24rpx pb-20rpx" @click.stop>
          <wd-button
            v-if="hasAccessByCodes(['erp:supplier:update']) && item.name !== '-'"
            size="small" type="primary" plain @click="handleEdit(item)"
          >
            编辑
          </wd-button>
          <wd-button
            v-if="hasAccessByCodes(['erp:supplier:delete']) && item.name !== '-'"
            size="small" type="error" plain @click="handleDelete(item.id!)"
          >
            删除
          </wd-button>
        </view>
      </view>

      <!-- 加载更多 -->
      <view v-if="loadMoreState !== 'loading' && list.length === 0" class="py-100rpx text-center">
        <wd-status-tip image="content" tip="暂无供应商数据" />
      </view>
      <wd-loadmore
        v-if="list.length > 0"
        :state="loadMoreState"
        @reload="loadMore"
      />
    </view>

    <!-- 新增按钮 -->
    <wd-fab
      v-if="hasAccessByCodes(['erp:supplier:create'])"
      position="right-bottom"
      type="primary"
      :expandable="false"
      @click="handleAdd"
    />

    <!-- 搜索弹窗 -->
    <wd-popup v-model="searchVisible" position="top" @close="searchVisible = false">
      <view class="yd-search-form-container" :style="{ paddingTop: `${getNavbarHeight()}px` }">
        <view class="yd-search-form-item">
          <view class="yd-search-form-label">供应商名称</view>
          <wd-input v-model="searchForm.name" placeholder="请输入供应商名称" clearable />
        </view>
        <view class="yd-search-form-item">
          <view class="yd-search-form-label">手机号码</view>
          <wd-input v-model="searchForm.mobile" placeholder="请输入手机号码" clearable />
        </view>
        <view class="yd-search-form-item">
          <view class="yd-search-form-label">联系电话</view>
          <wd-input v-model="searchForm.telephone" placeholder="请输入联系电话" clearable />
        </view>
        <view class="yd-search-form-actions">
          <wd-button class="flex-1" plain @click="handleReset">重置</wd-button>
          <wd-button class="flex-1" type="primary" @click="handleSearch">搜索</wd-button>
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<script lang="ts" setup>
import type { Supplier } from '@/api/erp/supplier'
import type { LoadMoreState } from '@/http/types'
import { onReachBottom } from '@dcloudio/uni-app'
import { computed, onMounted, reactive, ref } from 'vue'
import { useToast } from 'wot-design-uni'
import { deleteSupplier, getSupplierPage } from '@/api/erp/supplier'
import { useAccess } from '@/hooks/useAccess'
import { getNavbarHeight, navigateBackPlus } from '@/utils'

definePage({
  style: {
    navigationBarTitleText: '',
    navigationStyle: 'custom',
  },
})

const { hasAccessByCodes } = useAccess()
const toast = useToast()
const total = ref(0)
const list = ref<Supplier[]>([])
const loadMoreState = ref<LoadMoreState>('loading')
const queryParams = ref<Record<string, any>>({
  pageNo: 1,
  pageSize: 10,
})

// 搜索相关
const searchVisible = ref(false)
const searchForm = reactive({
  name: undefined as string | undefined,
  mobile: undefined as string | undefined,
  telephone: undefined as string | undefined,
})

/** 搜索条件 placeholder */
const searchPlaceholder = computed(() => {
  const conditions: string[] = []
  if (searchForm.name) conditions.push(`名称:${searchForm.name}`)
  if (searchForm.mobile) conditions.push(`手机:${searchForm.mobile}`)
  if (searchForm.telephone) conditions.push(`电话:${searchForm.telephone}`)
  return conditions.length > 0 ? conditions.join(' | ') : '搜索供应商'
})

/** 返回上一页 */
function handleBack() {
  navigateBackPlus()
}

/** 查询供应商列表 */
async function getList() {
  loadMoreState.value = 'loading'
  try {
    const params = { ...queryParams.value }
    const data = await getSupplierPage(params)
    list.value = [...list.value, ...data.list]
    total.value = data.total
    loadMoreState.value = list.value.length >= total.value ? 'finished' : 'loading'
  } catch {
    queryParams.value.pageNo = queryParams.value.pageNo > 1 ? queryParams.value.pageNo - 1 : 1
    loadMoreState.value = 'error'
  }
}

/** 搜索 */
function handleSearch() {
  searchVisible.value = false
  queryParams.value = {
    ...searchForm,
    pageNo: 1,
    pageSize: queryParams.value.pageSize,
  }
  list.value = []
  getList()
}

/** 重置 */
function handleReset() {
  searchForm.name = undefined
  searchForm.mobile = undefined
  searchForm.telephone = undefined
  searchVisible.value = false
  queryParams.value = { pageNo: 1, pageSize: 10 }
  list.value = []
  getList()
}

/** 加载更多 */
function loadMore() {
  if (loadMoreState.value === 'finished') return
  queryParams.value.pageNo++
  getList()
}

/** 新增供应商 */
function handleAdd() {
  uni.navigateTo({ url: '/pages-erp/supplier/form/index' })
}

/** 编辑 */
function handleEdit(item: Supplier) {
  if (item.name === '-') return
  uni.navigateTo({ url: `/pages-erp/supplier/form/index?id=${item.id}` })
}

/** 删除 */
function handleDelete(id: number) {
  uni.showModal({
    title: '提示',
    content: '确定要删除该供应商吗？',
    success: async (res) => {
      if (!res.confirm) return
      try {
        await deleteSupplier(id)
        toast.success('删除成功')
        list.value = []
        queryParams.value.pageNo = 1
        getList()
      } catch {
        // error handled by http
      }
    },
  })
}

/** 触底加载更多 */
onReachBottom(() => {
  loadMore()
})

/** 初始化 */
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
</style>
