<template>
  <view class="container" style="paddingBottom:1rpx;">
    <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="personId" required @click="handlePersonPick">
            <view class="input-with-arrow">
              <u--input v-model="form.personName" readonly disabledColor="#ffffff" placeholder="请选择人员"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item label="药品" prop="medicineId" required @click="handleMedicinePick">
            <view class="input-with-arrow">
              <u--input v-model="form.medicineDisplayName" readonly disabledColor="#ffffff" placeholder="请选择药品"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item label="慢性疾病" prop="chronicDiseaseId" @click="handleDiseasePick">
            <view class="input-with-arrow">
              <u--input v-model="form.diseaseName" readonly disabledColor="#ffffff" placeholder="请选择慢性疾病（可选）"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item label="每次剂量" prop="dosagePerTime" required>
            <view style="display:flex;align-items:center;gap:10rpx;width:100%">
              <u--input v-model="form.dosagePerTime" type="digit" placeholder="剂量"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
              <view @click="handleUnitPick" style="min-width:120rpx">
                <u--input v-model="form.dosageUnit" readonly disabledColor="#ffffff" placeholder="单位"
                  inputAlign="center" :customStyle="inputBaseStyle"></u--input>
              </view>
            </view>
          </u-form-item>
          <u-form-item label="频次类型" prop="frequencyType" @click="handleFrequencyPick">
            <view class="input-with-arrow">
              <u--input v-model="form.frequencyName" readonly disabledColor="#ffffff" placeholder="请选择频次类型"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item label="服药时间点" prop="timeSlots" labelPosition="top">
            <view class="time-slots-container">
              <view v-for="(time, idx) in form.timePointList" :key="idx" class="time-tag">
                <text>{{ time }}</text>
                <text class="time-tag-close" @click="removeTimePoint(idx)">×</text>
              </view>
              <view class="time-add-btn" @click="showTimePicker = true">
                <uni-icons type="plusempty" size="14" color="#667eea"></uni-icons>
                <text>添加</text>
              </view>
            </view>
          </u-form-item>
          <u-form-item label="开始日期" prop="startDate" required @click="openDatePicker('start')">
            <view class="input-with-arrow">
              <u--input v-model="form.startDate" readonly 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="openDatePicker('end')">
            <view class="input-with-arrow">
              <u--input v-model="form.endDate" readonly disabledColor="#ffffff" placeholder="请选择结束日期（可选）"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item label="启用提醒" prop="remindEnabled">
            <u-switch v-model="form.remindEnabled" activeValue="1" inactiveValue="0"></u-switch>
          </u-form-item>
          <u-form-item label="通知家属" prop="notifyFamily">
            <u-switch v-model="form.notifyFamily" activeValue="1" inactiveValue="0"></u-switch>
          </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 itemHeight="88" :show="showPerson" :columns="personColumns" keyName="name"
      @confirm="personConfirm" @cancel="showPerson = false"></u-picker>
    <u-picker itemHeight="88" :show="showMedicine" :columns="medicineColumns" keyName="displayName"
      @confirm="medicineConfirm" @cancel="showMedicine = false"></u-picker>
    <u-picker itemHeight="88" :show="showDisease" :columns="diseaseColumns" keyName="diseaseName"
      @confirm="diseaseConfirm" @cancel="showDisease = false"></u-picker>
    <u-picker itemHeight="88" :show="showUnit" :columns="unitColumns" keyName="dictLabel"
      @confirm="unitConfirm" @cancel="showUnit = false"></u-picker>
    <u-picker itemHeight="88" :show="showFrequency" :columns="frequencyColumns" keyName="label"
      @confirm="frequencyConfirm" @cancel="showFrequency = false"></u-picker>
    <u-datetime-picker :show="showDatePicker" v-model="datePickerValue" mode="date"
      @confirm="datePickerConfirm" @cancel="showDatePicker = false" @close="showDatePicker = false"></u-datetime-picker>
    <u-datetime-picker :show="showTimePicker" v-model="timePickerValue" mode="time"
      @confirm="timePickerConfirm" @cancel="showTimePicker = false" @close="showTimePicker = false"></u-datetime-picker>
  </view>
</template>

<script setup>
import { getMedicationPlan, addMedicationPlan, updateMedicationPlan } from '@/api/health/medicationPlan'
import { listPerson } from '@/api/health/person'
import { listMedicineBasic } from '@/api/health/medicineBasic'
import { listChronicDiseaseByMember } from '@/api/health/chronicDisease'
import { getDicts } from '@/api/system/dict/data.js'
import { onLoad } from "@dcloudio/uni-app"
import dayjs from 'dayjs'
import { reactive, toRefs, ref, getCurrentInstance } from "vue"

const { proxy } = getCurrentInstance()
const title = ref('用药计划-新增')

