<template>
  <div class="mobile-page">
    <!-- 搜索头部 -->
    <div class="mobile-page__header">
      <div class="mobile-page__search">
        <el-input
          v-model="queryParams.name"
          placeholder="搜索线索名称"
          clearable
          @keyup.enter="handleQuery"
          :prefix-icon="Search"
        />
        <el-button type="primary" :icon="Filter" @click="filterDrawerVisible = true" />
      </div>
      <div class="mobile-page__actions">
        <el-button type="primary" @click="openForm('create')" v-hasPermi="['crm:clue:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['crm:clue:export']"
        >
          导出
        </el-button>
      </div>
    </div>

    <!-- Tab 切换 -->
    <div class="mobile-page__tabs">
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="我负责的" name="1" />
        <el-tab-pane label="我参与的" name="2" />
        <el-tab-pane label="下属负责的" name="3" />
      </el-tabs>
    </div>

    <!-- 线索列表 -->
    <div class="mobile-page__content" v-loading="loading">
      <div class="mobile-item-list">
        <div
          v-for="item in list"
          :key="item.id"
          class="mobile-item-card mobile-item-card--clickable"
          @click="openDetail(item.id)"
        >
          <div class="mobile-item-card__header">
            <span class="mobile-item-card__name">{{ item.name }}</span>
            <el-tag v-if="item.transformStatus" type="success" size="small">已转化</el-tag>
            <el-tag v-else type="info" size="small">未转化</el-tag>
          </div>
          <div class="mobile-item-card__body">
            <div class="mobile-item-card__info-row">
              <span class="mobile-item-card__info-label">线索来源</span>
              <span class="mobile-item-card__info-value">
                <dict-tag :type="DICT_TYPE.CRM_CUSTOMER_SOURCE" :value="item.source" />
              </span>
            </div>
            <div class="mobile-item-card__info-row">
              <span class="mobile-item-card__info-label">手机</span>
              <span class="mobile-item-card__info-value">{{ item.mobile || '-' }}</span>
            </div>
            <div class="mobile-item-card__info-row">
              <span class="mobile-item-card__info-label">负责人</span>
              <span class="mobile-item-card__info-value">{{ item.ownerUserName || '-' }}</span>
            </div>
            <div class="mobile-item-card__info-row">
              <span class="mobile-item-card__info-label">客户级别</span>
              <span class="mobile-item-card__info-value">
                <dict-tag :type="DICT_TYPE.CRM_CUSTOMER_LEVEL" :value="item.level" />
              </span>
            </div>
            <div class="mobile-item-card__info-row">
              <span class="mobile-item-card__info-label">最后跟进</span>
              <span class="mobile-item-card__info-value">{{ item.contactLastTime ? dateFormatter(null, null, item.contactLastTime) : '-' }}</span>
            </div>
          </div>
          <div class="mobile-item-card__footer" @click.stop>
            <el-button
              size="small"
              type="primary"
              @click="openForm('update', item.id)"
              v-hasPermi="['crm:clue:update']"
            >编辑</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(item.id)"
              v-hasPermi="['crm:clue:delete']"
            >删除</el-button>
          </div>
        </div>
        <div v-if="list.length === 0 && !loading" class="mobile-empty-tip">暂无线索数据</div>
      </div>
      <!-- 分页 -->
      <div class="mobile-pagination" v-if="total > 0">
        <el-pagination
          v-model:current-page="queryParams.pageNo"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          :page-sizes="[10, 20]"
          layout="total, prev, pager, next"
          :pager-count="5"
          @size-change="getList"
          @current-change="getList"
        />
      </div>
    </div>
  </div>

  <!-- 筛选抽屉 -->
  <el-drawer
    v-model="filterDrawerVisible"
    title="筛选条件"
    direction="rtl"
    size="100%"
    :append-to-body="true"
    class="mobile-form-drawer"
  >
    <div class="mobile-form">
      <div class="mobile-form__section">
        <div class="mobile-form__section-title">筛选条件</div>
        <el-form :model="queryParams" ref="queryFormRef" label-position="top">
          <el-form-item label="线索名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入线索名称" clearable />
          </el-form-item>
          <el-form-item label="转化状态" prop="transformStatus">
            <el-select v-model="queryParams.transformStatus" style="width: 100%">
              <el-option :value="false" label="未转化" />
              <el-option :value="true" label="已转化" />
            </el-select>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="queryParams.mobile" placeholder="请输入手机号" clearable />
          </el-form-item>
          <el-form-item label="电话" prop="telephone">
            <el-input v-model="queryParams.telephone" placeholder="请输入电话" clearable />
          </el-form-item>
        </el-form>
      </div>
      <div class="mobile-form__footer">
        <el-button @click="resetQuery" style="flex: 1">重置</el-button>
        <el-button type="primary" @click="handleFilterConfirm" style="flex: 1">确认</el-button>
      </div>
    </div>
  </el-drawer>

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

