<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="diagnosis-modal page-bg">
      <view class="modal-header white">
        <d-text text="常用诊断" className="fs-32 font-bold color-title"></d-text>
      </view>

      <view class="modal-content">
        <!-- 搜索框 -->
        <view class="search-box">
          <u-input
              v-model="searchKey"
              placeholder="请输入想要搜索的诊断名称..."
              :custom-style="searchStyle"
              @input="handleSearch"
              @clear="handleSearch"
          >
            <template slot="suffix">
              <u-icon name="search" size="32" color="#B0B6C2"></u-icon>
            </template>
          </u-input>
        </view>

        <scroll-view
            class="scroll-container"
            scroll-y
            @scrolltolower="loadMore"
            :lower-threshold="100"
        >
          <view class="scroll-body-pad">
            <!-- 常用诊断列表 -->
            <view class="section white radius-16 p-32 m-b-24 shadow-sm" v-if="doctorMyDiseaseList.length > 0">
              <view class="section-header flex-row flex-jus-sp flex-ali-center m-b-24">
                <d-text text="常用诊断" className="fs-30 font-bold color-title"></d-text>
                <d-text :text="`${doctorMyDiseaseList.length}项`" className="fs-26 color-sub"></d-text>
              </view>
              <view class="modern-tag-container">
                <view
                    v-for="item in doctorMyDiseaseList"
                    :key="item.id"
                    class="modern-tag-item"
                    :class="{ 'is-selected': item.disease.isSelect === 1 }"
                    @click="selectDiagnosis(item.disease)"
                >
                  <text class="tag-text">{{ item.disease.name }}</text>
                  <view class="tag-action" @click.stop="removeFromMyDiagnosis(item)">
                    <u-icon name="close" size="20"></u-icon>
                  </view>
                </view>
              </view>
            </view>

            <!-- 搜索结果列表 -->
            <view class="section white radius-16 p-32 shadow-sm" v-if="allDiagnosisList.length > 0">
              <view class="section-header flex-row flex-jus-sp flex-ali-center m-b-24">
                <d-text text="搜索结果" className="fs-30 font-bold color-title"></d-text>
                <d-text :text="`共 ${allDiagnosisList.length} 条`" className="fs-26 color-sub"></d-text>
              </view>
              <view class="modern-tag-container">
                <view
                    v-for="item in allDiagnosisList"
                    :key="item.id"
                    class="modern-tag-item"
                    :class="{ 'is-selected': item.isSelect === 1 }"
                    @click="selectDiagnosis(item)"
                >
                  <text class="tag-text">{{ item.name }}</text>
                  <view class="tag-action" @click.stop="addToMyDiagnosis(item)" v-if="!item.isInMyList">
                    <u-icon name="plus" size="20"></u-icon>
                  </view>
                  <view class="tag-action" v-else>
                    <u-icon name="checkmark" size="20"></u-icon>
                  </view>
                </view>
              </view>

              <!-- 加载更多 -->
              <view class="load-more" v-if="loading">
                <u-loading mode="circle" color="#00A88A"></u-loading> <text class="load-more-text m-l-12">加载中...</text>
              </view>
              <view class="load-more" v-else-if="!hasMore && allDiagnosisList.length > 0">
                <text class="load-more-text">没有更多了</text>
              </view>
            </view>

            <!-- 空状态 -->
            <view class="empty-state" v-if="allDiagnosisList.length === 0 && searchKey">
              <d-empty text="暂无相关诊断"></d-empty>
            </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="{
            backgroundColor: '#F4F6F8',
            color: '#2A2E35',
            height: '88rpx',
            width: '320rpx',
            fontWeight: 'bold',
            fontSize: '30rpx',
            border: 'none'
          }"
        >取消</u-button>
        <u-button
            :throttle-time="0"
            @click="handleConfirm"
            shape="circle"
            :custom-style="{
            backgroundColor: '#00A88A',
            color: '#fff',
            height: '88rpx',
            width: '320rpx',
            fontWeight: 'bold',
            fontSize: '30rpx',
            boxShadow: '0 8rpx 20rpx rgba(0, 168, 138, 0.25)',
            border: 'none'
          }"
        >确定</u-button>
      </view>
    </view>
  </u-popup>
</template>

<script>
// 保留所有原有逻辑代码与注释
import { getDiseaseList, getMyDiseaseList, addMyDisease, deleteMyDisease } from '@/api/reception.js';
import { getClinicSalespersonDiseaseList } from '@/api/clinicSalesperson.js';

