<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="western-usage-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="medicine-card m-b-24" v-if="drug">
          <view class="flex-row flex-ali-start">
            <view class="info-icon m-r-16">
              <u-icon name="info-circle-fill" size="36" color="#00A88A"></u-icon>
            </view>
            <view class="flex-col">
              <d-text :text="drug.drug_name" className="fs-32 font-bold color-title m-b-8"></d-text>
              <d-text :text="`规格：${drug.specification || '--'}`" className="fs-26 color-sub"></d-text>
            </view>
          </view>
        </view>

        <!-- 表单区域：使用统一现代化表单卡片 -->
        <view class="form-card">
          <!-- 药品数量 -->
          <view class="form-item border-b">
            <view class="item-label">
              <d-text text="药品数量" className="fs-30 font-bold color-title"></d-text>
            </view>
            <view class="item-content flex-row flex-ali-center">
              <u-number-box
                  v-model="usageData.select_number"
                  :min="1"
                  :max="(drug && drug.stock) || 999"
                  :input-width="80"
                  :input-height="60"
                  bg-color="#F7F8FA"
              />
              <d-text text="盒" className="fs-28 color-sub m-l-16"></d-text>
            </view>
          </view>

          <!-- 用法 -->
          <view class="form-item border-b">
            <view class="item-label">
              <d-text text="给药途径" className="fs-30 font-bold color-title"></d-text>
            </view>
            <view class="item-content">
              <picker
                  mode="selector"
                  :range="drugUseList.drug_use_type || []"
                  range-key="name"
                  :value="usageData.type_id && drugUseList.drug_use_type ? drugUseList.drug_use_type.findIndex(item => item.id === usageData.type_id) : 0"
                  @change="handleChangeUsageType"
              >
                <view class="modern-picker-view">
                  <text class="fs-28 color-title">{{ (usageData.use_type && usageData.use_type.name) || '请选择用法' }}</text>
                  <u-icon name="arrow-right" size="24" color="#B0B6C2"></u-icon>
                </view>
              </picker>
            </view>
          </view>

          <!-- 频次 -->
          <view class="form-item border-b">
            <view class="item-label">
              <d-text text="用药频次" className="fs-30 font-bold color-title"></d-text>
            </view>
            <view class="item-content">
              <picker
                  mode="selector"
                  :range="drugUseList.drug_use_frequency || []"
                  range-key="name"
                  :value="usageData.frequency_id && drugUseList.drug_use_frequency ? drugUseList.drug_use_frequency.findIndex(item => item.id === usageData.frequency_id) : 0"
                  @change="handleChangeFrequency"
              >
                <view class="modern-picker-view">
                  <text class="fs-28 color-title">{{ (usageData.use_frequency && usageData.use_frequency.name) || '请选择频次' }}</text>
                  <u-icon name="arrow-right" size="24" color="#B0B6C2"></u-icon>
                </view>
              </picker>
            </view>
          </view>

          <!-- 时间 -->
          <view class="form-item border-b">
            <view class="item-label">
              <d-text text="用药时间" className="fs-30 font-bold color-title"></d-text>
            </view>
            <view class="item-content">
              <picker
                  mode="selector"
                  :range="drugUseList.drug_time || []"
                  range-key="name"
                  :value="usageData.time_id && drugUseList.drug_time ? drugUseList.drug_time.findIndex(item => item.id === usageData.time_id) : 0"
                  @change="handleChangeTime"
              >
                <view class="modern-picker-view">
                  <text class="fs-28 color-title">{{ (usageData.use_num && usageData.use_num.name) || '请选择时间' }}</text>
                  <u-icon name="arrow-right" size="24" color="#B0B6C2"></u-icon>
                </view>
              </picker>
            </view>
          </view>

          <!-- 单位与单次用量 -->
          <view class="form-item">
            <view class="item-label">
              <d-text text="单次用量" className="fs-30 font-bold color-title"></d-text>
            </view>
            <view class="item-content flex-row flex-ali-center flex-jus-end">
              <u-number-box
                  v-model="usageData.number"
                  :min="1"
                  :input-width="80"
                  :input-height="60"
                  bg-color="#F7F8FA"
              />
              <picker
                  mode="selector"
                  :range="drugUseList.drug_unit || []"
                  range-key="name"
                  :value="usageData.unit_id && drugUseList.drug_unit ? drugUseList.drug_unit.findIndex(item => item.id === usageData.unit_id) : 0"
                  @change="handleChangeUnit"
              >
                <view class="modern-picker-view m-l-16" style="min-width: 140rpx;">
                  <text class="fs-28 color-title">{{ (usageData.unit && usageData.unit.name) || '单位' }}</text>
                  <u-icon name="arrow-right" size="24" color="#B0B6C2"></u-icon>
                </view>
              </picker>
            </view>
          </view>
        </view>
      </view>

      <!-- 底部按钮：补充了 flex-row 以修复上下排列的问题 -->
      <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 { getDrugUseList, getDrugUseWithDefault } from '@/api/reception.js';

