<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="personId" required @click="showPerson = true">
            <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="diseaseName" required>
            <u--input v-model="form.diseaseName" placeholder="请输入疾病名称"
              inputAlign="left" :customStyle="inputBaseStyle"></u--input>
          </u-form-item>
          <u-form-item label="疾病编码" prop="diseaseCode">
            <u--input v-model="form.diseaseCode" placeholder="ICD-10编码（可选）"
              inputAlign="left" :customStyle="inputBaseStyle"></u--input>
          </u-form-item>
          <u-form-item label="确诊日期" prop="diagnosisDate" @click="showDatePicker = true">
            <view class="input-with-arrow">
              <u--input v-model="form.diagnosisDate" readonly disabledColor="#ffffff" placeholder="请选择确诊日期"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item label="疾病状态" prop="diseaseStatus" required @click="showStatus = true">
            <view class="input-with-arrow">
              <u--input v-model="form.diseaseStatusName" readonly disabledColor="#ffffff" placeholder="请选择状态"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item label="主治医生" prop="mainDoctor">
            <u--input v-model="form.mainDoctor" placeholder="请输入主治医生"
              inputAlign="left" :customStyle="inputBaseStyle"></u--input>
          </u-form-item>
          <u-form-item label="就诊医院" prop="hospital">
            <u--input v-model="form.hospital" placeholder="请输入就诊医院"
              inputAlign="left" :customStyle="inputBaseStyle"></u--input>
          </u-form-item>
          <u-form-item label="科室" prop="department">
            <u--input v-model="form.department" placeholder="请输入科室"
              inputAlign="left" :customStyle="inputBaseStyle"></u--input>
          </u-form-item>
          <u-form-item label="诊断结果" prop="notes" labelPosition="top">
            <u--textarea v-model="form.notes" placeholder="请输入诊断结果" inputAlign="left"
              style="border: 2rpx solid #dcdfe6 !important; height: 160rpx;"></u--textarea>
          </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="showStatus" :columns="statusColumns" keyName="label"
      @confirm="statusConfirm" @cancel="showStatus = false"></u-picker>
    <u-datetime-picker :show="showDatePicker" v-model="datePickerValue" mode="date"
      @confirm="dateConfirm" @cancel="showDatePicker = false" @close="showDatePicker = false"></u-datetime-picker>
  </view>
</template>

<script setup>
import { getChronicDisease, addChronicDisease, updateChronicDisease } from '@/api/health/chronicDisease'
import { listPerson } from '@/api/health/person'
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 showStatus = ref(false)
const showDatePicker = ref(false)
const datePickerValue = ref(Number(new Date()))

const personColumns = ref([[]])
const statusColumns = ref([[
  { label: '稳定', value: 1 },
  { label: '需关注', value: 2 },
  { label: '急性期', value: 3 }
]])

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,
    diseaseName: null,
    diseaseCode: null,
    diagnosisDate: null,
    diseaseStatus: 1,
    diseaseStatusName: '稳定',
    mainDoctor: null,
    hospital: null,
    department: null,
    notes: null,
    isActive: 1,
    remark: null
  },
  rules: {
    personId: [{ required: true, message: '请选择成员', trigger: 'change' }],
    diseaseName: [{ required: true, message: '疾病名称不能为空', trigger: 'blur' }],
    diseaseStatus: [{ 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)
  }
  loadPersonList()
})

function loadDetail(id) {
  getChronicDisease(id).then(res => {
    const d = res.data
    form.value = { ...form.value, ...d }
    form.value.personName = d.personName || ''
    form.value.diagnosisDate = formatDate(d.diagnosisDate)
    const statusMap = { 1: '稳定', 2: '需关注', 3: '急性期' }
    form.value.diseaseStatusName = statusMap[d.diseaseStatus] || ''
  })
}

function formatDate(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() {
  listPerson({ pageNum: 1, pageSize: 100 }).then(res => {
    personColumns.value = [res.rows || []]
  })
}

function personConfirm(e) {
  const item = e.value[0]
  form.value.personId = item.id
  form.value.personName = item.name
  showPerson.value = false
}

function statusConfirm(e) {
  const item = e.value[0]
  form.value.diseaseStatus = item.value
  form.value.diseaseStatusName = item.label
  showStatus.value = false
}

function dateConfirm(e) {
  form.value.diagnosisDate = dayjs(e.value).format('YYYY-MM-DD')
  showDatePicker.value = false
}

function submit() {
  proxy.$refs['uForm'].validate().then(() => {
    const submitData = { ...form.value }
    delete submitData.personName
    delete submitData.diseaseStatusName
    delete submitData.createTime
    delete submitData.updateTime

    if (submitData.id) {
      updateChronicDisease(submitData).then(() => {
        uni.showToast({ title: '修改成功', icon: 'success' })
        setTimeout(() => uni.navigateBack(), 1500)
      })
    } else {
      addChronicDisease(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: #fff; font-size: 28rpx; font-weight: 600;
    display: flex; align-items: center;
    &::before { content: ''; width: 6rpx; height: 28rpx; background: #fff; 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; }
    }
  }
}
</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>
