<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="140rpx"
        :labelStyle="{ color: '#333333', fontSize: '30rpx', marginRight: '24rpx' }">
        <u-form-item label="人员姓名" prop="personName" required @click="handlePerson">
          <view class="input-with-arrow">
            <u--input v-model="form.personName" readonly disabledColor="#ffffff" placeholder="请选择人员"
              inputAlign="left" :customStyle="getInputStyle('personName')"></u--input>
            <text class="arrow-icon">▼</text>
          </view>
        </u-form-item>
        <u-form-item label="档案名称" prop="name" required >
            <u--input v-model="form.name"  placeholder="请填写档案名称"
              inputAlign="left" :customStyle="getInputStyle('name')"></u--input>
          </u-form-item>
        <u-form-item label="类型" prop="typeName" required @click="handleType">
          <view class="input-with-arrow">
            <u--input v-model="form.typeName" readonly disabledColor="#ffffff" placeholder="请选择类型"
              inputAlign="left" :customStyle="getInputStyle('typeName')"></u--input>
            <text class="arrow-icon">▼</text>
          </view>
          </u-form-item>
          <u-form-item label="档案状态" prop="stateName" required @click="handleState">
            <view class="input-with-arrow">
              <u--input v-model="form.stateName" readonly disabledColor="#ffffff" placeholder="请选择档案状态"
                inputAlign="left" :customStyle="getInputStyle('stateName')"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item label="发生时间" prop="occurTime" required @click="selectOccurTime()">
            <view class="input-with-arrow">
              <u--input v-model="form.occurTime" readonly disabledColor="#ffffff" placeholder="请选择发生时间" inputAlign="left" :customStyle="getInputStyle('occurTime')"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
        </u-form-item>
          <u-form-item label="发生原因"  prop="etiologyName" required @click="handleEtiology">
            <view class="input-with-arrow">
              <u--input v-model="form.etiologyName" readonly disabledColor="#ffffff" placeholder="请选择发生原因"
                inputAlign="left" :customStyle="getInputStyle('etiologyName')"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item label="康复时间" prop="rehabilitationTime"  @click="selectRehabilitationTime()">
            <view class="input-with-arrow">
              <u--input v-model="form.rehabilitationTime" readonly disabledColor="#ffffff" placeholder="请选择康复时间" inputAlign="left" :customStyle="getInputStyle('rehabilitationTime')"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
        </u-form-item>
          <u-form-item label="初期症状" prop="initialSymptoms" required >
              <u--textarea v-model="form.initialSymptoms" placeholder="请填写初期症状" inputAlign="left" style="border: 2rpx solid #dcdfe6 !important; height: 160rpx;" :customStyle="getTextareaStyle('initialSymptoms')"></u--textarea>
          </u-form-item>
          <u-form-item label="中期症状" prop="mediumTermSymptoms"  >
              <u--textarea v-model="form.mediumTermSymptoms" placeholder="请填写中期症状" inputAlign="left" style="border: 2rpx solid #dcdfe6 !important; height: 160rpx;" :customStyle="getTextareaStyle('mediumTermSymptoms')"></u--textarea>
          </u-form-item>
          <u-form-item label="后期症状" prop="laterStageSymptoms"  >
              <u--textarea v-model="form.laterStageSymptoms" placeholder="请填写后期症状" inputAlign="left" style="border: 2rpx solid #dcdfe6 !important; height: 160rpx;" :customStyle="getTextareaStyle('laterStageSymptoms')"></u--textarea>
          </u-form-item>
         
        <!-- <u-form-item label="备注" prop="remark"  labelPosition="top">
          <u--textarea v-model="form.remark" placeholder="请填写备注" border="none" autoHeight inputAlign="right" count
            maxlength="2000" style="padding:18rpx 0;"></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="personList" keyName="name" @cancel="handlePersonCancel"
      @confirm="handlePersonConfirm"></u-picker>
      <u-picker itemHeight="88" :show="showState" :columns="stateList" keyName="dictLabel" @cancel="handleStateCancel"
        @confirm="handleStateConfirm"></u-picker>

        <u-picker itemHeight="88" :show="showEtiology" :columns="etiologyList" keyName="dictLabel" @cancel="handleEtiologyCancel"
        @confirm="handleEtiologyConfirm"></u-picker>

        <u-picker itemHeight="88" :show="showType" :columns="typeList" keyName="dictLabel" @cancel="handleTypeCancel"
        @confirm="handleTypeConfirm"></u-picker>
      <u-datetime-picker
			:show="occurTimeShow"
			mode="datetime"
      ref="occurTimeRef" 
			@cancel="occurTimeShow=false"
			@confirm="occurTimeConfirm"
			itemHeight="88"
		></u-datetime-picker>

    <u-datetime-picker
			:show="rehabilitationTimeShow"
			mode="datetime"
      ref="rehabilitationTimeRef" 
			@cancel="rehabilitationTimeShow=false"
			@confirm="rehabilitationTimeConfirm"
			itemHeight="88"
		></u-datetime-picker>
  </view>
