<template>
  <div class="recipe-acupoint-wrapper">
    <!-- 处方 tab 切换 -->
    <div class="prescription-tabs" v-if="treatmentList.length">
      <div
        class="tab-item"
        :class="{ active: activeIndex === index }"
        v-for="(item, index) in treatmentList"
        :key="index"
        @click="activeIndex = index"
      >
        <el-tooltip :content="item.treatItemName" placement="top" :open-delay="300">
          <span class="tab-name">{{ item.treatItemName }}</span>
        </el-tooltip>
      </div>
    </div>

    <div class="recipe-acupoint" v-if="activeTreatment">
      <!-- 工具栏 -->
      <div
        class="table-toolbar flex-vertical-center-l flex-wrap"
        v-if="treatmentList.length"
      >
        <div class="toolbar-item flex-vertical-center-l">
          <span>是否可修改：</span>
          <span class="readonly-text">{{ activeIsEditable }}</span>
        </div>
        <div class="toolbar-item flex-vertical-center-l">
          <span>详情：</span>
          <el-checkbox-group v-model="activeDetailTypes" size="mini" disabled>
            <el-checkbox label="穴位" disabled>穴位</el-checkbox>
            <el-checkbox label="经络" disabled>经络</el-checkbox>
            <el-checkbox label="耳穴" disabled>耳穴</el-checkbox>
            <el-checkbox label="部位" disabled>部位</el-checkbox>
            <el-checkbox label="其他详情" disabled>其他详情</el-checkbox>
            <el-checkbox label="无详情" disabled>无详情</el-checkbox>
          </el-checkbox-group>
        </div>
      </div>

      <div class="table-container">
        <!-- 动态详情表格区域 -->
        <div
          v-for="detailType in displayDetailTypes"
          :key="detailType"
          class="detail-table-section"
        >
          <div class="detail-section-label" v-if="treatmentList.length">
            {{ detailType }}
          </div>
          <!-- 左右表格 -->
          <div class="table-show flex-vertical-between">
            <!-- 左侧表格 -->
            <div class="table-left">
              <el-table
                :data="getLeftList(detailType)"
                border
                size="mini"
                style="width: 100%"
              >
                <el-table-column
                  prop="id"
                  label="序号"
                  width="50"
                  align="center"
                ></el-table-column>
                <el-table-column :label="detailType" min-width="100">
                  <template slot-scope="scope">
                    {{ scope.row.name || "-" }}
                  </template>
                </el-table-column>
                <el-table-column label="数量" width="60" align="center">
                  <template slot-scope="scope">
                    {{ scope.row.count || 1 }}
                  </template>
                </el-table-column>
                <el-table-column label="备注" min-width="80">
                  <template slot-scope="scope">
                    {{ scope.row.remark || "-" }}
                  </template>
                </el-table-column>
                <el-table-column
                  label="主配穴"
                  width="80"
                  align="center"
                  v-if="detailType === '穴位'"
                >
                  <template slot-scope="scope">
                    {{
                      scope.row.mainType === "1"
                        ? "主穴"
                        : scope.row.mainType === "2"
                        ? "配穴"
                        : "-"
                    }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="60" fixed="right">
                  <template slot-scope="scope" v-if="scope.row.name">
                    <div class="operate">
                      <img
                        v-if="
                          detailType !== '其他详情' && detailType !== '部位'
                        "
                        src="~@/assets/find.png"
                        alt
                        @click="find(scope, detailType)"
                      />
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <!-- 右侧表格 -->
            <div class="table-left">
              <el-table
                :data="getRightList(detailType)"
                border
                size="mini"
                style="width: 100%"
              >
                <el-table-column
                  prop="id"
                  label="序号"
                  width="50"
                  align="center"
                ></el-table-column>
                <el-table-column :label="detailType" min-width="100">
                  <template slot-scope="scope">
                    {{ scope.row.name || "-" }}
                  </template>
                </el-table-column>
                <el-table-column label="数量" width="60" align="center">
                  <template slot-scope="scope">
                    {{ scope.row.count || 1 }}
                  </template>
                </el-table-column>
                <el-table-column label="备注" min-width="80">
                  <template slot-scope="scope">
                    {{ scope.row.remark || "-" }}
                  </template>
                </el-table-column>
                <el-table-column
                  label="主配穴"
                  width="80"
                  align="center"
                  v-if="detailType === '穴位'"
                >
                  <template slot-scope="scope">
                    {{
                      scope.row.mainType === "1"
                        ? "主穴"
                        : scope.row.mainType === "2"
                        ? "配穴"
                        : "-"
                    }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="60" fixed="right">
                  <template slot-scope="scope" v-if="scope.row.name">
                    <div class="operate">
                      <img
                        v-if="
                          detailType !== '其他详情' && detailType !== '部位'
                        "
                        src="~@/assets/find.png"
                        alt
                        @click="find(scope, detailType)"
                      />
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部统计 -->
      <div class="table-bottom">
        <div class="table-b-header">
          <div class="header-about">
            <div
              class="item flex-vertical-center-l"
              style="align-items: flex-start;"
              v-if="showGuide"
            >
              <span>配穴指南：</span>
              <div style="flex: 1;">
                <el-input
                  size="mini"
                  placeholder="-"
                  :value="activeTreatment.pointMatchGuide"
                  type="textarea"
                  autosize
                  disabled
                ></el-input>
              </div>
            </div>
            <div
              class="item flex-vertical-center-l"
              style="align-items: flex-start;"
            >
              <span>操作指南：</span>
              <div style="flex: 1;">
                <el-input
                  size="mini"
                  placeholder="-"
                  v-model="activeTreatment.useExplain"
                  type="textarea"
                  autosize
                  disabled
                ></el-input>
              </div>
            </div>
          </div>
          <div class="header-about">
            <div class="stat-row flex-vertical-center-l flex-wrap">
              <div class="stat-field flex-vertical-center-l">
                <span>单次：</span>
                <el-input-number
                  size="mini"
                  v-model="activeTreatment.singleQty"
                  :min="0"
                  :controls="false"
                  style="width: 60px"
                  disabled
                ></el-input-number>
              </div>
              <div class="stat-field flex-vertical-center-l">
                <span>治疗次数：</span>
                <el-input-number
                  size="mini"
                  v-model="activeTreatment.treatNum"
                  :min="0"
                  :controls="false"
                  style="width: 60px"
                  disabled
                ></el-input-number>
              </div>
              <div class="stat-field flex-vertical-center-l">
                <span>频次：</span>
                <el-input-number
                  size="mini"
                  v-model="parsedFreqDays"
                  :min="0"
                  :controls="false"
                  style="width: 60px"
                  disabled
                ></el-input-number>
                <span class="stat-unit">天</span>
                <el-input-number
                  size="mini"
                  v-model="parsedFreqTimes"
                  :min="0"
                  :controls="false"
                  style="width: 60px"
                  disabled
                ></el-input-number>
                <span class="stat-unit">次</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部金额 -->
      <div class="table-b-bottom flex-vertical-between">
        <div class="t-b-b-left flex-vertical-center-l flex-wrap">
          <div class="t-b-l-item">
            单次金额：<span>{{ singlePriceText }}</span
            >元
          </div>
          <div class="t-b-l-item">
            疗程金额：<span>{{ coursePriceText }}</span
            >元
          </div>
          <div class="t-b-l-item">
            协定方总金额：<span>{{ totalPriceText }}</span
            >元
          </div>
        </div>
      </div>
    </div>

    <!-- 查看详情弹窗 -->
    <el-dialog
      :visible.sync="showDetailDialog"
      width="50%"
      top="5vh"
      :title="popupDetailType + '详情'"
      append-to-body
      custom-class="detail-dialog"
    >
      <div class="drug-body">
        <!-- 穴位详情 -->
        <template v-if="popupDetailType === '穴位'">
          <div class="drug-item">
            <span>穴位名称：</span>
            <div>{{ popupDetailData.acuname }}</div>
          </div>
          <div class="drug-item">
            <span>定位：</span>
            <div>{{ popupDetailData.acuposotion }}</div>
          </div>
          <div class="drug-item">
            <span>解剖：</span>
            <div>{{ popupDetailData.acudiscection }}</div>
          </div>
          <div class="drug-item">
            <span>主治：</span>
            <div>{{ popupDetailData.acumaintreat }}</div>
          </div>
          <div class="drug-item">
            <span>操作：</span>
            <div>{{ popupDetailData.acuoperation }}</div>
          </div>
          <div class="drug-item">
            <span>针刺：</span>
            <div>{{ popupDetailData.acuneedling }}</div>
          </div>
          <div class="drug-item" v-if="popupDetailData.acuimg">
            <span>图示：</span>
            <div class="detail-img"><img :src="popupDetailData.acuimg" /></div>
          </div>
        </template>
        <!-- 经络详情 -->
        <template v-else-if="popupDetailType === '经络'">
          <div class="drug-item">
            <span>经络名称：</span>
            <div>{{ popupDetailData.mername }}</div>
          </div>
          <div class="drug-item">
            <span>类型：</span>
            <div>{{ merTypeMap[popupDetailData.mertype] || "-" }}</div>
          </div>
          <div class="drug-item" v-if="popupDetailData.mermaindisease">
            <span>主要病候：</span>
            <div v-html="popupDetailData.mermaindisease"></div>
          </div>
          <div class="drug-item" v-if="popupDetailData.mermaintreat">
            <span>主治概要：</span>
            <div v-html="popupDetailData.mermaintreat"></div>
          </div>
          <div class="drug-item" v-if="popupDetailData.merimg">
            <span>图片：</span>
            <div class="detail-img"><img :src="popupDetailData.merimg" /></div>
          </div>
        </template>
        <!-- 耳穴详情 -->
        <template v-else-if="popupDetailType === '耳穴'">
          <div class="drug-item">
            <span>名称：</span>
            <div>{{ popupDetailData.name }}</div>
          </div>
          <div class="drug-item" v-if="popupDetailData.area">
            <span>定位：</span>
            <div>{{ popupDetailData.area }}</div>
          </div>
          <div class="drug-item" v-if="popupDetailData.effect">
            <span>功能：</span>
            <div>{{ popupDetailData.effect }}</div>
          </div>
          <div class="drug-item" v-if="popupDetailData.mainTreat">
            <span>主治：</span>
            <div>{{ popupDetailData.mainTreat }}</div>
          </div>
          <div class="drug-item" v-if="popupDetailData.photo">
            <span>图片：</span>
            <div class="detail-img"><img :src="popupDetailData.photo" /></div>
          </div>
        </template>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAcupointD,
  getMerD,
  getAcuMeridianDetail,
} from "@/api/knowledge.js";

// 详情类型映射
const TYPE_VALUE_MAP = {
  "1": "穴位",
  "2": "经络",
  "3": "耳穴",
  "4": "部位",
  "5": "其他详情",
  "6": "无详情",
};

export default {
  name: "SuitableTechDetail",
  props: {
    detailData: {
      type: Object,
      default: () => ({}),
    },
    showGuide: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      activeIndex: 0,
      // 详情弹窗
      showDetailDialog: false,
      popupDetailData: {},
      popupDetailType: "",
      merTypeMap: {
        1: "十二经脉",
        2: "奇经八脉",
        3: "经外奇穴",
        4: "阿是穴",
      },
    };
  },
  computed: {
    treatmentList() {
      return this.detailData.treatmentList || [];
    },
    activeTreatment() {
      return this.treatmentList[this.activeIndex] || null;
    },
    activeIsEditable() {
      if (!this.activeTreatment) return "-";
      return this.activeTreatment.isUpdate === "1" ? "是" : "否";
    },
    activeDetailTypes() {
      if (!this.activeTreatment) return [];
      const types = new Set();
      const detailKeys = [
        "detailPoint",
        "detailMeridian",
        "detailEarPoint",
        "detailBodyPart",
        "detailOther",
      ];
      detailKeys.forEach((key) => {
        const list = this.activeTreatment[key];
        if (Array.isArray(list) && list.length > 0) {
          list.forEach((item) => {
            const typeName = TYPE_VALUE_MAP[item.type];
            if (typeName) types.add(typeName);
          });
        }
      });
      if (
        this.activeTreatment.detailNone !== null &&
        this.activeTreatment.detailNone !== undefined &&
        typeof this.activeTreatment.detailNone === "object" &&
        !Array.isArray(this.activeTreatment.detailNone)
      ) {
        types.add("无详情");
      }
      return [...types];
    },
    displayDetailTypes() {
      return this.activeDetailTypes.filter((t) => t !== "无详情");
    },
    parsedFreqDays() {
      if (!this.activeTreatment || !this.activeTreatment.frequency)
        return undefined;
      const match = String(this.activeTreatment.frequency).match(
        /(\d+)天(\d+)次/,
      );
      return match ? parseInt(match[1], 10) : undefined;
    },
    parsedFreqTimes() {
      if (!this.activeTreatment || !this.activeTreatment.frequency)
        return undefined;
      const match = String(this.activeTreatment.frequency).match(
        /(\d+)天(\d+)次/,
      );
      return match ? parseInt(match[2], 10) : undefined;
    },
    singlePriceText() {
      return this.activeTreatment
        ? this.activeTreatment.singleAmount || "0.00"
        : "0.00";
    },
    coursePriceText() {
      return this.activeTreatment
        ? this.activeTreatment.courseAmount || "0.00"
        : "0.00";
    },
    totalPriceText() {
      if (!this.treatmentList.length) return "0.00";
      let total = 0;
      this.treatmentList.forEach((item) => {
        total += parseFloat(item.courseAmount) || 0;
      });
      return total.toFixed(2);
    },
  },
  methods: {
    getDetailRows(detailType) {
      if (!this.activeTreatment) return [];
      const TYPE_TO_FIELD = {
        穴位: "detailPoint",
        经络: "detailMeridian",
        耳穴: "detailEarPoint",
        部位: "detailBodyPart",
        其他详情: "detailOther",
      };
      const field = TYPE_TO_FIELD[detailType];
      if (!field) return [];
      const list = this.activeTreatment[field] || [];
      return list.map((item, index) => ({
        id: index + 1,
        name: item.name || "",
        count: item.num || 1,
        remark: item.remark || "",
        mainType: item.acupoint || "1",
        acuid: item.pointId || "",
      }));
    },
    getLeftList(detailType) {
      return this.getDetailRows(detailType).filter((item) => item.id % 2 !== 0);
    },
    getRightList(detailType) {
      return this.getDetailRows(detailType).filter((item) => item.id % 2 === 0);
    },
    async find(scope, detailType) {
      const row = scope.row;
      if (!row.acuid) return;
      try {
        let res;
        if (detailType === "经络") {
          res = await getMerD({ merid: row.acuid });
        } else if (detailType === "耳穴") {
          res = await getAcuMeridianDetail(row.acuid);
        } else {
          res = await getAcupointD({ acuid: row.acuid });
        }
        if (res.code === 0 || res.ResultCode === 0) {
          this.popupDetailData = res.data || res.Data || {};
          this.popupDetailType = detailType;
          this.showDetailDialog = true;
        }
      } catch (e) {
        console.error("获取详情失败", e);
      }
    },
    reset() {
      this.activeIndex = 0;
    },
  },
};
</script>