const showPerson = ref(false)
const showMedicine = ref(false)
const showDisease = ref(false)
const showUnit = ref(false)
const showFrequency = ref(false)
const showDatePicker = ref(false)
const showTimePicker = ref(false)
const datePickerValue = ref(Number(new Date()))
const timePickerValue = ref('08:00')
const datePickerTarget = ref('start')

const personColumns = ref([[]])
const medicineColumns = ref([[]])
const diseaseColumns = ref([[]])
const unitColumns = ref([[]])
const frequencyColumns = ref([[{ label: '每天', value: 1 }, { label: '每周', value: 2 }, { label: '隔天', value: 3 }, { label: '自定义', value: 4 }]])

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,
    planName: null,
    personId: null,
    personName: null,
    chronicDiseaseId: null,
    diseaseName: null,
    medicineId: null,
    medicineDisplayName: null,
    medicineName: null,
    dosagePerTime: 1,
    dosageUnit: '片',
    frequencyType: 1,
    frequencyName: '每天',
    timePointList: ['08:00', '12:00', '18:00'],
    timeSlots: null,
    startDate: null,
    endDate: null,
    remindEnabled: '0',
    notifyFamily: '0',
    remark: null
  },
  rules: {
    personId: [{ required: true, message: '请选择人员', trigger: 'change' }],
    medicineId: [{ required: true, message: '请选择药品', trigger: 'change' }],
    dosagePerTime: [{ required: true, message: '请输入剂量', trigger: 'blur' }],
    startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }]
  }
})
const { form, rules } = toRefs(data)

onLoad((option) => {
  if (option.id) {
    form.value.id = option.id
    title.value = '用药计划-修改'
    loadDetail(option.id)
  } else {
    applyChronicDiseasePrefill(option)
  }
  loadPersonList().then(() => fillPersonName())
  loadMedicineList()
  loadUnitList()
})

function loadDetail(id) {
  getMedicationPlan(id).then(res => {
    const d = res.data
    form.value = { ...form.value, ...d }
    form.value.personName = d.personName || ''
    form.value.medicineDisplayName = d.medicineName || ''
    form.value.diseaseName = d.diseaseName || ''
    form.value.remindEnabled = String(d.remindEnabled || 0)
    form.value.notifyFamily = String(d.notifyFamily || 0)
    // 转换日期
    form.value.startDate = convertDate(d.startDate)
    form.value.endDate = convertDate(d.endDate)
    // 解析时间点
    if (d.timeSlots) {
      try {
        form.value.timePointList = typeof d.timeSlots === 'string' ? JSON.parse(d.timeSlots) : d.timeSlots
      } catch (e) { form.value.timePointList = [] }
    }
    // 频次名称
    const freqMap = { 1: '每天', 2: '每周', 3: '隔天', 4: '自定义' }
    form.value.frequencyName = freqMap[d.frequencyType] || ''
    // 加载慢性疾病列表
    if (d.personId) loadDiseaseList(d.personId)
  })
}

function convertDate(date) {
  if (!date) return null
  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 null
}

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

function loadMedicineList() {
  listMedicineBasic({ pageNum: 1, pageSize: 1000 }).then(res => {
    const list = (res.rows || []).map(item => ({ ...item, displayName: item.shortName + '-' + item.brand }))
    medicineColumns.value = [list]
  })
}

function loadDiseaseList(personId) {
  return listChronicDiseaseByMember(personId).then(res => {
    diseaseColumns.value = [res.data || []]
    return res.data || []
  })
}

function applyChronicDiseasePrefill(option) {
  const personId = option.personId ? Number(option.personId) : null
  const chronicDiseaseId = option.chronicDiseaseId ? Number(option.chronicDiseaseId) : null
  if (!personId || !chronicDiseaseId) {
    return
  }
  const diseaseName = option.diseaseName ? decodeURIComponent(option.diseaseName) : ''
  form.value.personId = personId
  form.value.chronicDiseaseId = chronicDiseaseId
  form.value.diseaseName = diseaseName
  form.value.planName = diseaseName ? `${diseaseName}用药计划` : null
  loadDiseaseList(personId).then((list) => {
    const disease = list.find(item => item.id == chronicDiseaseId)
    if (disease) {
      form.value.diseaseName = disease.diseaseName
    }
  })
}

function fillPersonName() {
  if (!form.value.personId || form.value.personName) {
    return
  }
  const list = personColumns.value[0] || []
  const person = list.find(item => item.id == form.value.personId)
  if (person) {
    form.value.personName = person.name
  }
}

function loadUnitList() {
  getDicts('medical_unit').then(res => {
    unitColumns.value = [res.data || []]
  })
}

function handlePersonPick() { showPerson.value = true }
function handleMedicinePick() { showMedicine.value = true }
function handleDiseasePick() {
  if (!form.value.personId) {
    uni.showToast({ title: '请先选择人员', icon: 'none' })
    return
  }
  showDisease.value = true
}
function handleUnitPick() { showUnit.value = true }
function handleFrequencyPick() { showFrequency.value = true }

