<template>
  <!-- 查询协定方 -->
  <div class="prescription">
    <!-- 搜索条件 -->
    <div class="top-filter">
      <el-form label-position="right" label-width="80px" :model="form" inline>
        <el-form-item label="方名:">
          <el-input v-model="form.name" size="mini" placeholder="请输入"></el-input>
        </el-form-item>
        <!-- 中医病名：el-input + el-popover 自定义列表（参考 SuitableTech.vue） -->
        <el-form-item label="中医病名:">
          <el-popover placement="bottom" width="180" trigger="focus" :close-delay="100">
            <el-input
              size="mini"
              slot="reference"
              :placeholder="form.disName || '中医病名'"
              v-model="diseaseKey"
              ref="zybmInput"
              @input="getDiseaseList(diseaseKey)"
              @focus="handleFocusDisease"
              @keydown.enter.native="handleEnterDisease"
            >
              <div slot="suffix" class="suffix">
                <i class="el-icon-arrow-down" v-if="!diseaseKey"></i>
                <i class="el-icon-circle-close" v-else @click="clearDisease"></i>
              </div>
            </el-input>
            <ul class="option-list">
              <li
                v-for="item in diseaseList"
                :key="item.$uid"
                :class="{ active: form.disName === item.$name }"
                @click="handleSelectDisease(item)"
              >{{ item.$name }}</li>
            </ul>
          </el-popover>
        </el-form-item>
        <!-- 西医诊断：el-tag + el-autocomplete（参考 SuitableTech.vue） -->
        <el-form-item label="西医诊断:">
          <div class="western-disease-input-wrapper" @click="$refs.wdAutocomplete && $refs.wdAutocomplete.focus()">
            <el-tag
              v-for="code in westernCodes"
              :key="code"
              size="mini"
              closable
              @close="removeWesternDisease(code)"
            >{{ westernDiseaseNameMap[code] || code }}</el-tag>
            <el-autocomplete
              ref="wdAutocomplete"
              size="mini"
              popper-class="western-disease-select"
              v-model="westernDiseaseSearch"
              :fetch-suggestions="queryWesternDisease"
              value-key="westname"
              :placeholder="westernCodes.length ? '' : '请搜索选择'"
              clearable
              :trigger-on-focus="true"
              @select="onWesternDiseaseSelect"
              @visible-change="onWesternDiseaseVisible"
            >
              <template slot-scope="{ item }">
                <div :class="{ 'autocomplete-disabled': item._disabled }">
                  {{ item.westname }}
                </div>
              </template>
            </el-autocomplete>
          </div>
        </el-form-item>
        <!-- 共享至：多选 个人/科室/机构（可多选/单选/取消） -->
        <el-form-item label="共享至:">
          <el-checkbox-group v-model="form.shareType" size="mini">
            <el-checkbox label="0">个人</el-checkbox>
            <el-checkbox label="1">科室</el-checkbox>
            <el-checkbox label="2">机构</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <el-button size="mini" type="primary" @click="searchDis">搜索</el-button>
      <el-button size="mini" type="warning" @click="clearDis">清空</el-button>
    </div>
    <!-- 表格数据展示 -->
    <div class="table">
      <el-table :data="tableData1" border style="width: 100%" @row-click="onRowClick">
        <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
        <el-table-column prop="name" label="方名" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column prop="effect" label="功效与适应症" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column label="涵盖项目" align="center" show-overflow-tooltip>
          <template slot-scope="scope">{{ formatCoverage(scope.row) }}</template>
        </el-table-column>
        <el-table-column prop="provenance" label="处方出处" align="center" width="150" show-overflow-tooltip></el-table-column>
        <!-- 共享状态：参考 SuitableTech.vue，showType 0个人 1科室 2机构 -->
        <el-table-column prop="showType" label="共享状态" width="100" align="center">
          <template slot-scope="scope">
            <span>{{
              scope.row.showType === "0"
                ? "个人"
                : scope.row.showType === "1"
                ? "科室"
                : scope.row.showType === "2"
                ? "机构"
                : "-"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作" width="80" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleAgree(scope)">转方</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页数据 -->
    <div class="paging">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="10"
        :total="total"
        background
        layout=" prev, pager, next, jumper"
      ></el-pagination>
    </div>
  </div>
</template>
<script>
import { getSuitableTechList, getSuitableTechInfo } from "@/api/technology.js";
import { getDiseaseListMethod } from "@/request/api";
import { getXDiseaseName } from "@/api/knowledge.js";

export default {
  data() {
    return {
      // 中医病名
      diseaseList: [],
      diseaseKey: "", // 输入框搜索关键字
      // 西医诊断
      westernDiseaseSearch: "", // autocomplete 搜索关键字
      westernDiseaseOptions: [], // autocomplete 选项列表
      westernDiseaseNameMap: {}, // { westcode: westname }
      westernCodes: [], // 已选中的 westcode 数组
      westernDiseasePage: 1, // 分页页码
      westernDiseaseHasMore: true, // 是否还有更多
      westernDiseaseLoading: false, // 加载中
      // 表单
      form: {
        name: "", // 方名
        disName: "", // 中医病名
        westernCode: "", // 西医诊断码（逗号分隔）
        shareType: [], // 共享至（多选：0个人 1科室 2机构）
      },
      tableData1: [],
      currentPage: 1,
      total: 0
    };
  },
  created() {
    this.clearDis();
  },
  methods: {
    resetForm() {
      this.form = {
        name: "", // 方名
        disName: "", // 中医病名
        westernCode: "", // 西医诊断码
        shareType: [], // 共享至（多选：0个人 1科室 2机构）
      };
      this.diseaseKey = "";
      this.diseaseList = [];
      this.westernDiseaseSearch = "";
      this.westernDiseaseOptions = [];
      this.westernDiseaseNameMap = {};
      this.westernCodes = [];
    },
    clearDis() {
      this.currentPage = 1;
      this.resetForm();
      this.getAgreeRecipe();
    },
    handleCurrentChange(e) {
      this.currentPage = e;
      this.getAgreeRecipe();
    },
    searchDis() {
      this.currentPage = 1;
      this.getAgreeRecipe();
    },
    // 涵盖项目：遍历 treatmentList 取 treatItemName 拼接
    formatCoverage(row) {
      return (row.treatmentList || []).map(i => i.treatItemName).filter(Boolean).join("、");
    },
    async getDiseaseList(keyword = '') {
      const { list } = await getDiseaseListMethod(1, 9999, { keyword }).catch(() => ({ total: 0, list: [] }));
      this.diseaseList = list;
    },
    handleFocusDisease() {
      if (this.diseaseList.length === 0) this.getDiseaseList(this.diseaseKey);
    },
    handleSelectDisease(item) {
      this.form.disName = item.$name;
      this.diseaseKey = item.$name;
      this.$refs.zybmInput && this.$refs.zybmInput.blur();
    },
    clearDisease() {
      this.form.disName = "";
      this.diseaseKey = "";
      this.diseaseList = [];
    },
    handleEnterDisease() {
      if (this.diseaseList.length) {
        this.handleSelectDisease(this.diseaseList[0]);
      }
    },

    async queryWesternDisease(queryString, cb) {
      await this.searchWesternDisease(queryString);
      if (this.westernDiseaseOptions.length > 0) {
        cb(this.westernDiseaseOptions);
      } else {
        cb([{ westname: "暂无数据", _disabled: true }]);
      }
    },
    async searchWesternDisease(query) {
      this.westernDiseasePage = 1;
      this.westernDiseaseHasMore = true;
      this._wdQuery = query || "";
      this.westernDiseaseLoading = true;
      try {
        const pinyin = /^[A-Za-z]+$/g;
        const serchtype = query && pinyin.test(query) ? "1" : "";
        const res = await getXDiseaseName({
          pageid: 1,
          pagesize: 200,
          keyword: query || "",
          serchtype,
        });
        if (res.code == 0) {
          const list = res.data?.wests || [];
          // 保留已选中但不在搜索结果中的选项
          const resultCodes = new Set(list.map(i => i.westcode));
          const preserved = this.westernCodes
            .filter(code => !resultCodes.has(code))
            .map(code => ({
              westcode: code,
              westname: this.westernDiseaseNameMap[code] || code,
            }));
          this.westernDiseaseOptions = [...preserved, ...list];
          this.westernDiseaseHasMore = list.length >= 200;
          list.forEach(item => {
            if (item.westcode && item.westname) {
              this.westernDiseaseNameMap[item.westcode] = item.westname;
            }
          });
        }
      } catch (e) {
        console.error("搜索西医诊断失败", e);
      } finally {
        this.westernDiseaseLoading = false;
      }
    },
    // 滚动到底加载更多
    async loadMoreWesternDisease() {
      if (this.westernDiseaseLoading || !this.westernDiseaseHasMore) return;
      this.westernDiseasePage++;
      this.westernDiseaseLoading = true;
      try {
        const query = this._wdQuery || "";
        const pinyin = /^[A-Za-z]+$/g;
        const serchtype = query && pinyin.test(query) ? "1" : "";
        const res = await getXDiseaseName({
          pageid: this.westernDiseasePage,
          pagesize: 200,
          keyword: query,
          serchtype,
        });
        if (res.code == 0) {
          const list = res.data?.wests || [];
          this.westernDiseaseOptions = this.westernDiseaseOptions.concat(list);
          this.westernDiseaseHasMore = list.length >= 200;
          list.forEach(item => {
            if (item.westcode && item.westname) {
              this.westernDiseaseNameMap[item.westcode] = item.westname;
            }
          });
        }
      } catch (e) {
        console.error("加载更多西医诊断失败", e);
      } finally {
        this.westernDiseaseLoading = false;
      }
    },
    // 下拉显隐
    onWesternDiseaseVisible(show) {
      if (!show) {
        const wrap = document.querySelector(".western-disease-select .el-scrollbar__wrap");
        if (wrap && this._wdScroll) wrap.removeEventListener("scroll", this._wdScroll);
        return;
      }
      if (this.westernDiseaseOptions.length === 0) this.searchWesternDisease("");
      this.$nextTick(() => {
        const wrap = document.querySelector(".western-disease-select .el-scrollbar__wrap");
        if (wrap) {
          wrap.addEventListener("scroll", (this._wdScroll = () => {
            if (wrap.scrollHeight - wrap.scrollTop <= wrap.clientHeight + 5) {
              this.loadMoreWesternDisease();
            }
          }));
        }
      });
    },
    onWesternDiseaseSelect(item) {
      if (item._disabled) {
        this.$nextTick(() => { this.westernDiseaseSearch = ""; });
        return;
      }
      const code = String(item.westcode);
      if (!this.westernCodes.includes(code)) {
        this.westernCodes.push(code);
        this.westernDiseaseNameMap[code] = item.westname;
        this.updateWesternCode();
      }
      this.westernDiseaseSearch = "";
      this.$nextTick(() => { this.searchWesternDisease(""); });
    },
    removeWesternDisease(code) {
      this.westernCodes = this.westernCodes.filter(c => c !== code);
      this.updateWesternCode();
    },
    updateWesternCode() {
      this.form.westernCode = this.westernCodes.join(",");
    },

    async handleAgree(scope) {
      const row = scope.row;
      // 转方前取协定方详情，带出病名/证型/治法/西医诊断回填到开方页
      let info = {};
      try {
        const res = await getSuitableTechInfo(row.pid);
        if (res.ResultCode === 0) info = res.Data || {};
      } catch (e) {
        console.error('获取协定方详情失败', e);
      }
      const detail = {
        disName: info.disName || '',
        disId: info.disId || '',
        disCode: info.disCode || '',
        synName: info.synName || '',
        synId: info.synCode || '',
        synCode: info.synCode || '',
        theName: info.theName || '',
        theCode: info.theCode || '',
        westernCode: info.westernCode || '',
        westernDiag: info.westernDiag || '',
      };
      this.$emit('turn', row.pid, detail);
    },
    // 点击行：通知父级打开顶层协定方详情弹窗
    onRowClick(row, column) {
      if (column && column.label === "操作") return;
      this.$emit("open-detail", row.pid);
    },
    //获取协定方列表（使用适宜技术列表接口，status=0, purposeType=1）
    async getAgreeRecipe() {
      let params = {
        status: 0,
        purposeType: 0,
        name: this.form.name || undefined,
        disName: this.form.disName || undefined,
        westernCode: this.form.westernCode || undefined,
        showType: this.form.shareType.length ? this.form.shareType.join(',') : undefined,
        pageNum: this.currentPage,
        pageSize: 10
      };
      let res = await getSuitableTechList(params);
      if (res.ResultCode == 0) {
        this.total = res.Data?.totalRecordCount || 0;
        this.tableData1 = res.Data?.Items || [];
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.top-filter {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-bottom: 10px;
}

.top-filter {
  ::v-deep {
    .el-input__inner {
      width: 150px;
    }

    .el-form--inline .el-form-item {
      margin-bottom: 0;
    }
  }
}

.western-disease-input-wrapper {
  display: inline-flex;
  flex-wrap: wrap;
  align-items: center;
  width: 220px;
  min-height: 28px;
  box-sizing: border-box;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 0 15px;
  cursor: text;

  .el-tag {
    margin: 2px 4px 2px 0;
    max-width: 120px;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  ::v-deep .el-autocomplete {
    flex: 1;
    min-width: 60px;
  }
  ::v-deep .el-autocomplete .el-input__inner {
    border: none !important;
    padding: 0;
    height: 26px !important;
    line-height: 26px !important;
    width: 100% !important;
    background: transparent;
  }

  &:hover {
    border-color: #c0c4cc;
  }

  &:focus-within {
    border-color: #409eff;
  }
}

// autocomplete 暂无数据项置灰（参考 SuitableTech.vue）
.autocomplete-disabled {
  color: #999 !important;
  cursor: not-allowed !important;
  pointer-events: none;
}

// input suffix 图标（参考 SuitableTech.vue）
.suffix {
  height: 100%;
  padding-right: 5px;
  display: flex;
  align-items: center;

  i {
    cursor: pointer;
    color: #c0c4cc;
  }

  i:hover {
    color: #909399;
  }
}

// 下拉选项列表（中医病名 popover 内，参考 SuitableTech.vue）
.option-list {
  margin: -12px -12px;
  max-height: 300px;
  overflow: auto;
  padding: 0;
  list-style: none;

  li {
    padding: 8px 12px;
    box-sizing: border-box;
    width: 100%;
    font-size: 14px;
    color: #606266;
    font-weight: 500;
    cursor: pointer;

    &:hover {
      background: #f5f7fa;
    }
  }

  .active {
    color: #5386f6;
  }
}

.paging {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}
</style>

<style lang="scss">
.western-disease-select.el-autocomplete-suggestion {
  .el-autocomplete-suggestion__wrap {
    max-height: 200px;
  }
  .el-autocomplete-suggestion__list li {
    padding: 8px 12px;
    font-size: 14px;
    line-height: 20px;
  }
}
</style>
