<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="doctor-order-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">
        <scroll-view class="order-scroll" scroll-y>
          <view class="order-scroll-inner">
            <!-- 我的医嘱 -->
            <view class="section white radius-16 p-32 m-b-24 shadow-sm">
              <view class="section-header flex-row flex-jus-sp flex-ali-center m-b-24">
                <d-text text="我的医嘱" className="fs-30 font-bold color-title"></d-text>
                <view class="add-btn-modern" @click="openAddModal">
                  <u-icon name="plus" size="24" color="#00A88A" class="m-r-8"></u-icon>
                  <text class="add-text">添加医嘱</text>
                </view>
              </view>

              <!-- 我的医嘱列表 -->
              <view class="modern-tag-container">
                <view
                    v-for="item in doctorOrderMyList"
                    :key="item.id"
                    class="modern-tag-item"
                    :class="{ 'is-selected': item.isSelect === 1 }"
                    @click="selectDoctorOrder(item, 1)"
                >
                  <text class="tag-text">{{ item.content }}</text>
                  <view class="tag-action" @click.stop="deleteMyDoctorOrder(item)">
                    <u-icon name="close" size="20"></u-icon>
                  </view>
                </view>
              </view>
            </view>

            <!-- 公共医嘱 -->
            <view class="section white radius-16 p-32 shadow-sm" v-if="doctorOrderCommonList.length > 0">
              <view class="section-header m-b-24">
                <d-text text="系统公共医嘱" className="fs-30 font-bold color-title"></d-text>
              </view>
              <view class="modern-tag-container">
                <view
                    v-for="item in doctorOrderCommonList"
                    :key="item.id"
                    class="modern-tag-item"
                    :class="{ 'is-selected': item.isSelect === 1 }"
                    @click="selectDoctorOrder(item, 2)"
                >
                  <text class="tag-text">{{ item.content }}</text>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>

      <!-- 底部按钮 -->
      <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-modal
        v-model="showAddModal"
        :show-cancel-button="true"
        title="添加医嘱"
        z-index="10090"
        @confirm="addMyDoctorOrder"
        @cancel="cancelAdd"
    >
      <view class="slot-content" style="padding: 40rpx;">
        <u-input
            v-model="newOrderContent"
            placeholder="请输入医嘱内容"
            type="text"
            :border="true"
            border-color="#E2E8F0"
        />
      </view>
    </u-modal>
  </u-popup>
</template>

<script>
// 保留所有原有逻辑代码与注释
import { getDoctorOrderList, getDoctorOrderCommonList, createDoctorOrder, deleteDoctorOrder } from '@/api/reception.js';