<style lang="scss" scoped>
.recipe-acupoint-wrapper {
  width: 100%;
}

.prescription-tabs {
  display: flex;
  margin-bottom: 10px;
  flex-shrink: 0;

  .tab-item {
    position: relative;
    display: flex;
    align-items: center;
    padding: 8px 20px;
    font-size: 14px;
    color: #666;
    background: #f5f7fa;
    border-radius: 4px;
    cursor: pointer;
    margin-right: 6px;
    transition: all 0.25s;

    &:hover {
      color: #5386f6;
      background: #e8eefb;
    }

    &.active {
      background: #5386f6;
      color: #fff;

      &:hover {
        background: #4078f0;
      }
    }

    .tab-name {
      max-width: 120px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}

.recipe-acupoint {
  border: 2px solid #dedede;
  padding: 7px 0 0;
  display: flex;
  flex-direction: column;

  .table-toolbar {
    margin-bottom: 10px;
    padding: 0 5px;
    flex-shrink: 0;

    .toolbar-item {
      margin-right: 30px;
      margin-bottom: 5px;

      span {
        font-size: 14px;
        color: #333;
        white-space: nowrap;
      }
    }
  }

  .table-container {
    padding: 0 5px;
    flex: 1;
    min-height: 0;
    overflow: auto;
  }

  .detail-table-section {
    margin-bottom: 10px;

    .detail-section-label {
      display: inline-block;
      padding: 2px 12px;
      border: 1px solid #ff6245;
      border-radius: 4px;
      color: #ff6245;
      font-size: 13px;
      margin-bottom: 6px;
    }
  }

  .table-show {
    width: 100%;
    overflow: auto;
    display: flex;
    align-items: flex-start;
    justify-content: space-between;

    .table-left {
      flex: 0 0 49.9%;
      overflow-y: auto;
      border: 1px solid #dedede;
      box-sizing: border-box;
    }
  }

  .operate {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: space-around;

    img {
      width: 16px;
      cursor: pointer;
    }
  }

  // 底部统计
  .table-bottom {
    flex-shrink: 0;
    padding: 0 5px;
    margin-top: 5px;

    .table-b-header {
      .header-about {
        .item {
          margin-right: 20px;
          margin-bottom: 10px;

          span {
            font-size: 14px;
            color: #333;
            white-space: nowrap;
          }
        }
      }
    }
  }

  .stat-row {
    .stat-field {
      margin-right: 50px;
      margin-bottom: 5px;

      span {
        font-size: 14px;
        color: #333;
        white-space: nowrap;
      }

      .stat-unit {
        margin: 0 4px;
      }
    }
  }
}

.readonly-text {
  font-size: 14px;
  color: #666;
}

.recipe-acupoint ::v-deep .el-table .cell {
  text-align: center;
}

.recipe-acupoint ::v-deep .el-table td {
  padding: 2px 0;
}

.recipe-acupoint ::v-deep .el-table th {
  padding: 2px 0;
}

.recipe-acupoint .table-show .table-left ::v-deep .el-table__empty-block {
  min-height: 33px !important;
  height: 33px !important;
}

// 底部金额
.table-b-bottom {
  flex-shrink: 0;
  padding: 10px;
  border-top: 2px solid #dedede;
  margin-top: 5px;

  .t-b-l-item {
    font-size: 14px;
    color: #333;
    margin-right: 20px;

    span {
      color: #ff6245;
    }
  }
}

.drug-body {
  padding: 10px;

  .drug-item {
    display: flex;
    align-items: flex-start;
    margin-bottom: 12px;

    > span {
      min-width: 80px;
      font-size: 14px;
      color: #333;
      text-align: right;
      margin-right: 10px;
      flex-shrink: 0;
    }

    > div {
      flex: 1;
      font-size: 14px;
      color: #666;
      word-break: break-all;
      line-height: 1.6;
    }

    .detail-img {
      img {
        max-width: 100%;
        max-height: 300px;
      }
    }
  }
}

.recipe-acupoint
  ::v-deep
  .el-checkbox.is-disabled
  .el-checkbox__input.is-disabled
  .el-checkbox__inner {
  background-color: #fff;
  border-color: #dcdfe6;
}
.recipe-acupoint
  ::v-deep
  .el-checkbox.is-disabled
  .el-checkbox__input.is-disabled.is-checked
  .el-checkbox__inner {
  background-color: #5386f6;
  border-color: #5386f6;
}
.recipe-acupoint
  ::v-deep
  .el-checkbox.is-disabled
  .el-checkbox__input.is-disabled.is-checked
  .el-checkbox__inner::after {
  border-color: #fff;
}
</style>

<style lang="scss">
.detail-dialog {
  margin: 0 auto;

  .el-dialog__header {
    padding: 0;
    background: #5386f6;
    text-align: center;
    height: 40px;
    line-height: 40px;
  }

  .el-dialog__title {
    font-size: 16px;
    color: #fff;
  }

  .el-dialog__headerbtn {
    top: 8px;
    right: 10px;
    font-size: 22px;
    .el-dialog__close {
      color: #fff;
      font-size: 22px;
    }
  }

  .el-dialog__body {
    padding: 18px;
    max-height: 75vh;
    overflow-y: auto;
  }

  .drug-body {
    padding: 10px;

    .drug-item {
      display: flex;
      align-items: flex-start;
      margin-bottom: 12px;

      > span {
        min-width: 80px;
        font-size: 14px;
        color: #333;
        text-align: right;
        margin-right: 10px;
        flex-shrink: 0;
      }

      > div {
        flex: 1;
        font-size: 14px;
        color: #666;
        word-break: break-all;
        line-height: 1.6;
      }

      .detail-img {
        img {
          max-width: 100%;
          max-height: 300px;
        }
      }
    }
  }
}
</style>
