<template>
  <view class="container" style="paddingBottom: 120rpx;">
    <view class="section">
      <view class="section-title">{{ title }}</view>
      <view class="form-view">
        <u--form labelPosition="left" :model="form" :rules="rules" ref="uForm" label-width="180rpx"
          :labelStyle="{ color: '#333333', fontSize: '30rpx', marginRight: '24rpx' }">
          
          <u-form-item label="计划名称" prop="planName">
            <u--input v-model="form.planName" placeholder="请填写计划名称（可选）" inputAlign="left"
              :customStyle="inputBaseStyle"></u--input>
          </u-form-item>
          
          <u-form-item label="人员" prop="personName" required @click="handlePerson">
            <view class="input-with-arrow">
              <u--input v-model="form.personName" disabled disabledColor="#ffffff" placeholder="请选择人员"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          
          <u-form-item label="药品" prop="medicineName" required @click="handleMedicine">
            <view class="input-with-arrow">
              <u--input v-model="form.medicineName" disabled disabledColor="#ffffff" placeholder="请选择药品"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          
          <u-form-item label="每次剂量" prop="dosage" required>
            <view class="dosage-input">
              <u--input v-model="form.dosage" type="digit" placeholder="剂量" inputAlign="left"
                :customStyle="inputBaseStyle" style="flex: 1"></u--input>
              <u--input v-model="form.dosageUnit" disabled disabledColor="#ffffff" placeholder="单位"
                inputAlign="left" :customStyle="inputBaseStyle" style="width: 160rpx; margin-left: 16rpx"></u--input>
            </view>
          </u-form-item>
          
          <u-form-item label="每日次数" prop="frequency" required>
            <view class="stepper">
              <view class="stepper-btn" @click="decreaseFrequency">-</view>
              <text class="stepper-value">{{ form.frequency }}</text>
              <view class="stepper-btn" @click="increaseFrequency">+</view>
            </view>
          </u-form-item>
          
          <u-form-item label="频率类型" prop="frequencyTypeName" @click="handleFrequencyType">
            <view class="input-with-arrow">
              <u--input v-model="form.frequencyTypeName" disabled disabledColor="#ffffff" placeholder="请选择频率类型"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          
          <u-form-item label="服药时间点" prop="timePointsText">
            <view class="time-points-box">
              <view v-for="(time, idx) in form.timePointList" :key="idx" class="time-tag">
                <text>{{ time }}</text>
                <uni-icons type="closeempty" size="14" color="#909399" @click="removeTimePoint(idx)"></uni-icons>
              </view>
              <view class="time-add" @click="showTimePicker = true">
                <uni-icons type="plusempty" size="16" color="#667eea"></uni-icons>
              </view>
            </view>
          </u-form-item>
          
          <u-form-item label="开始日期" prop="startDate" required @click="showStartDate = true">
            <view class="input-with-arrow">
              <u--input v-model="form.startDate" disabled disabledColor="#ffffff" placeholder="请选择开始日期"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          
          <u-form-item label="结束日期" prop="endDate" @click="showEndDate = true">
            <view class="input-with-arrow">
              <u--input v-model="form.endDate" disabled disabledColor="#ffffff" placeholder="可选，不填则长期"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          
          <u-form-item label="启用提醒">
            <u-switch v-model="form.reminderEnabled" activeValue="1" inactiveValue="0"
              activeColor="#667eea" inactiveColor="#dcdfe6"></u-switch>
          </u-form-item>
          
          <u-form-item label="提前提醒" v-if="form.reminderEnabled === '1'">
            <view class="stepper">
              <view class="stepper-btn" @click="form.reminderMinutes = Math.max(0, form.reminderMinutes - 5)">-</view>
              <text class="stepper-value">{{ form.reminderMinutes }}分钟</text>
              <view class="stepper-btn" @click="form.reminderMinutes += 5">+</view>
            </view>
          </u-form-item>
          
          <u-form-item label="备注" prop="remark" labelPosition="top">
            <u--textarea v-model="form.remark" placeholder="请填写备注" inputAlign="left"
              style="border: 2rpx solid #dcdfe6 !important; height: 160rpx;"></u--textarea>
          </u-form-item>
        </u--form>
        
        <view class="form-btn">
          <u-button type="primary" text="提交" @click="submit"></u-button>
        </view>
      </view>
    </view>
    
    <u-toast ref="uToast"></u-toast>
    
    <!-- 选择器 -->
    <u-picker :show="showPersonPicker" :columns="personPickerList" keyName="name" @cancel="showPersonPicker = false"
      @confirm="onPersonConfirm"></u-picker>
    <u-picker :show="showMedicinePicker" :columns="medicinePickerList" keyName="shortNameBrand" @cancel="showMedicinePicker = false"
      @confirm="onMedicineConfirm"></u-picker>
    <u-picker :show="showFrequencyTypePicker" :columns="frequencyTypeList" keyName="label" @cancel="showFrequencyTypePicker = false"
      @confirm="onFrequencyTypeConfirm"></u-picker>
    <u-datetime-picker :show="showStartDate" mode="date" @cancel="showStartDate = false"
      @confirm="onStartDateConfirm" :maxDate="maxDate"></u-datetime-picker>
    <u-datetime-picker :show="showEndDate" mode="date" @cancel="showEndDate = false"
      @confirm="onEndDateConfirm"></u-datetime-picker>
    <u-datetime-picker :show="showTimePicker" mode="time" @cancel="showTimePicker = false"
      @confirm="onTimeConfirm"></u-datetime-picker>
  </view>
