<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="measureTime" required @click="selectDate()">
            <view class="input-with-arrow">
              <u--input v-model="form.measureTime" readonly disabledColor="#ffffff" placeholder="请选择测量时间"
                inputAlign="left" :customStyle="getInputStyle('measureTime')"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item label="身高" required prop="height" >
            <u--input v-model="form.height"  type="digit" placeholder="请填写身高"
              inputAlign="left" :customStyle="getInputStyle('height')">
              <template #suffix>
        <up-text
          text="CM"
        ></up-text>
      </template>
            </u--input>
          </u-form-item>
          <u-form-item label="体重" required prop="weight" >
            <u--input v-model="form.weight"  type="digit" placeholder="请填写体重过"
              inputAlign="left" :customStyle="getInputStyle('weight')">
              <template #suffix>
        <up-text
          text="KG"
        ></up-text>
      </template>
            </u--input>
          </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="personList" keyName="name" @cancel="handlePersonCancel"
      @confirm="handlePersonConfirm"></u-picker>
      <u-datetime-picker
    :show="datePickShow"
    mode="datetime"
    ref="measureTimeRef" 
    @cancel="datePickShow=false"
    @confirm="datePickConfirm"
    itemHeight="88"
  ></u-datetime-picker>
  </view>
</template>

<script setup>
import {
  getHeightWeightRecord,
  addHeightWeightRecord,
  updateHeightWeightRecord
} from '@/api/health/heightWeightRecord'
import { listPerson, } from '@/api/health/person'
const { proxy } = getCurrentInstance()
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 datePickShow = ref(false)
const showPerson = ref(false)
const title = ref("身高体重记录")
const personList = ref([])
const data = reactive({
form: {
  id: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    remark: null,
    measureTime: null,
    weight: null,
    personId: null,
    height: null
},
queryPersonParams: {
  pageNum: 1,
  status: '1',
  pageSize: 1000
},
rules: {
  personName: [{ required: true, message: '人员不能为空', trigger: ['change', 'blur'] }],
  measureTime: [{ required: true, message: '测量时间不能为空', trigger: ['change', 'blur'] }],
  weight: [{ required: true, message: '体重不能为空', trigger: ['change', 'blur'] }],
  height: [{ 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.measureTime = dayjs(new Date().getTime()).format("YYYY-MM-DD HH:mm:ss")
})
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){
      getHeightWeightRecord(form.value.id).then(res => {
        form.value = res.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
      form.value.healthRecordName = ''
      form.value.healthRecordId = ''
      queryHealthRecordParams.value.personId=e.value[0].id
      listHealthRecord(queryHealthRecordParams.value).then((response) => {  
        healthRecordList.value = [response.rows] 
  showPerson.value = false
})
      
}
function handlePersonCancel() {
     showPerson.value = false
  }
function  selectDate() {
      datePickShow.value = true
      proxy.$refs['measureTimeRef'].innerValue = new Date().getTime()
  }
function datePickConfirm(e) {
      form.value.measureTime = dayjs(e.value).format("YYYY-MM-DD HH:mm:ss")
      datePickShow.value = false
  }
function submit() {
      // 清空错误字段
      errorFields.value = []
      
      proxy.$refs['uForm'].validate().then(() => {
        if (form.value.id != null) {
          updateHeightWeightRecord(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '修改成功', complete() {
              uni.navigateTo({ url: `/pages/health/heightWeightRecord/list` })
            }
          })
        })
        }else {
          addHeightWeightRecord(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '新增成功', complete() {
              uni.navigateTo({ url: `/pages/health/heightWeightRecord/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;

    .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;
        z-index: 10;
      }
    }
  }
}
</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>
