<template>
  <u-popup
      v-model="show"
      mode="bottom"
      :closeable="true"
      @close="handleClose"
      :safe-area-inset-bottom="true"
      :mask-close-able="true"
      z-index="10078"
      height="80%"
  >
    <view class="tcm-term-modal page-bg">
      <view class="modal-header white">
        <d-text :text="titleText" className="fs-32 font-bold color-title"></d-text>
      </view>

      <view class="modal-content">
        <view class="search-box m-b-24">
          <u-input
              v-model="searchKey"
              placeholder="请输入关键词搜索（名称/别名/拼音首字母）"
              :custom-style="searchStyle"
              @input="onSearchInput"
              @clear="onSearchClear"
          >
            <template slot="suffix">
              <u-icon name="search" size="32" color="#B0B6C2"></u-icon>
            </template>
          </u-input>
        </view>

        <scroll-view class="list-scroll" scroll-y :scroll-top="scrollTop">
          <view v-if="!searchKeyTrim" class="hint-wrap">
            <text class="fs-26 color-sub">请输入关键词筛选术语（数据量较大）</text>
          </view>
          <view v-else-if="displayedList.length === 0" class="hint-wrap">
            <d-empty text="无匹配结果"></d-empty>
          </view>
          <view v-else class="tag-container">
            <view
                v-for="item in displayedList"
                :key="item.id"
                class="term-tag"
                :class="{ 'is-selected': Number(pendingId) === Number(item.id) }"
                @click="handlePick(item)"
            >
              <text class="tag-text">{{ item.name }}</text>
              <text v-if="item.alias" class="tag-alias">{{ item.alias }}</text>
            </view>
          </view>
        </scroll-view>
      </view>

      <view class="modal-footer flex-row flex-jus-between flex-ali-center white shadow-up">
        <u-button
            :throttle-time="0"
            @click="handleClose"
            shape="circle"
            :custom-style="btnGhost"
        >取消</u-button>
        <u-button
            :throttle-time="0"
            @click="handleConfirm"
            shape="circle"
            :custom-style="btnPrimary"
        >确定</u-button>
      </view>
    </view>
  </u-popup>
</template>

<script>
export default {
  name: 'TraditionalTermPickerModal',
  props: {
    value: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '请选择'
    },
    /** 当前字段已选 id（用于高亮） */
    selectedId: {
      type: [Number, String],
      default: null
    },
    /** 当前分类下的完整选项列表 */
    options: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      show: false,
      searchKey: '',
      searchTimer: null,
      pendingId: null,
      scrollTop: 0,
      searchStyle: {
        fontSize: '28rpx',
        backgroundColor: '#fff',
        borderRadius: '16rpx',
        height: '80rpx',
        padding: '0 32rpx',
        boxShadow: '0 4rpx 16rpx rgba(0,0,0,0.02)'
      },
      btnGhost: {
        backgroundColor: '#F4F6F8',
        color: '#2A2E35',
        height: '88rpx',
        width: '320rpx',
        fontWeight: 'bold',
        fontSize: '30rpx',
        border: 'none'
      },
      btnPrimary: {
        backgroundColor: '#00A88A',
        color: '#fff',
        height: '88rpx',
        width: '320rpx',
        fontWeight: 'bold',
        fontSize: '30rpx',
        boxShadow: '0 8rpx 20rpx rgba(0, 168, 138, 0.25)',
        border: 'none'
      }
    };
  },
  computed: {
    titleText() {
      return this.title || '请选择';
    },
    searchKeyTrim() {
      return (this.searchKey || '').trim();
    },
    displayedList() {
      const key = this.searchKeyTrim.toLowerCase();
      if (!key) return [];
      const all = this.options || [];
      const out = [];
      const max = 400;
      for (let i = 0; i < all.length && out.length < max; i++) {
        const it = all[i];
        if (!it) continue;
        const name = (it.name || '').toLowerCase();
        const alias = (it.alias || '').toLowerCase();
        const py = (it.initials_of_pinyin || '').toLowerCase();
        if (name.includes(key) || alias.includes(key) || py.includes(key)) {
          out.push(it);
        }
      }
      return out;
    }
  },
  watch: {
    value(newVal) {
      this.show = newVal;
      if (newVal) {
        this.searchKey = '';
        this.pendingId = this.selectedId != null && this.selectedId !== '' ? Number(this.selectedId) : null;
        this.scrollTop = 0;
      }
    },
    show(newVal) {
      if (!newVal) {
        this.$emit('input', false);
      }
    }
  },
  methods: {
    onSearchInput() {
      if (this.searchTimer) clearTimeout(this.searchTimer);
      this.searchTimer = setTimeout(() => {
        this.scrollTop = 0;
      }, 80);
    },
    onSearchClear() {
      this.searchKey = '';
      this.scrollTop = 0;
    },
    handlePick(item) {
      if (!item || item.id == null) return;
      this.pendingId = Number(item.id);
    },
    handleConfirm() {
      if (this.pendingId == null || Number.isNaN(this.pendingId)) {
        uni.showToast({ title: '请先选择一项', icon: 'none' });
        return;
      }
      this.$emit('confirm', this.pendingId);
      this.show = false;
    },
    handleClose() {
      this.show = false;
    }
  }
};
</script>

<style scoped lang="scss">
.tcm-term-modal {
  min-height: 60vh;
}
.modal-header {
  padding: 32rpx;
  border-bottom: 1rpx solid #eef0f3;
}
.modal-content {
  padding: 24rpx 32rpx 0;
}
.list-scroll {
  height: 52vh;
}
.hint-wrap {
  padding: 80rpx 32rpx;
  text-align: center;
}
.tag-container {
  display: flex;
  flex-wrap: wrap;
  padding-bottom: 24rpx;
}
.term-tag {
  margin: 0 16rpx 16rpx 0;
  padding: 16rpx 24rpx;
  border-radius: 40rpx;
  background: #f4f6f8;
  border: 2rpx solid transparent;
  max-width: 100%;
}
.term-tag.is-selected {
  background: #e8f6f4;
  border-color: #6acdbb;
}
.tag-text {
  font-size: 28rpx;
  color: #333;
}
.tag-alias {
  display: block;
  font-size: 22rpx;
  color: #999;
  margin-top: 4rpx;
}
.modal-footer {
  padding: 24rpx 32rpx calc(24rpx + env(safe-area-inset-bottom));
  border-top: 1rpx solid #eef0f3;
}
</style>
