<template>
  <!--
    金方导入弹窗（医生小程序）
    VIP：golden_formula；模板禁止 ?? ?. ；:class 禁止方法调用
  -->
  <u-popup
    v-model="show"
    mode="bottom"
    :closeable="true"
    @close="handleClose"
    :safe-area-inset-bottom="true"
    :mask-close-able="true"
    z-index="10078"
    height="82%"
  >
    <view class="gf-modal">
      <view class="gf-hd">
        <text class="fs-32 main-c font-bold">导入金方</text>
      </view>
      <view class="gf-search flex-row flex-ali-center">
        <u-input
          v-model="keyword"
          placeholder="名称/首拼/来源/速览"
          :clearable="true"
          :custom-style="{ background: '#f5f5f5', padding: '8rpx 16rpx' }"
          @confirm="onSearch"
        />
        <view class="gf-search-btn m-l-16" @click="onSearch">搜索</view>
      </view>
      <view class="gf-body flex-row">
        <scroll-view scroll-y class="gf-list">
          <view v-if="loading" class="p-24 color-sub fs-24">加载中…</view>
          <view v-else-if="!list.length" class="p-24 color-sub fs-24">暂无金方</view>
          <view
            v-for="item in list"
            :key="item.id"
            class="gf-item"
            :class="{ 'gf-item--on': selectedId == item.id }"
            :data-id="item.id"
            @click="onSelectTap"
          >
            <text class="fs-28 font-bold">{{ item.name }}</text>
            <text class="fs-22 color-sub m-t-8 line-clamp-2">{{ item.herb_overview || '—' }}</text>
            <text v-if="item.source" class="gf-source m-t-8">{{ item.source }}</text>
          </view>
        </scroll-view>
        <scroll-view scroll-y class="gf-match">
          <view v-if="applying" class="p-24 color-sub fs-24">对照中…</view>
          <view v-else-if="!matchResult" class="p-24 color-sub fs-24">请选择左侧金方</view>
          <block v-else>
            <text class="fs-28 font-bold">{{ matchResult.formula && matchResult.formula.name }}</text>
            <view class="m-t-12 fs-22">
              已匹配 {{ matchedCount }} · 未匹配 {{ unmatchedCount }}
            </view>
            <view
              v-if="matchResult.formula && matchResult.formula.original_formula"
              class="gf-original m-t-12"
            >
              <text class="fs-22 font-bold">原方：</text>
              <text class="fs-20 color-sub">{{ matchResult.formula.original_formula }}</text>
            </view>
            <!-- 非 H5 :key 仅支持简单变量，禁止字符串拼接表达式 -->
            <view
              v-for="(m, idx) in (matchResult.matched || [])"
              :key="idx"
              class="gf-row gf-row--ok"
            >
              <text class="fs-24">{{ m.show_dose || m.display_text || (m.ai_name + ' ' + (m.dose || '') + (m.unit || '')) }}</text>
              <text class="fs-22 color-sub">
                → {{ (m.candidates && m.candidates[0] && m.candidates[0].drug_name) || '—' }}
              </text>
            </view>
            <view
              v-for="(u, idx) in (matchResult.unmatched || [])"
              :key="idx"
              class="gf-row gf-row--miss"
            >
              <text class="fs-24">{{ u.show_dose || u.display_text || u.ai_name }}（未匹配）</text>
            </view>
            <view class="gf-footer">
              <u-button
                :throttle-time="0"
                shape="circle"
                :disabled="matchedCount <= 0"
                :custom-style="{ backgroundColor: '#6ACDBB', color: '#fff', height: '80rpx' }"
                @click="handleConfirm"
              >确认导入到处方</u-button>
            </view>
          </block>
        </scroll-view>
      </view>
    </view>
  </u-popup>
</template>

<script>
/**
 * 金方导入：列表检索 → 药名对照 → 确认导入（结构与 AI 出方 rows 一致）
 */
import {
  goldenFormulaListApi,
  goldenFormulaApplyApi,
} from '@/api/reception.js';