</template>

<script setup>
import { getMedicationPlan, addMedicationPlan, updateMedicationPlan } from '@/api/health/medicationPlan'
import { listMedicineBasic } from '@/api/health/medicineBasic'
import { listPerson } from '@/api/health/person'
import { onLoad, onReady } from "@dcloudio/uni-app"
import { reactive, toRefs, ref, computed, getCurrentInstance } from "vue"
import dayjs from 'dayjs'

const { proxy } = getCurrentInstance()
const title = ref("新增用药计划")
const planId = ref(null)
const copyFlag = ref(false)

const inputBaseStyle = {
  background: '#ffffff',
  border: '2rpx solid #dcdfe6',
  borderRadius: '8rpx',
  padding: '0 24rpx',
  height: '68rpx',
  width: '100%',
  boxSizing: 'border-box'
}

const data = reactive({
  form: {
    id: null,
    personId: null,
    personName: null,
    medicineId: null,
    medicineName: null,
    dosage: 1,
    dosageUnit: '片',
    frequency: 3,
    frequencyType: '1',
    frequencyTypeName: '每日',
    timePointList: ['08:00', '12:00', '18:00'],
    startDate: null,
    endDate: null,
    reminderEnabled: '0',
    reminderMinutes: 15,
    remark: null
  },
  rules: {
    personName: [{ required: true, message: '请选择人员', trigger: 'change' }],
    medicineName: [{ required: true, message: '请选择药品', trigger: 'change' }],
    dosage: [{ required: true, message: '请输入剂量', trigger: 'blur' }],
    frequency: [{ required: true, message: '请设置每日次数', trigger: 'change' }],
    startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }]
  }
})

const { form, rules } = toRefs(data)

// 选择器相关
const showPersonPicker = ref(false)
const showMedicinePicker = ref(false)
const showFrequencyTypePicker = ref(false)
const showStartDate = ref(false)
const showEndDate = ref(false)
const showTimePicker = ref(false)

const personList = ref([])
const medicineList = ref([])
const frequencyTypeList = ref([
  [{ value: '1', label: '每日' }],
  [{ value: '2', label: '隔日' }],
  [{ value: '3', label: '每周' }],
  [{ value: '4', label: '自定义' }]
])

const maxDate = ref(Date.now() + 365 * 24 * 60 * 60 * 1000)

const personPickerList = computed(() => [personList.value])
const medicinePickerList = computed(() => [medicineList.value])

onLoad((options) => {
  if (options.id) {
    planId.value = options.id
    if (options.flag === 'copy') {
      copyFlag.value = true
      title.value = "复制用药计划"
    } else {
      title.value = "编辑用药计划"
    }
  }
  getPersonList()
  getMedicineList()
})

onReady(() => {
  if (planId.value) {
    getDetail()
  }
})

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

function getMedicineList() {
  listMedicineBasic({ pageNum: 1, pageSize: 1000 }).then(res => {
    medicineList.value = (res.rows || []).map(item => ({
      ...item,
      shortNameBrand: `${item.shortName}-${item.brand}`
    }))
  })
}

function getDetail() {
  getMedicationPlan(planId.value).then(res => {
    form.value = {
      ...res.data,
      personName: res.data.personName,
      medicineName: res.data.shortName ? `${res.data.shortName}-${res.data.brand}` : null,
      frequencyTypeName: getFrequencyTypeName(res.data.frequencyType),
      timePointList: res.data.timePoints ? JSON.parse(res.data.timePoints) : [],
      startDate: res.data.startDate ? res.data.startDate.substring(0, 10) : null,
      endDate: res.data.endDate ? res.data.endDate.substring(0, 10) : null
    }
    if (copyFlag.value) {
      form.value.id = null
      title.value = "复制用药计划"
    }
  })
}

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

