<template>
  <view class="container" style="paddingBottom:1rpx;">
    <u-navbar
    leftIconSize="40rpx"
    leftIconColor="#333333"
    title="健康档案"
  >
  </u-navbar>
    <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="auto"
          :labelStyle="{ color: '#333333', fontSize: '30rpx' }">
          <u-form-item label="人员姓名" prop="personName" required @click="handlePerson">
            <u--input v-model="form.personName" disabled disabledColor="#ffffff" placeholder="请选择人员"
              inputAlign="right" border="none"></u--input>
            <u-icon slot="right" name="arrow-down"></u-icon>
          </u-form-item>
          <u-form-item label="档案名称" prop="name" required >
              <u--input v-model="form.name"  placeholder="请填写档案名称"
                inputAlign="right" border="none"></u--input>
            </u-form-item>
          <u-form-item label="类型" prop="typeName" required @click="handleType">
              <u--input v-model="form.typeName" disabled disabledColor="#ffffff" placeholder="请选择类型"
                inputAlign="right" border="none"></u--input>
              <u-icon slot="right" name="arrow-down"></u-icon>
            </u-form-item>
            <u-form-item label="档案状态" prop="stateName" required @click="handleState">
              <u--input v-model="form.stateName" disabled disabledColor="#ffffff" placeholder="请选择档案状态"
                inputAlign="right" border="none"></u--input>
              <u-icon slot="right" name="arrow-down"></u-icon>
            </u-form-item>
            <u-form-item label="发生时间" prop="occurTime" required @click="selectOccurTime()">
            <u--input v-model="form.occurTime" disabled disabledColor="#ffffff" placeholder="请选择发生时间" inputAlign="right" border="none"></u--input>
          <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>
            <u-form-item label="发生原因"  prop="etiologyName" required @click="handleEtiology">
              <u--input v-model="form.etiologyName" disabled disabledColor="#ffffff" placeholder="请选择发生原因"
                inputAlign="right" border="none"></u--input>
              <u-icon slot="right" name="arrow-down"></u-icon>
            </u-form-item>
            <u-form-item label="康复时间" prop="rehabilitationTime"  @click="selectRehabilitationTime()">
            <u--input v-model="form.rehabilitationTime" disabled disabledColor="#ffffff" placeholder="请选择康复时间" inputAlign="right" border="none"></u--input>
          <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>
            <u-form-item label="初期症状" prop="initialSymptoms" required >
                <u--textarea v-model="form.initialSymptoms" placeholder="请填写初期症状" border="none" autoHeight inputAlign="right" count
                maxlength="2000" style="padding:18rpx 0;"></u--textarea>
            </u-form-item>
            <u-form-item label="中期症状" prop="mediumTermSymptoms"  >
                <u--textarea v-model="form.mediumTermSymptoms" placeholder="请填写中期症状" border="none" autoHeight inputAlign="right" count
                maxlength="2000" style="padding:18rpx 0;"></u--textarea>
            </u-form-item>
            <u-form-item label="后期症状" prop="laterStageSymptoms"  >
                <u--textarea v-model="form.laterStageSymptoms" placeholder="请填写后期症状" border="none" autoHeight inputAlign="right" count
                maxlength="2000" style="padding:18rpx 0;"></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 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.resource = 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() {
      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` })
            }
          })
        })
        }
      })
    }
</script>

<style lang="scss" scoped>
.section {
  margin: 24rpx;
  padding: 16rpx 24rpx;
  background-color: #fff;
  border-radius: 8rpx;

  .section-title {
    width: 360rpx;
    color: #333333;
    line-height: 44rpx;
    font-size: 30rpx;
    border-left: 6rpx solid #2681FF;
    padding-left: 26rpx;
  }

  .form-view {
    padding: 20rpx 0rpx 0 10rpx;

    .form-btn {
      padding-top: 20rpx;
    }
  }
}
</style>