<template>
  <view class="customer-search-page">
    <view class="search-panel">

      <view class="form-row">
        <text class="form-label">姓名</text>
        <uv-input
          v-model="form.name"
          placeholder="请输入客户姓名"
          clearable
        />
      </view>
      <view class="form-row">
        <text class="form-label">手机号</text>
        <uv-input
          v-model="form.mobile"
          placeholder="请输入客户手机号"
          type="number"
          clearable
        />
      </view>
      <view class="form-row">
        <text class="form-label">微信号</text>
        <uv-input
          v-model="form.wechat"
          placeholder="请输入客户微信号"
          clearable
        />
      </view>
      <text class="form-tip">姓名 / 手机号 / 微信号至少填写一项</text>
      <view class="form-actions">
        <uv-button size="small" plain @click="handleReset">重置</uv-button>
        <uv-button
          size="small"
          type="primary"
          :disabled="!canSearch"
          @click="handleSearch"
        >
          搜索
        </uv-button>
      </view>
    </view>

    <view class="result-section">
      <view v-if="!hasSearched" class="result-placeholder">
        输入客户信息后点击搜索查看结果
      </view>

      <template v-else>
        <view
          class="customer-card"
          v-for="customer in list"
          :key="customer.id"
          @click="handleCustomerClick(customer)"
        >
          <CustomerSummaryBrief
            :name="customer.name"
            :intents="customer.intents"
            :status="customer.status"
            :show-edit="true"
            @edit="handleEdit(customer)"
          />

          <view class="customer-details">
            <view class="detail-row" v-if="customer.remark">
              <text class="detail-label">备注：</text>
              <text class="detail-value">{{ customer.remark || '--' }}</text>
            </view>

            <view class="detail-row" v-if="customer.mobile">
              <text class="detail-label">手机号：</text>
              <text class="detail-value">{{ customer.mobile || '--' }}</text>
            </view>

            <view
              class="detail-row"
              v-if="customer.lastFollowRecord && customer.lastFollowRecord.content"
            >
              <text class="detail-label">跟进内容：</text>
              <text class="detail-value follow-content">
                {{ truncateText(customer.lastFollowRecord.content, 30) }}
              </text>
            </view>

            <view class="detail-row" v-if="customer.nextFollowTime">
              <text class="detail-label">下次跟进：</text>
              <text class="detail-value">{{ formatDateTime(customer.nextFollowTime) }}</text>
            </view>

            <view class="detail-row" v-if="customer.followName">
              <text class="detail-label">跟进人：</text>
              <text class="detail-value">{{ customer.followName || '--' }}</text>
            </view>
          </view>

          <view class="action-buttons">
            <view class="action-item" @click.stop="handleFollowup(customer)">
              <text class="action-icon">✓</text>
              <text class="action-text">跟进</text>
            </view>
            <view class="action-item" @click.stop="handleTasks(customer)">
              <text class="action-icon">☰</text>
              <text class="action-text">任务</text>
            </view>
            <view class="action-item" @click.stop="handleCall(customer)">
              <text class="action-icon">☏</text>
              <text class="action-text">电话</text>
            </view>
            <view class="action-item" @click.stop="handleMore(customer)">
              <text class="action-icon">+</text>
              <text class="action-text">更多</text>
            </view>
          </view>
        </view>

        <view class="empty-state" v-if="isEmpty && !loading">
          <text class="empty-text">暂无匹配客户</text>
        </view>

        <view class="loading-state" v-if="loading && list.length === 0">
          <text class="loading-text">加载中...</text>
        </view>

        <view class="load-more" v-if="hasSearched && list.length > 0">
          <text class="load-more-text">
            {{ loading ? '加载中...' : (noMore ? '没有更多数据了' : '上拉加载更多') }}
          </text>
        </view>
      </template>
    </view>
  </view>
</template>

