<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="common-prescription-modal">
      <view class="modal-header">
        <d-text text="常用方" className="fs-32 main-c"></d-text>
      </view>

      <view class="modal-content">
        <scroll-view class="list-scroll" scroll-y>
          <view class="list-scroll-inner">
            <!-- 常用方列表 -->
            <view class="prescription-list" v-if="prescriptionList.length > 0">
              <view
                class="prescription-item white b-r-8 m-t-2"
                v-for="(item, index) in prescriptionList"
                :key="item.id"
                @click="handleSelectPrescription(item, index)"
              >
                <view class="item-header flex-row flex-jus-sp flex-ali-center">
                  <view class="flex-row flex-ali-center">
                    <d-text text="名称：" className="fs-3 color9"></d-text>
                    <d-text :text="item.name" className="fs-3 main-c"></d-text>
                  </view>
                  <view class="tag" :class="tagClass">
                    {{ tagText }}
                  </view>
                </view>
                <view class="item-content m-t-16">
                  <view class="label">药品：</view>
                  <view class="drug-list">
                    <text
                      v-for="(drug, idx) in getDrugList(item, index)"
                      :key="idx"
                      class="drug-item"
                    >
                      {{ formatDrugName(drug) }}
                    </text>
                  </view>
                </view>
                <view class="item-footer m-t-24 btnBox" v-if="!isSelectMode">
                  <view @click.stop="handleDeletePrescription(item, index)" class="btn left">移除</view>
                  <view @click.stop="handleSelectPrescription(item, index)" class="btn right">使用</view>
                </view>
              </view>
            </view>

            <!-- 空状态 -->
            <view class="empty-state" v-else>
              <d-empty text="暂无常用方"></d-empty>
            </view>
          </view>
        </scroll-view>
      </view>

      <!-- 底部按钮 -->
      <view class="modal-footer flex-jus-between flex-ali-center" v-if="!isSelectMode">
        <u-button
          :throttle-time="0"
          @click="handleClose"
          shape="circle"
          :custom-style="{
            backgroundColor: '#f5f5f5',
            color: '#333',
            height: '86rpx',
            width: '320rpx'
          }"
        >取消</u-button>
        <u-button
          :throttle-time="0"
          @click="handleAddNew"
          shape="circle"
          :custom-style="{
            backgroundColor: '#6ACDBB',
            color: '#fff',
            height: '86rpx',
            width: '320rpx'
          }"
        >新建常用方</u-button>
      </view>
    </view>
  </u-popup>
</template>

<script>
import { getCommonPrescriptionListApi, deleteCommonPrescriptionApi } from '@/api/reception.js';

