<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <!-- 第一行：搜索内容 -->
      <el-row :gutter="20">
        <!-- 左边部分：最多4个搜索条件 -->
        <el-col :span="22">
          <el-row :gutter="20">
            <el-col :span="6" v-for="(field, index) in visibleFields" :key="index">
              <el-form-item :label="field.label" :prop="field.prop">
                <el-input
                  v-model="queryParams[field.prop]"
                  :placeholder="`请输入${field.label}`"
                  clearable
                  @keyup.enter="handleQuery"
                  class="!w-240px"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <!-- 右边部分：展开按钮 -->
        <el-col :span="2" style="text-align: right;" v-if="hasMoreFields">
          <el-form-item>
            <el-button type="text" @click="toggleShowMore">
              {{ showMore ? '收起' : '展开更多' }}
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 更多搜索条件 -->
      <el-collapse-transition>
        <div v-show="showMore">
          <el-row :gutter="22">
            <el-col :span="6" v-for="(field, index) in hiddenFields" :key="index">
              <el-form-item :label="field.label" :prop="field.prop">
                <el-input
                  v-model="queryParams[field.prop]"
                  :placeholder="`请输入${field.label}`"
                  clearable
                  @keyup.enter="handleQuery"
                  class="!w-240px"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-collapse-transition>

      <!-- 第二行：搜索按钮 -->
      <el-row :gutter="20">
        <el-col :span="24" style="text-align: right;">
          <el-form-item>
            <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
            <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
            <el-button
              type="primary"
              plain
              @click="openForm('create')"
              v-hasPermi="['pm:customer:create']"
            >
              <Icon icon="ep:plus" class="mr-5px" /> 新增
            </el-button>
            <el-button
              type="success"
              plain
              @click="handleExport"
              :loading="exportLoading"
              v-hasPermi="['pm:customer:export']"
            >
              <Icon icon="ep:download" class="mr-5px" /> 导出
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="客户名称" align="center" prop="name" />
      <el-table-column label="机构代码" align="center" prop="code" />
      <el-table-column label="联系人" align="center" prop="contacts" />
      <el-table-column label="电话" align="center" prop="phone" />
      <el-table-column label="地址" align="center" prop="address" />
      <el-table-column label="累计合同签订额" align="center" prop="total_contract_amount" />
      <el-table-column label="累计三年及以上应收款" align="center" prop="total_accounts_receivable" />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['pm:customer:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['pm:customer:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <CustomerForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { CustomerApi, CustomerVO } from '@/api/pm/customer'
import CustomerForm from './CustomerForm.vue'
import { ref, onMounted, computed } from 'vue'

/** 客户信息 列表 */
defineOptions({ name: 'Customer' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<CustomerVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  code: undefined,
  contacts: undefined,
  phone: undefined,
  address: undefined,
  // 可以继续添加其他字段
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const showMore = ref(false) // 控制更多搜索项的显示

// 定义所有搜索字段
const allFields = [
  { label: '名称', prop: 'name' },
  { label: '机构代码', prop: 'code' },
  { label: '联系人', prop: 'contacts' },
  { label: '电话', prop: 'phone' },
  { label: '地址', prop: 'address' },
  // 可以继续添加其他字段
]

// 计算可见字段和隐藏字段
const visibleFields = computed(() => allFields.slice(0, 4))
const hiddenFields = computed(() => allFields.slice(4))
const hasMoreFields = computed(() => allFields.length > 4)

/** 切换更多搜索项的显示 */
const toggleShowMore = () => {
  showMore.value = !showMore.value
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await CustomerApi.getCustomerPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

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

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

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await CustomerApi.deleteCustomer(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await CustomerApi.exportCustomer(queryParams)
    download.excel(data, '客户信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

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

<style scoped>
/* 自定义样式可以根据需要添加 */
</style>