</template>

<script setup>
import {getHealthRecord, addHealthRecord, updateHealthRecord } from '@/api/health/healthRecord'
import { listPerson, getPerson } from '@/api/health/person'
const { proxy } = getCurrentInstance()
  import { getDicts } from '@/api/system/dict/data.js'
import dayjs from 'dayjs'
import {onLoad,onReady} from "@dcloudio/uni-app";
  // 计算属性与监听属性是在vue中而非uniap中 需要注意！！！
import {reactive ,toRefs,ref,computed ,getCurrentInstance }from "vue";

// 错误字段
const errorFields = ref([])

// 输入框基础样式
const inputBaseStyle = {
  background: '#ffffff',
  border: '2rpx solid #dcdfe6',
  borderRadius: '8rpx',
  padding: '0 24rpx',
  height: '68rpx',
  width: '100%',
  boxSizing: 'border-box'
}

// 输入框错误样式
const inputErrorStyle = {
  background: '#fef0f0',
  border: '2rpx solid #f56c6c',
  borderRadius: '8rpx',
  padding: '0 24rpx',
  height: '68rpx',
  width: '100%',
  boxSizing: 'border-box'
}

// 根据字段名获取输入框样式
const getInputStyle = (field) => {
  return errorFields.value.includes(field) ? inputErrorStyle : inputBaseStyle
}
// 输入框基础样式
const textareaBaseStyle = {
  background: '#ffffff',
  border: '2rpx solid #dcdfe6',
}

// 输入框错误样式
const textareaErrorStyle = {
  background: '#fef0f0',
  border: '2rpx solid #f56c6c'
}

// 根据字段名获取输入框样式
const getTextareaStyle = (field) => {
  return errorFields.value.includes(field) ? textareaErrorStyle : textareaBaseStyle
}

const occurTimeShow = ref(false)
const showPerson = ref(false)
const title = ref("健康档案")
const personList = ref([])

const typeList = ref([])
const showType = ref(false)

const stateList = ref([])
const showState = ref(false)

const etiologyList = ref([])
const showEtiology = ref(false)

const rehabilitationTimeShow = ref(false)

const data = reactive({
form: {
  id: null,
    name: null,
    type: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    remark: null,
    occurTime: null,
    rehabilitationTime: null,
    initialSymptoms: null,
    mediumTermSymptoms: null,
    laterStageSymptoms: null,
    etiology: null,
    personId: null,
    state: '1',
    stateName: '建档中'
},
queryPersonParams: {
  pageNum: 1,
  status: '1',
  pageSize: 1000
},
rules: {
  name: [{ required: true, message: '档案名称不能为空', trigger:['change', 'blur'] }],
  personName: [{ required: true, message: '人员姓名不能为空', trigger: ['change', 'blur'] }],
  occurTime: [{ required: true, message: '发生时间不能为空', trigger: ['change', 'blur'] }],
  typeName: [{ required: true, message: '类型不能为空', trigger: ['change', 'blur'] }],
  etiologyName: [{ required: true, message: '发生原因不能为空', trigger: ['change', 'blur'] }],
  stateName: [{ required: true, message: '状态不能为空', trigger: ['change', 'blur'] }],
  initialSymptoms: [{ required: true, message: '初期症状不能为空', trigger: ['change', 'blur'] }]
}
})
const { form, queryPersonParams, rules} = toRefs(data)


onLoad((option) => {
     form.value.id = option.id
     if(form.value.id!=null){
      title.value="健康档案-修改"
     }else{
      title.value="健康档案-新增"
     }
    getData()
})
onReady(() => {
     form.value.occurTime = dayjs(new Date().getTime()).format("YYYY-MM-DD HH:mm:ss")
})
function dictStr(val, arr) {
      let str = ''
      arr.map(item => {
        if (item.dictValue === val) {
          str = item.dictLabel
        }
      })
      return str
 }
function  getData() {
    listPerson(queryPersonParams.value).then((response) => {
     personList.value = [response.rows] 
     if(response.rows.length>0){
      form.value.personName= response.rows[0].name
      form.value.personId = response.rows[0].id
      if( form.value.id==null){
      getPerson( response.rows[0].id).then((response) => {
    const date = new Date()
    const year = date.getFullYear() // 年份
    let month = date.getMonth() + 1 // 月份，返回值为0-11，所以需要加1
    let day = date.getDate() // 日期

    // 对月份和日期进行补零
    month = month < 10 ? '0' + month : month.toString()
    day = day < 10 ? '0' + day : day.toString()

    const currentDate = year + month + day
    form.value.name = response.data.name + currentDate + '档案'
  })}
     }
     })
     // 类型
     getDicts('record_type').then(res => {
        typeList.value =[res.data] 
      })
       // 状态
       getDicts('health_record_state').then(res => {
        stateList.value =[res.data] 
      })
       // 发生原因
       getDicts('etiology').then(res => {
        etiologyList.value =[res.data] 
      })
    if(form.value.id!=null){
      getHealthRecord(form.value.id).then(res => {
        form.value = res.data   
        getDicts('etiology').then(result => {
          form.value.etiologyName=dictStr(form.value.etiology, result.data)
         })
          // 状态
        getDicts('health_record_state').then(result => {
          form.value.stateName=dictStr(form.value.state, result.data)
         })
                // 类型
           getDicts('record_type').then(result => {
          form.value.typeName=dictStr(form.value.type, result.data)
         })
      })
    }
}