function handlePerson() { showPersonPicker.value = true }
function handleMedicine() { showMedicinePicker.value = true }
function handleFrequencyType() { showFrequencyTypePicker.value = true }

function onPersonConfirm(e) {
  const selected = e.value[0]
  form.value.personId = selected.id
  form.value.personName = selected.name
  showPersonPicker.value = false
}

function onMedicineConfirm(e) {
  const selected = e.value[0]
  form.value.medicineId = selected.id
  form.value.medicineName = selected.shortNameBrand
  form.value.dosageUnit = selected.unit || '片'
  showMedicinePicker.value = false
}

function onFrequencyTypeConfirm(e) {
  const selected = e.value[0]
  form.value.frequencyType = selected.value
  form.value.frequencyTypeName = selected.label
  showFrequencyTypePicker.value = false
}

function onStartDateConfirm(e) {
  form.value.startDate = dayjs(e.value).format('YYYY-MM-DD')
  showStartDate.value = false
}

function onEndDateConfirm(e) {
  form.value.endDate = dayjs(e.value).format('YYYY-MM-DD')
  showEndDate.value = false
}

function onTimeConfirm(e) {
  const time = dayjs(e.value).format('HH:mm')
  if (!form.value.timePointList.includes(time)) {
    form.value.timePointList.push(time)
    form.value.timePointList.sort()
  }
  showTimePicker.value = false
}

function removeTimePoint(idx) {
  form.value.timePointList.splice(idx, 1)
}

function decreaseFrequency() {
  if (form.value.frequency > 1) form.value.frequency--
}

function increaseFrequency() {
  if (form.value.frequency < 10) form.value.frequency++
}

function submit() {
  proxy.$refs.uForm.validate().then(() => {
    const data = {
      ...form.value,
      timePoints: JSON.stringify(form.value.timePointList)
    }
    
    if (form.value.id && !copyFlag.value) {
      updateMedicationPlan(data).then(() => {
        proxy.$refs.uToast.show({ message: '修改成功', type: 'success' })
        setTimeout(() => uni.navigateBack(), 1000)
      })
    } else {
      addMedicationPlan(data).then(() => {
        proxy.$refs.uToast.show({ message: '新增成功', type: 'success' })
        setTimeout(() => uni.navigateBack(), 1000)
      })
    }
  }).catch(err => {
    console.log('验证失败', err)
  })
}
</script>

<style lang="scss" scoped>
.container {
  background: #f5f7fa;
  min-height: 100vh;
}

.section {
  background: #fff;
  margin: 24rpx;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
  
  .section-title {
    padding: 32rpx 24rpx 16rpx;
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    border-bottom: 1rpx solid #f0f2f5;
  }
  
  .form-view {
    padding: 24rpx;
  }
}

.input-with-arrow {
  position: relative;
  width: 100%;
  
  .arrow-icon {
    position: absolute;
    right: 24rpx;
    top: 50%;
    transform: translateY(-50%);
    color: #909399;
    font-size: 24rpx;
  }
}

.dosage-input {
  display: flex;
  width: 100%;
}

.stepper {
  display: flex;
  align-items: center;
  
  .stepper-btn {
    width: 64rpx;
    height: 64rpx;
    background: #f5f7fa;
    border-radius: 8rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 36rpx;
    color: #667eea;
    font-weight: 600;
    
    &:active { background: #e8edf3; }
  }
  
  .stepper-value {
    min-width: 120rpx;
    text-align: center;
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
  }
}

.time-points-box {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  
  .time-tag {
    display: flex;
    align-items: center;
    padding: 12rpx 20rpx;
    background: rgba(102, 126, 234, 0.1);
    border-radius: 8rpx;
    border: 1rpx solid rgba(102, 126, 234, 0.3);
    
    text {
      font-size: 28rpx;
      color: #667eea;
      margin-right: 8rpx;
    }
  }
  
  .time-add {
    width: 64rpx;
    height: 64rpx;
    background: rgba(102, 126, 234, 0.08);
    border: 2rpx dashed #667eea;
    border-radius: 8rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.form-btn {
  margin-top: 40rpx;
  padding: 24rpx;
  
  :deep(.u-button) {
    height: 88rpx;
    border-radius: 12rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
  }
}
</style>