export default {
  name: 'WesternMedicineUsageModal',
  props: {
    /**
     * 弹窗显示状态
     */
    value: {
      type: Boolean,
      default: false
    },
    /**
     * 药品数据
     */
    drug: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      show: false,
      usageData: {
        select_number: 1,
        number: 1,
        type_id: 0,
        frequency_id: 0,
        time_id: 0,
        unit_id: 0,
        use_type: null,
        use_frequency: null,
        use_num: null,
        unit: null
      },
      drugUseList: {
        drug_use_type: [],
        drug_use_frequency: [],
        drug_time: [],
        drug_unit: []
      }
    };
  },
  watch: {
    value(newVal) {
      this.show = newVal;
      if (newVal && this.drug) {
        // 打开时先加载用法用量列表和默认值，再根据 default/drug 初始化 usageData
        this.loadDrugUseList();
      }
    },
    show(newVal) {
      if (!newVal) {
        this.$emit('input', false);
      }
    }
  },
  methods: {
    /**
     * 初始化用法用量数据
     * 职责：从药品数据中初始化用法用量
     */
    initUsageData() {
      if (this.drug) {
        this.usageData = {
          select_number: this.drug.select_number || this.drug.number || 1,
          number: this.drug.number || 1,
          type_id: this.drug.type_id || 0,
          frequency_id: this.drug.frequency_id || 0,
          time_id: this.drug.time_id || 0,
          unit_id: this.drug.unit_id || 0,
          use_type: this.drug.use_type || null,
          use_frequency: this.drug.use_frequency || null,
          use_num: this.drug.use_num || null,
          unit: this.drug.unit || null
        };
      }
    },

    /**
     * 加载药品使用方式列表
     * 职责：调用接口获取药品使用方式列表
     */
    async loadDrugUseList() {
      try {
        const drugId = this.drug && (this.drug.drug_id || this.drug.id);
        let payload = null;

        if (drugId) {
          const res = await getDrugUseWithDefault(drugId);
          if (res) {
            payload = res.data || res.result || res;
          }
        } else {
          const res = await getDrugUseList();
          if (res) {
            payload = res.data || res.result || res;
          }
        }

        if (!payload) {
          this.drugUseList = { drug_use_type: [], drug_use_frequency: [], drug_time: [], drug_unit: [] };
          this.$toast('暂无用法用量配置，请联系管理员');
          return;
        }

        const lists = payload.lists || payload;
        const def = payload.default || {};
        this.drugUseList = lists;

        // 仅在当前 usageData 还没有配置时使用默认值
        if (!this.usageData.type_id && def.type_id && lists.drug_use_type) {
          this.usageData.type_id = def.type_id;
          this.usageData.use_type = (lists.drug_use_type || []).find(i => i.id === def.type_id) || null;
        }
        if (!this.usageData.frequency_id && def.frequency_id && lists.drug_use_frequency) {
          this.usageData.frequency_id = def.frequency_id;
          this.usageData.use_frequency = (lists.drug_use_frequency || []).find(i => i.id === def.frequency_id) || null;
        }
        if (!this.usageData.time_id && def.time_id && lists.drug_time) {
          this.usageData.time_id = def.time_id;
          this.usageData.use_num = (lists.drug_time || []).find(i => i.id === def.time_id) || null;
        }
        if (!this.usageData.unit_id && def.unit_id && lists.drug_unit) {
          this.usageData.unit_id = def.unit_id;
          this.usageData.unit = (lists.drug_unit || []).find(i => i.id === def.unit_id) || null;
        }

        const hasOptions =
            (lists.drug_use_type || []).length ||
            (lists.drug_use_frequency || []).length ||
            (lists.drug_time || []).length ||
            (lists.drug_unit || []).length;
        if (!hasOptions) {
          this.$toast('暂无用法用量配置，请联系管理员');
        }
      } catch (error) {
        console.error('获取药品使用方式列表失败:', error);
        this.$toast('获取用法用量失败');
      }
    },

    /**
     * 改变用法类型
     * @param {Object} e - 事件对象
     * 职责：更新用法类型
     */
    handleChangeUsageType(e) {
      const index = parseInt(e.detail.value);
      const item = this.drugUseList.drug_use_type[index];
      if (item) {
        this.usageData.type_id = item.id;
        this.usageData.use_type = item;
      }
    },

    /**
     * 改变频次
     * @param {Object} e - 事件对象
     * 职责：更新频次
     */
    handleChangeFrequency(e) {
      const index = parseInt(e.detail.value);
      const item = this.drugUseList.drug_use_frequency[index];
      if (item) {
        this.usageData.frequency_id = item.id;
        this.usageData.use_frequency = item;
      }
    },

    /**
     * 改变时间
     * @param {Object} e - 事件对象
     * 职责：更新时间
     */
    handleChangeTime(e) {
      const index = parseInt(e.detail.value);
      const item = this.drugUseList.drug_time[index];
      if (item) {
        this.usageData.time_id = item.id;
        this.usageData.use_num = item;
      }
    },

    /**
     * 改变单位
     * @param {Object} e - 事件对象
     * 职责：更新单位
     */
    handleChangeUnit(e) {
      const index = parseInt(e.detail.value);
      const item = this.drugUseList.drug_unit[index];
      if (item) {
        this.usageData.unit_id = item.id;
        this.usageData.unit = item;
      }
    },

    /**
     * 确认
     * 职责：触发confirm事件，传递用法用量数据
     */
    handleConfirm() {
      this.$emit('confirm', { ...this.usageData });
      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-8 { margin-bottom: 8rpx; }
.m-b-24 { margin-bottom: 24rpx; }
.m-r-16 { margin-right: 16rpx; }
.m-l-16 { margin-left: 16rpx; }
.border-b { border-bottom: 1px dashed #E2E8F0; }
.shadow-up { box-shadow: 0 -4rpx 20rpx rgba(0,0,0,0.04); }

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

.western-usage-modal {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

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

.modal-content {
  flex: 1;
  overflow-y: auto;
  padding: 32rpx;
  /* 底部防遮挡边距 */
  padding-bottom: 24rpx;
}

/* 顶部药品提示卡片 */
.medicine-card {
  background: #E8F6F4;
  border-radius: 16rpx;
  padding: 24rpx;
  border: 1px solid #BFE6DF;
}
.info-icon {
  margin-top: 4rpx;
}

/* 统一表单卡片 */
.form-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 0 32rpx;
  box-shadow: 0 4rpx 16rpx rgba(42, 46, 53, 0.04);
}

.form-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx 0;
}

.modern-picker-view {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12rpx 24rpx;
  background: #F7F8FA;
  border-radius: 8rpx;
  min-width: 240rpx;
}

/* 彻底解决底部按钮上下排列，显式开启 flex 布局 */
.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>