export default {
  name: 'DoctorOrderModal',
  props: {
    /**
     * 弹窗显示状态
     */
    value: {
      type: Boolean,
      default: false
    },
    /**
     * 已选中的医嘱文本
     */
    selectedDoctorOrder: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      show: false,
      doctorOrderCommonList: [],
      doctorOrderMyList: [],
      selectDoctorOrderList: '',
      showAddModal: false,
      newOrderContent: ''
    };
  },
  watch: {
    value(newVal) {
      this.show = newVal;
      if (newVal) {
        this.selectDoctorOrderList = this.selectedDoctorOrder || '';
        this.loadDoctorOrderListData();
      }
    },
    show(newVal) {
      if (!newVal) {
        this.$emit('input', false);
      }
    }
  },
  methods: {
    /**
     * 加载医嘱列表数据
     * 职责：调用接口获取我的医嘱和公共医嘱列表
     */
    async loadDoctorOrderListData() {
      try {
        // 获取我的医嘱
        const myRes = await getDoctorOrderList();
        if (myRes && (myRes.code === 0 || myRes.errcode === 0)) {
          const list = myRes.data || myRes.result || myRes.my || [];
          this.doctorOrderMyList = list.map((item) => {
            item.isSelect = 0;
            if (this.selectDoctorOrderList) {
              const valuesArr = this.selectDoctorOrderList.split('，');
              valuesArr.forEach((value) => {
                if (value === item.content) {
                  item.isSelect = 1;
                }
              });
            }
            return item;
          });
        } else {
          this.doctorOrderMyList = [];
        }

        // 获取公共医嘱
        const commonRes = await getDoctorOrderCommonList({
          store_id: uni.getStorageSync('store_id') || 11001
        });
        if (commonRes && commonRes.code === 0) {
          this.doctorOrderCommonList = (commonRes.result || []).map((item) => {
            item.isSelect = 0;
            if (this.selectDoctorOrderList) {
              const valuesArr = this.selectDoctorOrderList.split('，');
              valuesArr.forEach((value) => {
                if (value === item.content) {
                  item.isSelect = 1;
                }
              });
            }
            return item;
          });
        }
      } catch (error) {
        console.error('获取医嘱列表失败:', error);
        this.$toast('获取医嘱列表失败');
      }
    },

    /**
     * 选择医嘱
     * @param {Object} item - 医嘱项
     * @param {number} type - 类型：1=我的医嘱，2=公共医嘱
     * 职责：切换医嘱的选中状态，更新选中列表
     */
    selectDoctorOrder(item, type = 1) {
      let arr = this.selectDoctorOrderList ? this.selectDoctorOrderList.split('，').filter(Boolean) : [];

      if (type === 1) {
        // 我的医嘱
        if (item.isSelect === 1) {
          arr = arr.filter(name => name !== item.content);
          item.isSelect = 0;
        } else {
          if (!arr.includes(item.content)) {
            arr.push(item.content);
          }
          item.isSelect = 1;
        }
      } else {
        // 公共医嘱
        if (item.isSelect === 1) {
          arr = arr.filter(name => name !== item.content);
          item.isSelect = 0;
        } else {
          if (!arr.includes(item.content)) {
            arr.push(item.content);
          }
          item.isSelect = 1;
        }
      }

      this.selectDoctorOrderList = arr.join('，');
    },

    /**
     * 打开添加医嘱弹窗
     * 职责：清空旧内容，打开弹窗
     */
    openAddModal() {
      this.newOrderContent = '';
      this.showAddModal = true;
    },

    /**
     * 添加自定义医嘱
     * 职责：调用接口添加我的医嘱
     */
    async addMyDoctorOrder() {
      if (!this.newOrderContent.trim()) {
        this.$toast('请输入医嘱内容');
        return;
      }

      try {
        const res = await createDoctorOrder(this.newOrderContent.trim());
        if (res && (res.code === 0 || res.errcode === 0)) {
          this.$toast('添加成功');
          this.newOrderContent = '';
          this.showAddModal = false;
          await this.loadDoctorOrderListData();
        } else {
          this.$toast(res.msg || res.message || '添加失败');
        }
      } catch (error) {
        console.error('添加医嘱失败:', error);
        this.$toast('添加失败');
      }
    },

    /**
     * 删除我的医嘱
     * @param {Object} item - 医嘱项
     * 职责：调用接口删除我的医嘱
     */
    async deleteMyDoctorOrder(item) {
      try {
        const res = await deleteDoctorOrder(item.id);
        if (res && (res.code === 0 || res.errcode === 0)) {
          this.$toast('删除成功');
          await this.loadDoctorOrderListData();
        } else {
          this.$toast(res.msg || res.message || '删除失败');
        }
      } catch (error) {
        console.error('删除医嘱失败:', error);
        this.$toast('删除失败');
      }
    },

    /**
     * 取消添加
     * 职责：关闭弹窗
     */
    cancelAdd() {
      this.showAddModal = false;
      this.newOrderContent = '';
    },

    /**
     * 确认选择
     * 职责：触发确认事件，传递选中的医嘱文本
     */
    handleConfirm() {
      this.$emit('confirm', this.selectDoctorOrderList);
      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; }
.fs-26 { font-size: 26rpx; }
.fs-30 { font-size: 30rpx; }
.fs-32 { font-size: 32rpx; }
.font-bold { font-weight: bold; }
.m-b-24 { margin-bottom: 24rpx; }
.m-t-16 { margin-top: 16rpx; }
.m-r-8 { margin-right: 8rpx; }
.m-l-16 { margin-left: 16rpx; }
.p-32 { padding: 32rpx; }
.radius-16 { border-radius: 16rpx; }
.shadow-sm { box-shadow: 0 4rpx 16rpx rgba(42, 46, 53, 0.04); }
.shadow-up { box-shadow: 0 -4rpx 20rpx rgba(0,0,0,0.04); }

.flex-row { display: flex; flex-direction: row; }
.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; }

.doctor-order-modal {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
  overflow: hidden;
}

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

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

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

.order-scroll-inner {
  padding-bottom: 140rpx;
}

.add-btn-modern {
  display: flex;
  align-items: center;
  padding: 8rpx 20rpx;
  background: #E8F6F4;
  border-radius: 32rpx;
  cursor: pointer;

  .add-text {
    font-size: 24rpx;
    font-weight: bold;
    color: #00A88A;
  }
}

.modern-tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.modern-tag-item {
  display: inline-flex;
  align-items: center;
  padding: 12rpx 24rpx;
  background-color: #F7F8FA;
  border: 1px solid #E2E8F0;
  border-radius: 36rpx;
  cursor: pointer;
  transition: all 0.2s;

  &.is-selected {
    background-color: #E8F6F4;
    border-color: #00A88A;
    .tag-text {
      color: #00A88A;
      font-weight: bold;
    }
    .tag-action {
      color: #00A88A;
    }
  }

  .tag-text {
    font-size: 26rpx;
    color: #4b5563;
  }

  .tag-action {
    margin-left: 12rpx;
    display: flex;
    align-items: center;
    color: #8A92A3;
  }
}

.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>