export default {
  name: 'DiagnosisModal',
  props: {
    /**
     * 弹窗显示状态
     */
    value: {
      type: Boolean,
      default: false
    },
    /**
     * 已选中的诊断文本
     */
    selectedDiagnosis: {
      type: String,
      default: ''
    },
    salespersonTransferMode: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      show: false,
      searchKey: '',
      allDiagnosisList: [],
      doctorMyDiseaseList: [],
      selectDiagnosisList: '',
      currentPage: 1,
      pageSize: 20,
      hasMore: false,
      loading: false,
      searchTimer: null,
      searchStyle: {
        fontSize: '28rpx',
        backgroundColor: '#fff',
        borderRadius: '16rpx',
        height: '80rpx',
        padding: '0 32rpx',
        boxShadow: '0 4rpx 16rpx rgba(0,0,0,0.02)'
      }
    };
  },
  watch: {
    value(newVal) {
      this.show = newVal;
      if (newVal) {
        this.selectDiagnosisList = this.selectedDiagnosis || '';
        this.searchKey = '';
        this.allDiagnosisList = [];
        this.currentPage = 1;
        this.hasMore = false;
        if (!this.salespersonTransferMode) {
          this.loadDoctorMyDiseaseList();
        }
      }
    },
    show(newVal) {
      if (!newVal) {
        this.$emit('input', false);
      }
    }
  },
  methods: {
    /**
     * 加载诊断列表
     * @param {string} searchKey - 搜索关键词
     * @param {number} page - 页码
     * @param {boolean} append - 是否追加数据
     * 职责：调用接口获取诊断列表
     */
    async loadDiagnosisList(searchKey = '', page = 1, append = false) {
      try {
        let res;
        if (this.salespersonTransferMode) {
          const wrap = await getClinicSalespersonDiseaseList({
            name: searchKey,
            page,
            page_size: this.pageSize,
          });
          res = wrap && wrap.ok ? wrap.res : null;
        } else {
          res = await getDiseaseList(searchKey, page, this.pageSize);
        }
        let list = [];
        let hasMore = false;

        // 正确解析响应数据
        if (res && (res.code === 0 || res.errcode === 0)) {
          // 优先使用 data，然后是 result
          if (res.data && Array.isArray(res.data)) {
            list = res.data;
          } else if (res.result && Array.isArray(res.result)) {
            list = res.result;
          } else if (Array.isArray(res)) {
            list = res;
          }

          // 从响应中获取分页信息
          if (res.pagination) {
            hasMore = res.pagination.has_more || false;
          } else if (res.has_more !== undefined) {
            hasMore = res.has_more;
          } else {
            // 如果没有分页信息，根据返回数量判断
            hasMore = list.length >= this.pageSize;
          }
        }

        const processedList = list.map((item) => {
          item.isSelect = 0;
          item.isInMyList = this.doctorMyDiseaseList.some(
              (myItem) => myItem.disease && myItem.disease.id === item.id
          );
          if (this.selectDiagnosisList) {
            const valuesArr = this.selectDiagnosisList.split('，');
            valuesArr.forEach((value) => {
              if (value === item.name) {
                item.isSelect = 1;
              }
            });
          }
          return item;
        });

        if (append) {
          this.allDiagnosisList = [...this.allDiagnosisList, ...processedList];
        } else {
          this.allDiagnosisList = processedList;
          this.currentPage = 1;
        }

        this.hasMore = hasMore;
        this.loading = false;
      } catch (error) {
        console.error('获取诊断列表失败:', error);
        this.$toast('获取诊断列表失败');
        this.loading = false;
        this.hasMore = false;
      }
    },

    /**
     * 加载常用诊断列表
     * 职责：调用接口获取医生的常用诊断列表
     */
    async loadDoctorMyDiseaseList() {
      try {
        const res = await getMyDiseaseList();
        let list = [];

        // 正确解析响应数据
        if (res && (res.code === 0 || res.errcode === 0)) {
          if (res.data && Array.isArray(res.data)) {
            list = res.data;
          } else if (res.result && Array.isArray(res.result)) {
            list = res.result;
          } else if (Array.isArray(res)) {
            list = res;
          }
        }

        // 确保 list 是数组，避免 map 报错
        if (!Array.isArray(list)) {
          list = [];
        }

        this.doctorMyDiseaseList = list.map((item) => {
          // 确保 item.disease 存在
          if (item.disease) {
            item.disease.isSelect = 0;
            if (this.selectDiagnosisList) {
              const valuesArr = this.selectDiagnosisList.split('，');
              valuesArr.forEach((value) => {
                if (value === item.disease.name) {
                  item.disease.isSelect = 1;
                }
              });
            }
          }
          return item;
        });
      } catch (error) {
        console.error('获取常用诊断列表失败:', error);
        this.doctorMyDiseaseList = [];
      }
    },

    /**
     * 搜索诊断
     * 职责：防抖搜索，只在有输入时调用加载诊断列表
     */
    handleSearch() {
      clearTimeout(this.searchTimer);
      this.searchTimer = setTimeout(() => {
        if (this.searchKey && this.searchKey.trim()) {
          this.loading = true;
          this.currentPage = 1;
          this.allDiagnosisList = [];
          this.loadDiagnosisList(this.searchKey.trim(), 1, false);
        } else {
          // 清空搜索时，清空列表
          this.allDiagnosisList = [];
          this.currentPage = 1;
          this.hasMore = false;
        }
      }, 300);
    },

    /**
     * 触底加载更多
     * 职责：加载下一页数据
     */
    loadMore() {
      if (this.loading || !this.hasMore || !this.searchKey || !this.searchKey.trim()) {
        return;
      }
      this.loading = true;
      this.currentPage++;
      this.loadDiagnosisList(this.searchKey.trim(), this.currentPage, true);
    },

    /**
     * 选择诊断
     * @param {Object} item - 诊断项
     * 职责：切换诊断的选中状态，更新选中列表
     */
    selectDiagnosis(item) {
      let arr = this.selectDiagnosisList ? this.selectDiagnosisList.split('，').filter(Boolean) : [];

      if (item.isSelect === 1) {
        arr = arr.filter(name => name !== item.name);
        item.isSelect = 0;
      } else {
        if (!arr.includes(item.name)) {
          arr.push(item.name);
        }
        item.isSelect = 1;
      }

      this.selectDiagnosisList = arr.join('，');
    },

    /**
     * 添加到常用诊断
     * @param {Object} item - 诊断项
     * 职责：调用接口添加到常用诊断
     */
    async addToMyDiagnosis(item) {
      try {
        const res = await addMyDisease(item.id);
        if (res && (res.code === 0 || res.errcode === 0)) {
          this.$toast('已添加到常用诊断');
          await this.loadDoctorMyDiseaseList();
          item.isInMyList = true;
        } else {
          this.$toast(res.msg || res.message || '添加失败');
        }
      } catch (error) {
        console.error('添加常用诊断失败:', error);
        this.$toast('添加失败');
      }
    },

    /**
     * 从常用诊断中删除
     * @param {Object} item - 诊断项
     * 职责：调用接口从常用诊断中删除
     */
    async removeFromMyDiagnosis(item) {
      try {
        const res = await deleteMyDisease(item.id);
        if (res && (res.code === 0 || res.errcode === 0)) {
          this.$toast('已从常用诊断中移除');
          await this.loadDoctorMyDiseaseList();
          const searchItem = this.allDiagnosisList.find(d => d.id === item.disease.id);
          if (searchItem) {
            searchItem.isInMyList = false;
          }
        } else {
          this.$toast(res.msg || res.message || '删除失败');
        }
      } catch (error) {
        console.error('删除常用诊断失败:', error);
        this.$toast('删除失败');
      }
    },

    /**
     * 确认选择
     * 职责：触发确认事件，传递选中的诊断文本
     */
    handleConfirm() {
      this.$emit('confirm', this.selectDiagnosisList);
      this.handleClose();
    },

    /**
     * 关闭弹窗
     * 职责：关闭弹窗，触发input事件
     */
    handleClose() {
      this.show = false;
      this.$emit('input', false);
    }
  }
};
</script>