export default {
  name: 'GoldenFormulaModal',
  props: {
    value: { type: Boolean, default: false },
    storeId: { type: [Number, String], default: 0 },
    registerId: { type: [Number, String], default: 0 },
    /** 开方页 activeCategory：1中药 2西药 */
    prescriptionType: { type: Number, default: 1 },
  },
  data() {
    return {
      show: false,
      loading: false,
      applying: false,
      keyword: '',
      list: [],
      selectedId: 0,
      matchResult: null,
    };
  },
  computed: {
    matchedCount() {
      const m = this.matchResult && this.matchResult.matched;
      return Array.isArray(m) ? m.length : 0;
    },
    unmatchedCount() {
      const u = this.matchResult && this.matchResult.unmatched;
      return Array.isArray(u) ? u.length : 0;
    },
  },
  watch: {
    value: {
      immediate: true,
      handler(v) {
        this.show = !!v;
        if (v) {
          this.keyword = '';
          this.matchResult = null;
          this.selectedId = 0;
          this.loadList();
        }
      },
    },
    show(v) {
      if (!v && this.value) this.$emit('input', false);
    },
  },
  methods: {
    handleClose() {
      this.show = false;
      this.$emit('input', false);
    },
    onSearch() {
      this.loadList();
    },
    async loadList() {
      this.loading = true;
      this.matchResult = null;
      this.selectedId = 0;
      try {
        const res = await goldenFormulaListApi({
          keyword: this.keyword,
          page: 1,
          pageSize: 50,
          store_id: this.storeId || undefined,
        });
        this.list = (res && res.items) || [];
      } catch (e) {
        console.error(e);
        this.$toast((e && e.message) || '加载金方失败');
      } finally {
        this.loading = false;
      }
    },
    onSelectTap(e) {
      const id = Number((e.currentTarget && e.currentTarget.dataset && e.currentTarget.dataset.id) || 0);
      if (!id) return;
      this.handleSelect(id);
    },
    async handleSelect(id) {
      this.selectedId = id;
      this.applying = true;
      this.matchResult = null;
      try {
        // ProductType：中药1 / 西药2，与 activeCategory 对齐
        const pt = Number(this.prescriptionType) === 2 ? 2 : 1;
        const res = await goldenFormulaApplyApi({
          id,
          store_id: this.storeId || undefined,
          register_id: this.registerId || undefined,
          prescription_type: pt,
        });
        this.matchResult = res || null;
      } catch (e) {
        console.error(e);
        this.$toast((e && e.message) || '对照失败');
      } finally {
        this.applying = false;
      }
    },
    handleConfirm() {
      const matched = (this.matchResult && this.matchResult.matched) || [];
      if (!matched.length) {
        this.$toast('没有可导入的已匹配药品');
        return;
      }
      const rows = matched.map((m) => {
        const candidates = m.candidates || [];
        const selectedId = Number(m.selected_drug_id || 0);
        let candidate = candidates[0] || {};
        for (let i = 0; i < candidates.length; i++) {
          if (Number(candidates[i].drug_id) === selectedId) {
            candidate = candidates[i];
            break;
          }
        }
        return {
          ai_name: m.ai_name,
          dose: m.dose,
          unit: m.unit,
          usage: m.usage,
          frequency: m.frequency,
          candidate,
        };
      });
      this.$emit('import', {
        rows,
        formulaName: (this.matchResult.formula && this.matchResult.formula.name) || '',
      });
      const unmatched = (this.matchResult && this.matchResult.unmatched) || [];
      if (unmatched.length) {
        this.$toast('已导入 ' + rows.length + ' 味；未匹配 ' + unmatched.length + ' 味请手动补录');
      } else {
        this.$toast('已导入金方');
      }
      this.handleClose();
    },
  },
};
</script>

<style lang="scss" scoped>
.gf-modal {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 24rpx 24rpx 0;
  box-sizing: border-box;
}
.gf-hd {
  margin-bottom: 16rpx;
}
.gf-search {
  margin-bottom: 16rpx;
}
.gf-search-btn {
  flex-shrink: 0;
  padding: 12rpx 24rpx;
  background: #6acdbb;
  color: #fff;
  border-radius: 32rpx;
  font-size: 24rpx;
}
.gf-body {
  flex: 1;
  min-height: 0;
  overflow: hidden;
}
.gf-list {
  width: 40%;
  height: 100%;
  border-right: 1px solid #eee;
  padding-right: 12rpx;
  box-sizing: border-box;
}
.gf-match {
  width: 60%;
  height: 100%;
  padding-left: 16rpx;
  box-sizing: border-box;
}
.gf-item {
  padding: 16rpx;
  border: 1px solid #eee;
  border-radius: 12rpx;
  margin-bottom: 12rpx;
}
.gf-item--on {
  border-color: #6acdbb;
  background: rgba(106, 205, 187, 0.08);
}
.gf-source {
  display: inline-block;
  font-size: 20rpx;
  color: #b8860b;
  background: #fff8e6;
  padding: 2rpx 10rpx;
  border-radius: 6rpx;
}
.gf-row {
  margin-top: 12rpx;
  padding: 12rpx;
  border-radius: 8rpx;
}
.gf-row--ok {
  background: #f0faf7;
}
.gf-row--miss {
  background: #fff7e6;
}
.gf-original {
  max-height: 160rpx;
  overflow-y: auto;
  padding: 12rpx;
  background: #fff8e6;
  border-radius: 8rpx;
  line-height: 1.5;
}
.gf-footer {
  margin-top: 24rpx;
  padding-bottom: 24rpx;
}
.line-clamp-2 {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}
</style>