<script setup>
import { reactive, ref, computed, onMounted, onUnmounted } from 'vue';
import { onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app';
import CustomerSummaryBrief from '@/components/customer/CustomerSummaryBrief.vue';
import { getCustomerList, deleteCustomer } from '@/api/customer';
import { usePagination } from '@/composables/usePagination';

const PAGE_SIZE = 20;
const BASE_QUERY = {
  orderByColumn: 'createTime',
  isAsc: 'descending',

};

const form = reactive({
  name: '',
  mobile: '',
  wechat: ''
});

const hasSearched = ref(false);

const {
  list,
  loading,
  noMore,
  isEmpty,
  getList,
  loadMore,
  updateParams,
  reset,
  queryParams
} = usePagination({
  fetchData: getCustomerList,
  pageSize: PAGE_SIZE,
  defaultParams: {
    ...BASE_QUERY
  }
});

const toast = (message) => {
  if (uni?.$uv?.toast) {
    uni.$uv.toast(message);
  } else {
    uni.showToast({
      title: message,
      icon: 'none'
    });
  }
};

const sanitize = (value) => {
  if (!value) return undefined;
  const trimmed = value.trim();
  return trimmed.length ? trimmed : undefined;
};

const canSearch = computed(() =>
  Boolean(sanitize(form.name) || sanitize(form.mobile) || sanitize(form.wechat))
);

const handleSearch = () => {
  if (!canSearch.value) {
    toast('请输入姓名/手机号/微信号任意一项');
    return;
  }

  hasSearched.value = true;
  updateParams({
    ...BASE_QUERY,
    name: sanitize(form.name),
    mobile: sanitize(form.mobile),
    wechat: sanitize(form.wechat)
  });
};

const handleReset = () => {
  form.name = '';
  form.mobile = '';
  form.wechat = '';
  hasSearched.value = false;
  reset();
  queryParams.value = {
    pageNum: 1,
    pageSize: PAGE_SIZE,
    ...BASE_QUERY
  };
};

const truncateText = (text, maxLength) => {
  if (!text) return '--';
  if (text.length <= maxLength) return text;
  return `${text.substring(0, maxLength)}...`;
};

const formatDateTime = (dateTime) => {
  if (!dateTime) return '暂无';
  try {
    const date = new Date(dateTime);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  } catch (e) {
    return dateTime;
  }
};

const handleCustomerClick = (customer) => {
  uni.navigateTo({
    url: `/pages/customer/detail/index?id=${customer.id}`
  });
};

const handleEdit = (customer) => {
  uni.navigateTo({
    url: `/pages/customer/edit/index?id=${customer.id}`
  });
};

const handleFollowup = (customer) => {
  uni.navigateTo({
    url: `/pages/customer/follow/add/index?customerId=${customer.id}&customerName=${encodeURIComponent(customer.name || '')}`
  });
};

const handleTasks = (customer) => {
  uni.navigateTo({
    url: `/pages/customer-tasks/index?customerId=${customer.id}&customerName=${customer.name}`
  });
};

const handleCall = (customer) => {
  if (customer.mobile) {
    uni.makePhoneCall({
      phoneNumber: customer.mobile,
      fail: (err) => {
        console.error('拨打电话失败:', err);
        toast('拨打电话失败');
      }
    });
  } else {
    toast('客户未设置电话号码');
  }
};

const handleMore = (customer) => {
  uni.showActionSheet({
    itemList: ['编辑客户', '删除客户', '查看详情'],
    success: async (res) => {
      if (res.tapIndex === 0) {
        handleEdit(customer);
      } else if (res.tapIndex === 1) {
        uni.showModal({
          title: '确认删除',
          content: `确定要删除客户"${customer.name}"吗？`,
          success: async (modalRes) => {
            if (modalRes.confirm) {
              try {
                uni.showLoading({
                  title: '删除中...',
                  mask: true
                });
                await deleteCustomer(customer.id);
                uni.hideLoading();
                toast('删除成功');
                await getList(true);
              } catch (error) {
                uni.hideLoading();
                console.error('删除客户失败:', error);
                toast(error?.message || '删除失败，请重试');
              }
            }
          }
        });
      } else if (res.tapIndex === 2) {
        handleCustomerClick(customer);
      }
    }
  });
};

onPullDownRefresh(async () => {
  if (!hasSearched.value) {
    uni.stopPullDownRefresh();
    return;
  }

  try {
    await getList(true);
  } finally {
    uni.stopPullDownRefresh();
  }
});

onReachBottom(() => {
  if (hasSearched.value && !loading.value && !noMore.value) {
    loadMore();
  }
});

const handleCustomerListRefresh = () => {
  if (hasSearched.value) {
    getList(true);
  }
};

onMounted(() => {
  uni.$on('customerListRefresh', handleCustomerListRefresh);
});

onUnmounted(() => {
  uni.$off('customerListRefresh', handleCustomerListRefresh);
});
</script>

<style lang="scss" scoped>
.customer-search-page {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-bottom: 40px;
}

.search-panel {
  background-color: #fff;
  padding: 16px;
  margin: 12px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
}

.search-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
}

.form-row {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.form-label {
  width: 60px;
  font-size: 14px;
  color: #606266;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-bottom: 12px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.result-section {
  flex: 1;
}

.result-placeholder {
  margin: 80px auto;
  text-align: center;
  color: #909399;
  font-size: 14px;
}

.customer-card {
  background-color: #fff;
  border-radius: 12px;
  padding: 16px;
  margin: 0 12px 12px 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;

  &:active {
    transform: scale(0.98);
    box-shadow: 0 1px 6px rgba(0, 0, 0, 0.12);
  }
}

.customer-details {
  margin-top: 12px;
  margin-bottom: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f2f5;
}

.detail-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 8px;
  font-size: 14px;
  line-height: 1.5;

  &:last-child {
    margin-bottom: 0;
  }
}

.detail-label {
  color: #909399;
  margin-right: 8px;
  flex-shrink: 0;
  min-width: 70px;
}

.detail-value {
  color: #303133;
  flex: 1;
  word-break: break-all;
}

.action-buttons {
  display: flex;
  justify-content: space-around;
  align-items: center;
  border-top: 1px solid #f0f2f5;
  gap: 8px;
  padding-top: 12px;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  padding: 8px 12px;
  border-radius: 8px;
  flex: 1;
  transition: all 0.3s ease;

  &:active {
    background-color: #f5f7fa;
    transform: scale(0.95);
  }
}

.action-icon {
  font-size: 18px;
  color: #606266;
  font-weight: 500;
}

.action-text {
  font-size: 12px;
  color: #606266;
}

.empty-state {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 80px 20px;
}

.empty-text {
  font-size: 14px;
  color: #909399;
  margin-top: 12px;
}

.loading-state {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 60px 20px;
}

.loading-text {
  font-size: 14px;
  color: #909399;
}

.load-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  margin-bottom: 20px;
}

.load-more-text {
  font-size: 13px;
  color: #909399;
}
</style>