<style lang="scss" scoped>
/* 使用与 index.vue 统一的设计风格与变量 */
.page-bg { background-color: #F4F6F8; }
.white { background: #fff; }
.color-title { color: #2A2E35; }
.color-sub { color: #8A92A3; }
.fs-26 { font-size: 26rpx; }
.fs-28 { font-size: 28rpx; }
.fs-30 { font-size: 30rpx; }
.fs-32 { font-size: 32rpx; }
.font-bold { font-weight: bold; }
.m-b-24 { margin-bottom: 24rpx; }
.m-l-12 { margin-left: 12rpx; }
.p-32 { padding: 32rpx; }
.radius-16 { border-radius: 16rpx; }
.shadow-sm { box-shadow: 0 4rpx 16rpx rgba(42, 46, 53, 0.04); }
.shadow-up { box-shadow: 0 -4rpx 20rpx rgba(0,0,0,0.04); }

.flex-row { display: flex; flex-direction: row; }
.flex-jus-sp { justify-content: space-between; }
.flex-jus-between { justify-content: space-between; }
.flex-ali-center { align-items: center; }

.diagnosis-modal {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
  overflow: hidden;
}

.modal-header {
  padding: 32rpx;
  text-align: center;
  border-bottom: 1px solid #F0F2F5;
}

.modal-content {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding: 32rpx;
}

.scroll-container {
  flex: 1;
  min-height: 0;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.scroll-body-pad {
  padding-bottom: 140rpx;
}

.search-box {
  margin-bottom: 32rpx;
}

.modern-tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.modern-tag-item {
  display: inline-flex;
  align-items: center;
  padding: 12rpx 24rpx;
  background-color: #F7F8FA;
  border: 1px solid #E2E8F0;
  border-radius: 36rpx;
  cursor: pointer;
  transition: all 0.2s;

  &.is-selected {
    background-color: #E8F6F4;
    border-color: #00A88A;
    .tag-text {
      color: #00A88A;
      font-weight: bold;
    }
    .tag-action {
      color: #00A88A;
    }
  }

  .tag-text {
    font-size: 26rpx;
    color: #4b5563;
  }

  .tag-action {
    margin-left: 12rpx;
    display: flex;
    align-items: center;
    color: #8A92A3;
  }
}

.load-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 32rpx 0;
  .load-more-text {
    font-size: 24rpx;
    color: #999;
  }
}

.empty-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  text-align: center;
}

.modal-footer {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 32rpx calc(24rpx + env(safe-area-inset-bottom));
  background-color: #fff;
}
</style>