<template>
  <view class="container">
    <u-sticky offsetTop="0rpx" customNavHeight="0rpx">
      <view class="search-view">
        <u--input 
          v-model="queryParams.keys" 
          border="surround"
          @change="searchBlur"
          placeholder="计划名称/药品名称" 
          placeholderStyle="color: #909399"
          color="#333333"
          customStyle="background: rgba(102, 126, 234, 0.08); border: 2rpx solid rgba(102, 126, 234, 0.3); border-radius: 24rpx; height: 66rpx"
          class="search-input" 
          suffixIcon="search" 
          suffixIconStyle="color: #667eea">
        </u--input>
        <view class="filter-btn" @click="filterPanel = !filterPanel">
          <uni-icons type="list" size="18" color="#667eea"></uni-icons>
          <text>筛选</text>
        </view>
        <view class="add-btn" v-show="auth.hasPermi('health:medicationPlan:add')" @click="handleAdd()">
          <uni-icons type="plusempty" size="18" color="#667eea"></uni-icons>
          <text>新增</text>
        </view>
        <u-transition :show="filterPanel" mode="fade">
          <view class="filter-panel">
            <view class="filter-panel-content">
              <view class="filter-title">状态</view>
              <view class="state-list">
                <view v-for="item in statusList" :key="item.value" class="state-item"
                  :class="queryParams.status == item.value ? 'active' : ''" @click="selectStatus(item)">{{ item.label }}</view>
              </view>
              <view class="filter-title">人员</view>
              <view class="state-list">
                <view v-for="item in personList" :key="item.id" class="state-item"
                  :class="queryParams.personId == item.id ? 'active' : ''" @click="selectPerson(item)">{{ item.name }}</view>
              </view>
            </view>
            <view class="btn-box">
              <view class="btn-reset" @click="resetQuery()">
                <uni-icons type="reload" size="16" color="#909399"></uni-icons>
                <text>重置</text>
              </view>
              <view class="btn-confirm" @click="searchSubmit()">
                <uni-icons type="checkmarkempty" size="16" color="#ffffff"></uni-icons>
                <text>确定</text>
              </view>
            </view>
          </view>
        </u-transition>
      </view>
    </u-sticky>
    <u-list @scrolltolower="loadmore" :spaceHeight="116" lowerThreshold="100">
      <u-list-item v-for="(item, index) in listData" :key="index">
        <view class="list-item">
          <view class="item-header">
            <view class="card-name-section">
              <view class="card-icon">
                <uni-icons type="calendar" size="20" color="#ffffff"></uni-icons>
              </view>
              <view class="card-info">
                <text class="card-name">{{ item.planName || item.medicineName || '用药计划' }}</text>
              </view>
            </view>
            <view class="status-tag" :class="'status-' + item.status">
              {{ getStatusLabel(item.status) }}
            </view>
          </view>
          
          <view class="card-body">
            <view class="info-row">
              <view class="info-item">
                <text class="info-label">人员</text>
                <text class="info-value">{{ item.personName || '--' }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">药品</text>
                <text class="info-value">{{ item.medicineName || '--' }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">剂量</text>
                <text class="info-value">{{ item.dosagePerTime || '--' }} {{ item.dosageUnit || '' }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">频次</text>
                <text class="info-value">{{ getFrequencyLabel(item.frequencyType) }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">开始日期</text>
                <text class="info-value">{{ formatDate(item.startDate) }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">结束日期</text>
                <text class="info-value">{{ item.endDate ? formatDate(item.endDate) : '长期' }}</text>
              </view>
              <view class="info-item info-item-full" v-if="item.timeSlots">
                <text class="info-label">服药时间</text>
                <text class="info-value">{{ parseTimeSlots(item.timeSlots).join('、') }}</text>
              </view>
            </view>
          </view>
          
          <view class="operate" @click.stop>
            <view class="btn-edit" v-if="item.status === 1" @click="handlePause(item)">
              <uni-icons type="pausemini" size="16" color="#fa8c16"></uni-icons>
              <text>暂停</text>
            </view>
            <view class="btn-edit" v-if="item.status === 2" @click="handleResume(item)">
              <uni-icons type="right" size="16" color="#52c41a"></uni-icons>
              <text>恢复</text>
            </view>
            <view class="btn-edit" v-if="item.status !== 3" @click="handleEnd(item)">
              <uni-icons type="checkbox" size="16" color="#667eea"></uni-icons>
              <text>结束</text>
            </view>
            <view class="btn-edit" v-show="auth.hasPermi('health:medicationPlan:edit')" @click="handleEdit(item)">
              <uni-icons type="compose" size="16" color="#667eea"></uni-icons>
              <text>修改</text>
            </view>
            <view class="btn-delete" v-show="auth.hasPermi('health:medicationPlan:remove')" @click="handleDelete(item)">
              <uni-icons type="trash" size="16" color="#f5576c"></uni-icons>
              <text>删除</text>
            </view>
          </view>
        </view>
      </u-list-item>
      <u-loadmore :status="status" loadingIcon="semicircle" height="88" fontSize="32rpx" @loadmore="loadmore" />
    </u-list>
    <suspend></suspend>
  </view>
</template>

<script setup>
import { listMedicationPlan, delMedicationPlan, pauseMedicationPlan, resumeMedicationPlan, endMedicationPlan } from '@/api/health/medicationPlan'
import { listPerson } from '@/api/health/person'
import { onLoad, onShow } from "@dcloudio/uni-app"
import auth from "@/plugins/auth"
import { reactive, toRefs, ref } from "vue"

const pageNum = ref(1)
const listData = ref([])
const isShow = ref(false)
const status = ref('loadmore')
const personList = ref([])
const statusList = ref([
  { label: '进行中', value: 1 },
  { label: '已暂停', value: 2 },
  { label: '已结束', value: 3 }
])

const data = reactive({
  filterPanel: false,
  queryParams: {
    keys: null,
    personId: null,
    status: null
  }
})
const { filterPanel, queryParams } = toRefs(data)

onLoad(() => {
  getPersonList()
  getList()
})

onShow(() => {
  if (isShow.value) {
    listData.value = []
    pageNum.value = 1
    getList()
    isShow.value = false
  }
})

function getPersonList() {
  listPerson({ pageNum: 1, pageSize: 100 }).then(res => {
    personList.value = res.rows || []
  })
}

function getStatusLabel(s) {
  const map = { 1: '进行中', 2: '已暂停', 3: '已结束' }
  return map[s] || '未知'
}

function getFrequencyLabel(type) {
  const map = { 1: '每天', 2: '每周', 3: '隔天', 4: '自定义' }
  return map[type] || '--'
}

function formatDate(date) {
  if (!date) return '--'
  if (Array.isArray(date)) {
    return `${date[0]}-${String(date[1]).padStart(2, '0')}-${String(date[2]).padStart(2, '0')}`
  }
  if (typeof date === 'string') return date.substring(0, 10)
  return '--'
}

function parseTimeSlots(timeSlots) {
  if (!timeSlots) return []
  try {
    return typeof timeSlots === 'string' ? JSON.parse(timeSlots) : timeSlots
  } catch (e) {
    return []
  }
}

function selectStatus(item) {
  queryParams.value.status = queryParams.value.status == item.value ? null : item.value
}

function selectPerson(item) {
  queryParams.value.personId = queryParams.value.personId == item.id ? null : item.id
}

function loadmore() {
  pageNum.value += 1
  if (status.value == 'loadmore') {
    getList()
  }
}

function getList() {
  status.value = 'loading'
  listMedicationPlan({ pageSize: 10, pageNum: pageNum.value, ...queryParams.value, keyword: queryParams.value.keys }).then(res => {
    listData.value = listData.value.concat(res.rows || [])
    if (listData.value.length < res.total) {
      status.value = 'loadmore'
    } else {
      status.value = 'nomore'
    }
  }).catch(() => {
    status.value = 'nomore'
  })
}

function searchSubmit() {
  pageNum.value = 1
  listData.value = []
  getList()
  filterPanel.value = false
}

function searchBlur() {
  pageNum.value = 1
  listData.value = []
  getList()
}

function resetQuery() {
  queryParams.value.keys = null
  queryParams.value.personId = null
  queryParams.value.status = null
}

function handleAdd() {
  uni.navigateTo({ url: '/pages/health/medicationPlan/addEdit' })
  isShow.value = true
}

function handleEdit(item) {
  uni.navigateTo({ url: `/pages/health/medicationPlan/addEdit?id=${item.id}` })
  isShow.value = true
}

function handlePause(item) {
  uni.showModal({
    title: '确认暂停',
    content: '确定要暂停该用药计划吗？',
    confirmColor: '#667eea',
    success: function (res) {
      if (res.confirm) {
        pauseMedicationPlan(item.id).then(() => {
          uni.showToast({ title: '暂停成功', icon: 'success' })
          pageNum.value = 1
          listData.value = []
          getList()
        })
      }
    }
  })
}

function handleResume(item) {
  resumeMedicationPlan(item.id).then(() => {
    uni.showToast({ title: '恢复成功', icon: 'success' })
    pageNum.value = 1
    listData.value = []
    getList()
  })
}

function handleEnd(item) {
  uni.showModal({
    title: '确认结束',
    content: '确认结束该用药计划？结束后将不再生成用药记录。',
    confirmColor: '#667eea',
    success: function (res) {
      if (res.confirm) {
        endMedicationPlan(item.id).then(() => {
          uni.showToast({ title: '已结束', icon: 'success' })
          pageNum.value = 1
          listData.value = []
          getList()
        })
      }
    }
  })
}

function handleDelete(item) {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这条记录吗？',
    confirmText: '删除',
    cancelText: '取消',
    confirmColor: '#f5576c',
    success: function (res) {
      if (res.confirm) {
        delMedicationPlan(item.id).then(() => {
          uni.showToast({ title: '删除成功', icon: 'success' })
          pageNum.value = 1
          listData.value = []
          getList()
        })
      }
    }
  })
}
</script>

<style lang="scss" scoped>
@import '@/styles/health-common.scss';

// 筛选面板位置补充（单行模式）
.search-view .filter-panel {
  top: 96rpx;
}

// 用药计划特有状态色
.status-tag {
  &.status-active, &.status-1 {
    background: rgba(82, 196, 26, 0.2);
    color: #52c41a;
  }
  &.status-ended, &.status-2 {
    background: rgba(250, 140, 22, 0.2);
    color: #fa8c16;
  }
  &.status-paused, &.status-3 {
    background: rgba(144, 147, 153, 0.2);
    color: #909399;
  }
}
</style>
