<template>
  <!-- 查询医派协定方 -->
  <div class="prescription">
    <!-- 搜索条件 -->
    <div class="top-filter">
      <el-form label-position="right" label-width="70px" :model="form" inline>
        <el-form-item label="方名:">
          <el-input v-model="form.name" size="small" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="医派:">
          <el-select v-model="form.sectCategory" @change="onSectCategoryChange"
                     placeholder="请选择" size="small" clearable>
            <el-option v-for="item in sectCategoryList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="科室:">
          <el-select v-model="form.sectDept"
                     placeholder="请选择" size="small" clearable>
            <el-option v-for="item in sectDeptList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <!-- 共享至：多选 个人/科室/机构（同协定方弹窗） -->
        <el-form-item label="共享至:">
          <el-checkbox-group v-model="form.shareType" size="small">
            <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="small" type="primary" @click="searchDis">搜索</el-button>
      <el-button size="small" type="warning" @click="clearDis">清空</el-button>
    </div>
    <!-- 表格数据展示 -->
    <div class="table">
      <!-- 统建处方(医派协定方)表格 -->
      <el-table :data="tableData1" border style="width: 100%" @row-click="onRowClick">
        <el-table-column prop="sectCategory" label="医派" align="center" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column prop="sectDept" label="科室" align="center" width="120" show-overflow-tooltip></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>
        <!-- 共享状态：同协定方弹窗，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 { getEffectQuery } from "@/api/knowledge.js";
import { getSuitableTechList, getPreSectInfo, getSuitableTechInfo } from "@/api/technology.js";

export default {
  data() {
    return {
      // 医派信息 Map：key 为医派（'' 表示全部派别科室），value 为派别科室列表
      sectInfoMap: {},
      sectCategoryList: [], // 医派下拉项
      sectDeptList: [],     // 科室下拉项
      form: {
        name: "", // 方名
        sectCategory: '', // 医派
        sectDept: '', // 科室
        shareType: [], // 共享至（多选：0个人 1科室 2机构）
      },
      tableData1: [],
      currentPage: 1,
      total: 0
    };
  },
  created() {
    this.getEffectQuery();
    this.clearDis();
  },
  methods: {
    // 医派下拉变化：刷新科室列表
    onSectCategoryChange() {
      this.updateSectDeptList();
    },
    // 派别科室列表项归一化
    normalizeDept(dept) {
      if (dept == null) return null;
      if (typeof dept === 'string') return { label: dept, value: dept };
      const name = dept.name != null ? dept.name
        : dept.deptName != null ? dept.deptName
        : dept.sectDept != null ? dept.sectDept
        : '';
      return { label: name, value: name };
    },
    // 根据当前医派刷新科室下拉（未选医派 → '' 即全部派别科室）
    updateSectDeptList() {
      const key = this.form.sectCategory || '';
      const raw = this.sectInfoMap[key] || this.sectInfoMap[''] || [];
      this.sectDeptList = raw.map(d => this.normalizeDept(d)).filter(Boolean);
      // 当前选中科室已不在新列表中则清空
      if (!this.sectDeptList.find(d => d.value === this.form.sectDept)) {
        this.form.sectDept = '';
      }
    },
    // 获取医派信息
    async fetchSectInfo() {
      try {
        const res = await getPreSectInfo();
        this.sectInfoMap = (res && res.Data) ? res.Data : {};
        // 医派下拉
        this.sectCategoryList = Object.keys(this.sectInfoMap).filter(k => k !== '');
        this.updateSectDeptList();
      } catch (e) {
        console.error('获取医派信息失败', e);
        this.sectInfoMap = {};
        this.sectCategoryList = [];
        this.sectDeptList = [];
      }
    },
    resetForm() {
      this.form = {
        sectCategory: '', // 医派
        sectDept: '', // 科室
        name: "", // 方名
        shareType: [] // 共享至（多选：0个人 1科室 2机构）
      };
    },
    clearDis() {
      this.currentPage = 1;
      this.resetForm();
      this.fetchSectInfo();
      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 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);
    },
    // 点击行：通知父级打开顶层详情弹窗（医派协定方 → unify：标题「医派协定方」、底部展示医派+科室）
    onRowClick(row, column) {
      if (column && column.label === "操作") return;
      this.$emit("open-detail", row.pid, "unify");
    },
    // 获取方剂分类
    async getEffectQuery() {
      let res = await getEffectQuery({
        effecttype: "1",
        effictId: ""
      });
      if (res.code == 0) {
        // 预留：方剂分类
      }
    },
    //获取医派协定方列表（使用适宜技术列表接口，status=0, purposeType=0）
    async getAgreeRecipe() {
      let params = {
        status: 0,
        purposeType: 1,
        sectCategory: this.form.sectCategory || undefined,
        sectDept: this.form.sectDept || undefined,
        name: this.form.name || 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;
    }
  }
}

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