export default {
  name: 'CommonPrescriptionModal',
  props: {
    /**
     * 弹窗显示状态
     */
    value: {
      type: Boolean,
      default: false
    },
    /**
     * 处方类型：1=中药，2=西药，3=保健食品
     */
    prescriptionType: {
      type: Number,
      default: 2
    },
    /**
     * 是否为选择模式（选择模式不显示删除按钮）
     */
    isSelectMode: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      show: false,
      prescriptionList: [],
      // 与 prescriptionList 平行的药品数组：list 接口里 west/chinese/granular 字段，按下标一一对应
      recipesByIndex: [],
      loading: false
    };
  },
  computed: {
    /**
     * 获取标签类名（计算属性）
     * @returns {string} 标签类名
     */
    tagClass() {
      if (this.prescriptionType === 1) {
        return 'tag-chinese';
      } else if (this.prescriptionType === 2) {
        return 'tag-west';
      } else {
        return 'tag-granular';
      }
    },

    /**
     * 获取标签文本（计算属性）
     * @returns {string} 标签文本
     */
    tagText() {
      if (this.prescriptionType === 1) {
        return '中药饮片';
      } else if (this.prescriptionType === 2) {
        return '西药(中成)';
      } else {
        return '保健食品';
      }
    }
  },
  watch: {
    value(newVal) {
      this.show = newVal;
      if (newVal) {
        this.loadPrescriptionList();
      }
    },
    show(newVal) {
      if (!newVal) {
        this.$emit('input', false);
      }
    }
  },
  methods: {
    /**
     * 加载常用方列表
     * 职责：调用接口获取常用方列表
     */
    async loadPrescriptionList() {
      this.loading = true;
      try {
        const storeId = uni.getStorageSync('store_id') || 11001;
        const type = this.getCommonPrescriptionType(this.prescriptionType);
        const res = await getCommonPrescriptionListApi(storeId);

        if (res && res.code === 0) {
          // 根据类型过滤常用方主表行 + 平行药品行
          const listKey = this.getListKey(type);
          this.prescriptionList = res.result?.[listKey] || [];
          // type 即 west/chinese/granular，正好是 list 接口里平行药品数组的 key
          this.recipesByIndex = res.result?.[type] || [];
        } else {
          this.prescriptionList = [];
          this.recipesByIndex = [];
        }
      } catch (error) {
        console.error('获取常用方列表失败:', error);
        this.$toast('获取常用方列表失败');
        this.prescriptionList = [];
        this.recipesByIndex = [];
      } finally {
        this.loading = false;
      }
    },

    /**
     * 获取常用方类型字符串
     * @param {number} type - 处方类型
     * @returns {string} 常用方类型：west、chinese、granular
     */
    getCommonPrescriptionType(type) {
      if (type === 1) {
        return 'chinese';
      } else if (type === 2) {
        return 'west';
      } else {
        return 'granular';
      }
    },

    /**
     * 获取列表键名
     * @param {string} type - 常用方类型
     * @returns {string} 列表键名
     */
    getListKey(type) {
      if (type === 'chinese') {
        return 'chin_prescription';
      } else if (type === 'west') {
        return 'west_prescription';
      } else {
        return 'granular_prescription';
      }
    },

    /**
     * 获取某条常用方对应的药品列表
     * 与 PC 一致：list 接口返回的主表行与药品行按下标对齐，从 recipesByIndex[index] 取
     * @param {Object} _prescription - 主表行（保留参数为可调试用，未使用）
     * @param {number} index - 列表中的下标
     * @returns {Array} 药品列表
     */
    getDrugList(_prescription, index) {
      return this.recipesByIndex[index] || [];
    },

    /**
     * 格式化药品名称
     * @param {Object} drug - 药品数据
     * @returns {string} 格式化后的药品名称
     */
    formatDrugName(drug) {
      if (typeof drug === 'string') {
        try {
          drug = JSON.parse(drug);
        } catch (e) {
          return drug;
        }
      }

      if (this.prescriptionType === 1) {
        // 中药
        const name = drug.drug_name || drug.name || '';
        const number = drug.number || 1;
        const unit = drug.unit?.name || 'g';
        return `${name} ${number}${unit}`;
      } else {
        // 西药或其他
        const name = drug.drug_name || drug.name || '';
        const number = drug.number || drug.select_number || 1;
        return `${name} *${number}盒`;
      }
    },

    /**
     * 获取列表项的唯一key
     * @param {Object} item - 列表项
     * @param {number} index - 索引
     * @returns {string|number} 唯一key
     */
    getItemKey(item, index) {
      return item.id || `item_${index}`;
    },

    /**
     * 选择常用方
     * 直接 emit 整条主表行（已包含后端组装好的 apply_payload），
     * 父组件读 item.apply_payload 即可直接 spread 覆盖编辑区。
     * @param {Object} item - 主表行（含 apply_payload）
     * @param {number} _index - 列表中的下标（保留以维持模板调用兼容，未使用）
     */
    handleSelectPrescription(item, _index) {
      this.$emit('select', item);
      this.handleClose();
    },

    /**
     * 删除常用方
     * @param {Object} prescription - 常用方数据
     * @param {number} index - 索引
     * 职责：调用接口删除常用方
     */
    async handleDeletePrescription(prescription, index) {
      uni.showModal({
        title: '删除常用方',
        content: '是否要删除该常用方？',
        showCancel: true,
        success: async ({ confirm }) => {
          if (confirm) {
            try {
              const type = this.getCommonPrescriptionType(this.prescriptionType);
              const res = await deleteCommonPrescriptionApi({
                id: prescription.id,
                type
              });
              if (res && res.code === 0) {
                this.prescriptionList.splice(index, 1);
                this.recipesByIndex.splice(index, 1);
                this.$toast('删除成功');
              } else {
                this.$toast(res.msg || res.message || '删除失败');
              }
            } catch (error) {
              console.error('删除常用方失败:', error);
              this.$toast('删除失败');
            }
          }
        }
      });
    },

    /**
     * 新建常用方
     * 职责：关闭弹窗，触发新建事件
     */
    handleAddNew() {
      const initialCategory =
        this.prescriptionType === 1 ? 1 : this.prescriptionType === 2 ? 2 : 3;
      this.handleClose();
      uni.navigateTo({
        url: `/subPackages/sub_workbench/prescription_v2/index?save_common=1&initial_category=${initialCategory}`
      });
    },

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

<style lang="scss" scoped>
.common-prescription-modal {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
  overflow: hidden;
  background-color: #fff;
}

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

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

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

.list-scroll-inner {
  padding: 32rpx;
}

.prescription-list {
  padding-bottom: 32rpx;
}

.prescription-item {
  padding: 32rpx;
  margin-bottom: 16rpx;
}

.item-header {
  position: relative;
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.tag {
  position: absolute;
  right: 0;
  top: 0;
  padding: 8rpx 24rpx;
  border-radius: 48rpx;
  color: #fff;
  font-size: 24rpx;
  text-align: center;

  &.tag-chinese {
    background: rgba(15, 190, 22, 0.55);
  }

  &.tag-west {
    background: rgba(15, 163, 190, 0.55);
  }

  &.tag-granular {
    background: #6ACDBB;
  }
}

.item-content {
  display: flex;
  flex-direction: column;
}

.label {
  font-size: 28rpx;
  color: #6C7380;
  margin-bottom: 16rpx;
}

.drug-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.drug-item {
  font-size: 28rpx;
  color: #333;
  padding: 8rpx 16rpx;
  background: #f9f9f9;
  border-radius: 8rpx;
}

.item-footer {
  display: flex;
  justify-content: space-around;
  padding-top: 24rpx;
  border-top: 1rpx solid #f0f0f0;
}

.btnBox {
  display: flex;
  align-items: center;
  border: 1rpx solid rgba(242, 242, 242, 1);

  .btn {
    flex: 1;
    height: 86rpx;
    line-height: 86rpx;
    text-align: center;
    font-size: 28rpx;

    &.left {
      border-right: 1rpx solid rgba(242, 242, 242, 1);
      color: #FC3636;
    }

    &.right {
      color: #6ACDBB;
    }
  }
}

.empty-state {
  padding: 100rpx 0;
  text-align: center;
}

.modal-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx;
  border-top: 1rpx solid #eee;
}

.white {
  background: #fff;
}

.b-r-8 {
  border-radius: 8rpx;
}

.m-t-2 {
  margin-top: 16rpx;
}

.m-t-16 {
  margin-top: 16rpx;
}

.m-t-24 {
  margin-top: 24rpx;
}

.flex-row {
  display: flex;
  flex-direction: row;
}

.flex-jus-sp {
  justify-content: space-between;
}

.flex-ali-center {
  align-items: center;
}

.color9 {
  color: #999;
}
</style>