<script setup lang="ts">
import { DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import * as ClueApi from '@/api/crm/clue'
import ClueForm from './ClueForm.vue'
import { TabsPaneContext } from 'element-plus'
import { Search, Filter } from '@element-plus/icons-vue'

defineOptions({ name: 'CrmClue' })

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

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const filterDrawerVisible = ref(false) // 筛选抽屉
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  sceneType: '1', // 默认和 activeName 相等
  name: null,
  telephone: null,
  mobile: null,
  transformStatus: false
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const activeName = ref('1') // 列表 tab

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ClueApi.getCluePage(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()
}

/** tab 切换 */
const handleTabClick = (tab: TabsPaneContext) => {
  queryParams.sceneType = tab.paneName
  handleQuery()
}

/** 打开线索详情 */
const { push } = useRouter()
const openDetail = (id: number) => {
  push({ name: 'CrmClueDetail', params: { id } })
}

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

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

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

/** 筛选确认 */
const handleFilterConfirm = () => {
  filterDrawerVisible.value = false
  handleQuery()
}

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

<style lang="scss" scoped>
.mobile-page {
  padding: 12px;
  background: #f5f7fa;
  min-height: 100vh;
}
.mobile-page__header {
  margin-bottom: 12px;
}
.mobile-page__search {
  display: flex;
  gap: 8px;
  margin-bottom: 10px;
}
.mobile-page__actions {
  display: flex;
  gap: 8px;
}
.mobile-page__tabs {
  background: #fff;
  border-radius: 10px;
  padding: 0 12px;
  margin-bottom: 12px;
}
.mobile-page__content {
  min-height: 200px;
}
.mobile-item-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.mobile-item-card {
  background: #fff;
  border-radius: 10px;
  padding: 12px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
  &--clickable {
    cursor: pointer;
    transition: all 0.2s;
    &:active {
      background: #f5f5f5;
    }
  }
  &__header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 10px;
    padding-bottom: 8px;
    border-bottom: 1px solid #f0f0f0;
  }
  &__name {
    flex: 1;
    font-size: 15px;
    font-weight: 600;
    color: #303133;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  &__body {
    font-size: 13px;
  }
  &__info-row {
    display: flex;
    justify-content: space-between;
    padding: 4px 0;
  }
  &__info-label {
    color: #909399;
    flex-shrink: 0;
  }
  &__info-value {
    color: #606266;
    text-align: right;
  }
  &__footer {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    margin-top: 10px;
    padding-top: 10px;
    border-top: 1px solid #f0f0f0;
  }
}
.mobile-empty-tip {
  text-align: center;
  color: #909399;
  padding: 40px 0;
  font-size: 14px;
}
.mobile-pagination {
  margin-top: 12px;
  display: flex;
  justify-content: center;
  :deep(.el-pagination) {
    flex-wrap: wrap;
    justify-content: center;
  }
}
.mobile-form {
  padding: 0 4px;
}
.mobile-form__section {
  background: #fff;
  border-radius: 10px;
  padding: 14px;
  margin-bottom: 12px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
}
.mobile-form__section-title {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}
.mobile-form__footer {
  position: sticky;
  bottom: 0;
  background: #fff;
  padding: 12px 16px;
  padding-bottom: calc(12px + constant(safe-area-inset-bottom));
  padding-bottom: calc(12px + env(safe-area-inset-bottom));
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  z-index: 10;
  margin: 0 -4px;
}
</style>
