<template>
  <el-dialog :model-value="modelValue" @update:model-value="$emit('update:modelValue', $event)" :title="title"
    width="560px" append-to-body class="select-client-dialog" @opened="onOpened">
    <div class="select-client-body">
      <div class="sc-selected-bar" v-if="localSelected.length > 0">
        <span class="sc-label">{{ selectedLabel }}</span>
        <el-tag v-for="(client, idx) in localSelected" :key="idx" closable size="default" @close="removeClient(idx)"
          class="sc-tag">
          {{ client.name }}
        </el-tag>
      </div>

      <div class="sc-search">
        <el-input v-model="keyword" :placeholder="searchPlaceholder" clearable size="large" class="sc-search-input"
          @keyup.enter="handleSearch">
          <template #prefix>
            <el-icon>
              <Search />
            </el-icon>
          </template>
        </el-input>
        <el-button type="primary" size="large" icon="Search" :loading="searchLoading" @click="handleSearch">
          搜索
        </el-button>
      </div>

      <div class="sc-results" v-if="searchResults.length > 0">
        <div v-for="item in searchResults" :key="item.rowId" class="sc-result-card"
          :class="{ 'is-selected': isSelected(item.rowId) }" @click="addClient(item)">
          <div class="sc-result-left">
            <div class="sc-result-avatar">{{ item.name?.charAt(0) }}</div>
            <div class="sc-result-info">
              <span class="sc-result-name">{{ item.name }}</span>
              <span class="sc-result-extra">{{ item.clientClass || '未分类' }}</span>
            </div>
          </div>
          <el-icon v-if="isSelected(item.rowId)" class="sc-result-selected">
            <CircleCheckFilled />
          </el-icon>
          <el-icon v-else class="sc-result-add">
            <CirclePlus />
          </el-icon>
        </div>
      </div>
      <el-empty v-else-if="searched" description="未找到匹配的客户" :image-size="60" />

      <div v-if="!searched && searchResults.length === 0" class="sc-placeholder">
        <el-icon class="sc-placeholder-icon">
          <Search />
        </el-icon>
        <p>{{ placeholderText }}</p>
      </div>
    </div>
    <template #footer>
      <div class="add-dialog-footer">
        <el-button size="large" icon="Close" @click="$emit('update:modelValue', false)">取 消</el-button>
        <el-button size="large" type="primary" icon="Check" :loading="confirmLoading" @click="$emit('confirm')">
          {{ confirmText }}（{{ localSelected.length }}）
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { ErpClientVO } from '@/api/erp/client/types';

const props = withDefaults(defineProps<{
  modelValue: boolean;
  title?: string;
  selectedLabel?: string;
  searchPlaceholder?: string;
  placeholderText?: string;
  confirmText?: string;
  selectedClients: ErpClientVO[];
  searchResults: ErpClientVO[];
  searchLoading?: boolean;
  confirmLoading?: boolean;
  searched?: boolean;
}>(), {
  title: '选择授权客户',
  selectedLabel: '已选',
  searchPlaceholder: '搜索客户名称',
  placeholderText: '输入客户名称进行搜索',
  confirmText: '确认选择',
  searchLoading: false,
  confirmLoading: false,
  searched: false
});

const emit = defineEmits<{
  'update:modelValue': [value: boolean];
  'update:selectedClients': [value: ErpClientVO[]];
  'search': [keyword: string];
  'confirm': [];
}>();

const keyword = ref('');
const localSelected = ref<ErpClientVO[]>([...props.selectedClients]);

watch(() => props.selectedClients, (val) => {
  localSelected.value = [...val];
}, { deep: true });

watch(() => props.modelValue, (val) => {
  if (!val) {
    keyword.value = '';
  }
});

const onOpened = () => {
  keyword.value = '';
  localSelected.value = [...props.selectedClients];
};

const handleSearch = () => {
  const kw = keyword.value?.trim();
  if (!kw) return;
  emit('search', kw);
};

const isSelected = (rowId: string) => {
  return localSelected.value.some(c => c.rowId === rowId);
};

const addClient = (client: ErpClientVO) => {
  if (isSelected(client.rowId)) return;
  localSelected.value.push({ ...client });
  emit('update:selectedClients', [...localSelected.value]);
};

const removeClient = (idx: number) => {
  localSelected.value.splice(idx, 1);
  emit('update:selectedClients', [...localSelected.value]);
};
</script>

<style scoped>
.select-client-dialog :deep(.el-dialog__header) {
  padding: 22px 24px 0;
  margin: 0;
}

.select-client-dialog :deep(.el-dialog__title) {
  font-size: 17px;
  font-weight: 600;
  color: #1a1a1a;
}

.select-client-dialog :deep(.el-dialog__body) {
  padding: 16px 24px 8px;
}

.select-client-body {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.sc-selected-bar {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
  padding: 10px 14px;
  background: #f9fafb;
  border-radius: 10px;
  min-height: 42px;
}

.sc-label {
  font-size: 12px;
  color: #909399;
  font-weight: 500;
  flex-shrink: 0;
}

.sc-tag {
  border-radius: 16px;
  padding: 4px 14px;
  font-size: 13px;
}

.sc-search {
  display: flex;
  gap: 10px;
}

.sc-search-input {
  flex: 1;
}

.sc-search-input :deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 0 0 1px #e4e7ed inset;
}

.sc-search-input :deep(.el-input--large.is-focus .el-input__wrapper) {
  box-shadow: 0 0 0 1px #409eff inset, 0 0 0 3px rgba(64, 158, 255, 0.08);
}

.sc-search .el-button {
  border-radius: 8px;
  padding: 0 24px;
}

.sc-results {
  display: flex;
  flex-direction: column;
  gap: 6px;
  max-height: 300px;
  overflow-y: auto;
}

.sc-result-card {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  border-radius: 10px;
  border: 1px solid #f0f0f0;
  cursor: pointer;
  transition: all 0.2s;
}

.sc-result-card:hover {
  background: #f5f8ff;
  border-color: #d4e2ff;
}

.sc-result-card.is-selected {
  background: #f0f5ff;
  border-color: #bdd3ff;
}

.sc-result-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.sc-result-avatar {
  width: 40px;
  height: 40px;
  border-radius: 10px;
  background: linear-gradient(135deg, #409eff, #3370ff);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: 600;
  flex-shrink: 0;
}

.sc-result-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.sc-result-name {
  font-size: 14px;
  font-weight: 500;
  color: #1a1a1a;
}

.sc-result-extra {
  font-size: 12px;
  color: #909399;
}

.sc-result-add {
  font-size: 20px;
  color: #c0c4cc;
  transition: color 0.2s;
}

.sc-result-card:hover .sc-result-add {
  color: #409eff;
}

.sc-result-selected {
  font-size: 20px;
  color: #409eff;
}

.sc-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48px 0;
  color: #c0c4cc;
}

.sc-placeholder-icon {
  font-size: 40px;
  margin-bottom: 12px;
}

.sc-placeholder p {
  margin: 0;
  font-size: 13px;
  color: #b0b5be;
}

.add-dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 4px;
}

.add-dialog-footer .el-button {
  border-radius: 8px;
  padding: 10px 28px;
  font-size: 14px;
  font-weight: 500;
  letter-spacing: 0.5px;
}

.add-dialog-footer .el-button--primary {
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.25);
}

.add-dialog-footer .el-button--primary:hover {
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.35);
}
</style>
