<script setup lang="ts">
import { computed, watch } from "vue";
import { DIALOG_WIDTH, LABEL_WIDTH } from "../../../constants/ui";

type ExpertManageTab = "bound" | "search";

const visible = defineModel<boolean>({ required: true });
const activeTab = defineModel<ExpertManageTab>("activeTab", { required: true });
const bindExpertKeyword = defineModel<string>("bindExpertKeyword", { required: true });
const currentSearchSelectedPlatformExpertIds = defineModel<number[]>("currentSearchSelectedPlatformExpertIds", { required: true });

const props = defineProps<{
  canMaterialSave: boolean;
  boundExpertRows: any[];
  selectedPlatformExpertIds: number[];
  selectedPlatformExpertNameMap: Record<number, string>;
  platformExpertSearched: boolean;
  platformExpertRows: any[];
  maskPhone: (value?: string) => string;
  maskIdNo: (value?: string) => string;
}>();

defineEmits<{
  loadPlatformExperts: [];
  removeSelectedPlatformExpert: [id: number];
  openCreatePlatformExpert: [];
  currentSearchExpertSelectChange: [checkedIds: Array<number | string>];
  bindExperts: [];
  unbindExpert: [row: any];
}>();

const selectedExpertCount = computed(() => props.selectedPlatformExpertIds.length);
const isReadonly = computed(() => !props.canMaterialSave);
const boundTabLabel = computed(() => `已绑定专家（${props.boundExpertRows.length}）`);
const searchTabLabel = computed(() =>
  selectedExpertCount.value > 0 ? `平台专家检索（已选${selectedExpertCount.value}）` : "平台专家检索",
);

watch(
  () => props.canMaterialSave,
  (canMaterialSave) => {
    if (!canMaterialSave && activeTab.value === "search") {
      activeTab.value = "bound";
    }
  },
  { immediate: true },
);
</script>

<template>
  <el-dialog v-model="visible" title="专家管理" :width="DIALOG_WIDTH.lg">
    <el-alert
      v-if="isReadonly"
      class="dialog-readonly-alert"
      title="当前会议资料审核中或已审核通过，仅支持查看已绑定专家。"
      type="warning"
      :closable="false"
      show-icon
    />
    <el-tabs v-model="activeTab">
      <el-tab-pane :label="boundTabLabel" name="bound">
        <el-empty v-if="boundExpertRows.length === 0" description="当前会议尚未绑定专家" />
        <el-table v-else :data="boundExpertRows">
          <el-table-column prop="expertName" label="专家姓名" width="140" />
          <el-table-column prop="phone" label="手机号" width="140" />
          <el-table-column prop="title" label="职称" width="140" />
          <el-table-column prop="organization" label="单位" />
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <el-button v-if="canMaterialSave" size="small" type="danger" @click="$emit('unbindExpert', row)">解绑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane :label="searchTabLabel" name="search" :disabled="isReadonly">
        <el-form :inline="true" class="search-toolbar">
          <el-form-item label="身份证号">
            <el-input v-model="bindExpertKeyword" placeholder="请输入身份证号" clearable @keyup.enter="$emit('loadPlatformExperts')" />
          </el-form-item>
          <el-form-item>
            <el-button @click="$emit('loadPlatformExperts')">查询</el-button>
          </el-form-item>
        </el-form>
        <el-form label-position="left" :label-width="LABEL_WIDTH.md">
          <el-form-item label="">
            <div class="w-full">
              <div v-if="selectedExpertCount > 0" class="selected-expert-summary">
                <span>已累计选择 {{ selectedExpertCount }} 位专家</span>
                <el-tag
                  v-for="id in selectedPlatformExpertIds"
                  :key="`selected-expert-${id}`"
                  size="small"
                  :closable="canMaterialSave"
                  @close="$emit('removeSelectedPlatformExpert', id)"
                >
                  {{ selectedPlatformExpertNameMap[id] || `专家#${id}` }}
                </el-tag>
              </div>
              <el-alert
                v-if="!platformExpertSearched"
                title="请先输入身份证号并点击“查询”，再选择要绑定到会议的专家。"
                type="info"
                :closable="false"
                show-icon
              />
              <el-empty
                v-else-if="platformExpertRows.length === 0"
                description="未查询到专家信息，请确认身份证号后重试"
              >
                <el-button v-if="canMaterialSave" type="primary" class="ml-sm" @click="$emit('openCreatePlatformExpert')">
                  新增专家
                </el-button>
              </el-empty>
              <template v-else>
                <el-checkbox-group
                  v-model="currentSearchSelectedPlatformExpertIds"
                  class="w-full"
                  @change="$emit('currentSearchExpertSelectChange', $event)"
                >
                  <el-row :gutter="10">
                    <el-col
                      v-for="item in platformExpertRows"
                      :key="item.id"
                      :span="8"
                      class="platform-expert-col"
                    >
                      <div class="platform-expert-item">
                        <el-checkbox :label="item.id" class="platform-expert-checkbox">
                          <div class="platform-expert-content">
                            <div class="platform-expert-header">
                              <div class="platform-expert-name">{{ item.expertName || "-" }}</div>
                              <el-tag size="small" effect="plain" type="info">{{ item.title || "未设置职称" }}</el-tag>
                            </div>
                            <div class="platform-expert-meta">
                              <div><span class="text-secondary">手机号：</span>{{ maskPhone(item.phone) }}</div>
                              <div><span class="text-secondary">身份证：</span>{{ maskIdNo(item.idNo) }}</div>
                              <div><span class="text-secondary">单位：</span>{{ item.organization || "-" }}</div>
                            </div>
                          </div>
                        </el-checkbox>
                      </div>
                    </el-col>
                  </el-row>
                </el-checkbox-group>
              </template>
            </div>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <el-button @click="visible = false">关闭</el-button>
      <el-button v-if="activeTab === 'search' && canMaterialSave" type="primary" @click="$emit('bindExperts')">保存绑定</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.dialog-readonly-alert {
  margin-bottom: 16px;
}

.search-toolbar {
  margin-bottom: 8px;
}

.selected-expert-summary {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
  color: #606266;
  font-size: 13px;
}

.platform-expert-col {
  margin-bottom: 10px;
}

.platform-expert-item {
  padding: 12px 14px;
  min-height: 100px;
  border-radius: 10px;
  border: 1px solid #e4e7ed;
  background: linear-gradient(180deg, #ffffff 0%, #fafcff 100%);
  box-shadow: 0 2px 8px rgba(31, 35, 41, 0.05);
  transition: all 0.2s ease;
  overflow: hidden;
}

.platform-expert-checkbox {
  width: 100%;
  align-items: flex-start;
}

.platform-expert-content {
  width: 100%;
  min-width: 0;
}

.platform-expert-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  margin-bottom: 8px;
  width: 100%;
  min-width: 0;
}

.platform-expert-name {
  flex: 1;
  min-width: 0;
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.platform-expert-meta {
  display: grid;
  grid-template-columns: 1fr;
  row-gap: 4px;
  color: #606266;
  font-size: 13px;
  line-height: 1.5;
}

:deep(.platform-expert-checkbox .el-checkbox__label) {
  display: inline-block;
  width: calc(100% - 20px);
  min-width: 0;
  padding-left: 8px;
  white-space: normal;
}
</style>