function handlePerson() {
      if (personList.value[0].length === 0) {
        proxy.$refs['uToast'].show({
          message: '人员为空  ', type: 'warning'
        })
      } else {
        showPerson.value = true
      }
   }
function   handlePersonConfirm(e) {
     form.value.personName = e.value[0].name
      form.value.personId = e.value[0].id

      getPerson( e.value[0].id).then((response) => {
    const date = new Date()
    const year = date.getFullYear() // 年份
    let month = date.getMonth() + 1 // 月份，返回值为0-11，所以需要加1
    let day = date.getDate() // 日期

    // 对月份和日期进行补零
    month = month < 10 ? '0' + month : month.toString()
    day = day < 10 ? '0' + day : day.toString()

    const currentDate = year + month + day
    form.value.name = response.data.name + currentDate + '档案'
  })
      showPerson.value = false         
}
function handlePersonCancel() {
     showPerson.value = false
  }

function handleState() {
        if (stateList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '档案状态为空  ', type: 'warning'
          })
        } else {
          showState.value = true
        }
     }
  function   handleStateConfirm(e) {
        form.value.stateName = e.value[0].dictLabel
        form.value.state = e.value[0].dictValue
        showState.value = false
  }
 function handleStateCancel() {
      showState.value = false
      }


      function handleEtiology() {
        if (etiologyList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '发生原因为空  ', type: 'warning'
          })
        } else {
          showEtiology.value = true
        }
     }
  function   handleEtiologyConfirm(e) {
        form.value.etiologyName = e.value[0].dictLabel
        form.value.etiology = e.value[0].dictValue
        showEtiology.value = false
  }
 function handleEtiologyCancel() {
  showEtiology.value = false
      }

  function handleType() {
        if (typeList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '类型为空  ', type: 'warning'
          })
        } else {
          showType.value = true
        }
     }
  function   handleTypeConfirm(e) {
        form.value.typeName = e.value[0].dictLabel
        form.value.type = e.value[0].dictValue
        showType.value = false
  }
 function handleTypeCancel() {
       showType.value = false
      }

function  selectOccurTime() {
      occurTimeShow.value = true
      proxy.$refs['occurTimeRef'].innerValue = new Date().getTime()
  }
function occurTimeConfirm(e) {
      form.value.occurTime = dayjs(e.value).format("YYYY-MM-DD HH:mm:ss")
      occurTimeShow.value = false
  }

  function  selectRehabilitationTime() {
    rehabilitationTimeShow.value = true
      proxy.$refs['rehabilitationTimeRef'].innerValue = new Date().getTime()
  }
function rehabilitationTimeConfirm(e) {
      form.value.rehabilitationTime = dayjs(e.value).format("YYYY-MM-DD HH:mm:ss")
      rehabilitationTimeShow.value = false
  }

function submit() {
      errorFields.value = []
      proxy.$refs['uForm'].validate().then(() => {
        if (form.value.id != null) {
          updateHealthRecord(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '修改成功', complete() {
              uni.navigateTo({ url: `/pages/health/healthRecord/list` })
            }
          })
        })
        }else {
          addHealthRecord(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '新增成功', complete() {
              uni.navigateTo({ url: `/pages/health/healthRecord/list` })
            }
          })
        })
        }
      }).catch(errors => {
        // 验证失败，记录错误字段
        if (errors && errors.length > 0) {
          errorFields.value = errors.map(err => err.field)
        }
        proxy.$modal.msgError('请填写完整信息')
      })
    }
</script>

<style lang="scss" scoped>
.section {
  margin: 24rpx;
  padding: 0;
  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;
    line-height: 1.2;
    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;

    // 带箭头的输入框容器
    .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;
        z-index: 10;
      }
    }

    .form-btn {
      padding-top: 16rpx;
    }
  }
}
</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;
  letter-spacing: 2rpx !important;
}

/* 强制让错误状态的输入框边框变红 */
.u-form-item--error .u--input,
.u-form-item--error .u-input,
.u-form-item--error .u-input__content,
.u-form-item--error .u-input__content__field-wrapper {
  border: 2rpx solid #f56c6c !important;
  background: #fef0f0 !important;
}

.u-form-item--error .u--textarea,
.u-form-item--error .u-textarea {
  border: 2rpx solid #f56c6c !important;
  background: #fef0f0 !important;
}
</style>