function personConfirm(e) {
  const item = e.value[0]
  form.value.personId = item.id
  form.value.personName = item.name
  showPerson.value = false
  // 切换人员后重新加载疾病列表
  form.value.chronicDiseaseId = null
  form.value.diseaseName = null
  loadDiseaseList(item.id)
}

function medicineConfirm(e) {
  const item = e.value[0]
  form.value.medicineId = item.id
  form.value.medicineDisplayName = item.displayName
  form.value.medicineName = item.displayName
  form.value.dosageUnit = item.unit || '片'
  showMedicine.value = false
}

function diseaseConfirm(e) {
  const item = e.value[0]
  form.value.chronicDiseaseId = item.id
  form.value.diseaseName = item.diseaseName
  showDisease.value = false
}

function unitConfirm(e) {
  form.value.dosageUnit = e.value[0].dictLabel
  showUnit.value = false
}

function frequencyConfirm(e) {
  form.value.frequencyType = e.value[0].value
  form.value.frequencyName = e.value[0].label
  showFrequency.value = false
}

function openDatePicker(target) {
  datePickerTarget.value = target
  showDatePicker.value = true
}

function datePickerConfirm(e) {
  const dateStr = dayjs(e.value).format('YYYY-MM-DD')
  if (datePickerTarget.value === 'start') {
    form.value.startDate = dateStr
  } else {
    form.value.endDate = dateStr
  }
  showDatePicker.value = false
}

function timePickerConfirm(e) {
  const timeStr = e.value
  if (timeStr && !form.value.timePointList.includes(timeStr)) {
    form.value.timePointList.push(timeStr)
  }
  showTimePicker.value = false
}

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

function submit() {
  proxy.$refs['uForm'].validate().then(() => {
    const submitData = { ...form.value }
    submitData.timeSlots = JSON.stringify(form.value.timePointList)
    submitData.remindEnabled = parseInt(form.value.remindEnabled)
    submitData.notifyFamily = parseInt(form.value.notifyFamily)
    // 清理展示字段
    delete submitData.personName
    delete submitData.medicineDisplayName
    delete submitData.diseaseName
    delete submitData.frequencyName
    delete submitData.timePointList
    delete submitData.createTime
    delete submitData.updateTime

    if (submitData.id) {
      updateMedicationPlan(submitData).then(() => {
        uni.showToast({ title: '修改成功', icon: 'success' })
        setTimeout(() => uni.navigateBack(), 1500)
      })
    } else {
      addMedicationPlan(submitData).then(() => {
        uni.showToast({ title: '新增成功', icon: 'success' })
        setTimeout(() => uni.navigateBack(), 1500)
      })
    }
  }).catch(() => {
    uni.showToast({ title: '请填写完整信息', icon: 'none' })
  })
}
</script>

<style lang="scss" scoped>
.section {
  margin: 24rpx;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;
  .section-title {
    padding: 16rpx 24rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #ffffff;
    font-size: 28rpx;
    font-weight: 600;
    display: flex;
    align-items: center;
    &::before { content: ''; width: 6rpx; height: 28rpx; background: #ffffff; border-radius: 3rpx; margin-right: 12rpx; }
  }
  .form-view {
    padding: 24rpx;
    .form-btn { padding-top: 16rpx; }
    .input-with-arrow {
      position: relative;
      width: 100%;
      .arrow-icon { position: absolute; right: 20rpx; top: 50%; transform: translateY(-50%); color: #c0c4cc; font-size: 20rpx; pointer-events: none; }
    }
  }
}
.time-slots-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
  padding: 16rpx 0;
  .time-tag {
    display: flex;
    align-items: center;
    gap: 8rpx;
    padding: 8rpx 20rpx;
    background: rgba(102, 126, 234, 0.1);
    border: 1rpx solid rgba(102, 126, 234, 0.3);
    border-radius: 24rpx;
    font-size: 26rpx;
    color: #667eea;
    .time-tag-close { font-size: 32rpx; color: #f56c6c; }
  }
  .time-add-btn {
    display: flex;
    align-items: center;
    gap: 6rpx;
    padding: 8rpx 20rpx;
    background: rgba(102, 126, 234, 0.08);
    border: 2rpx dashed rgba(102, 126, 234, 0.4);
    border-radius: 24rpx;
    font-size: 26rpx;
    color: #667eea;
  }
}
</style>

<style lang="scss">
.form-btn .u-button {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
  border: none !important;
  border-radius: 24rpx !important;
  height: 80rpx !important;
  box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.4) !important;
}
.form-btn .u-button__text {
  font-size: 30rpx !important;
  font-weight: 500 !important;
}
</style>
