<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="healthRecordName" required @click="handHealthRecord">
            <u--input v-model="form.healthRecordName" 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="hospitalName" required >
              <u--input v-model="form.hospitalName"  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="departments" required >
              <u--input v-model="form.departments"  placeholder="请填写科室"
                inputAlign="right" border="none"></u--input>
            </u-form-item>
            <u-form-item label="大夫" prop="doctor" required >
              <u--input v-model="form.doctor"  placeholder="请填写大夫"
                inputAlign="right" border="none"></u--input>
            </u-form-item>
            <u-form-item label="就诊时间" prop="visitingTime" required @click="selectDate()">
            <u--input v-model="form.visitingTime" 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="partner" required >
              <u--input v-model="form.partner"  placeholder="请填写陪同人"
                inputAlign="right" border="none"></u--input>
            </u-form-item>

          <u-form-item label="总费用" prop="totalCost" required >
              <u--input v-model="form.totalCost"  placeholder="请填写总费用"
                inputAlign="right" border="none">
                <template #suffix>
					<up-text
						text="元"
					></up-text>
				</template></u--input>
            </u-form-item>
          <u-form-item label="诊断结果" prop="diagnosis"  required labelPosition="top">
            <u--textarea v-model="form.diagnosis" placeholder="请填写诊断结果" border="none" autoHeight inputAlign="right" count
              maxlength="2000" style="padding:18rpx 0;"></u--textarea>
          </u-form-item>
          <u-form-item label="处理及医嘱" prop="prescribe"  required labelPosition="top">
            <u--textarea v-model="form.prescribe" placeholder="请填写处理及医嘱" border="none" autoHeight inputAlign="right" count
              maxlength="2000" style="padding:18rpx 0;"></u--textarea>
          </u-form-item>
            <u-form-item label="费用明细" prop="costDetail" >
              <u--textarea v-model="form.costDetail" 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="showHealthRecord" :columns="healthRecordList" keyName="name" @cancel="handHealthRecordCancel"
      @confirm="handHealthRecordConfirm"></u-picker>
      <u-picker itemHeight="88" :show="showType" :columns="typeList" keyName="dictLabel" @cancel="handleTypeCancel"
      @confirm="handleTypeConfirm"></u-picker>
      <u-datetime-picker
			:show="datePickShow"
			mode="datetime"
      ref="visitingTimeRef" 
			@cancel="datePickShow=false"
			@confirm="datePickConfirm"
			itemHeight="88"
		></u-datetime-picker>
  </view>
</template>

<script setup>
import { getDoctorRecord, addDoctorRecord, updateDoctorRecord } from '@/api/health/doctorRecord'
import { listPerson } from '@/api/health/person'
import { listHealthRecord } from '@/api/health/healthRecord'
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 datePickShow = ref(false)
const showPerson = ref(false)
const showHealthRecord = ref(false)
const title = ref("就医记录")
const healthRecordList = ref([])
const personList = ref([])
const typeList = ref([])
const showType = ref(false)
const flag = ref('add')
const data = reactive({
form: {
  id: null,
    hospitalName: null,
    departments: null,
    doctor: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    remark: null,
    healthRecordId: null,
    visitingTime: null,
    prescribe: null,
    personId: null,
    totalCost: 0,
    partner: null,
    costDetail: null
},
queryPersonParams: {
  pageNum: 1,
  status: '1',
  pageSize: 1000
},
queryHealthRecordParams: {
  pageNum: 1,
  personId:null,
  pageSize: 1000
},
rules: {
  healthRecordName: [{ required: true, message: '健康档案不能为空', trigger:['change', 'blur'] }],
  personName: [{ required: true, message: '人员不能为空', trigger: ['change', 'blur'] }],
  hospitalName: [{ required: true, message: '医院名称不能为空', trigger: ['change', 'blur'] }],
  departments: [{ required: true, message: '科室不能为空', trigger: ['change', 'blur'] }],
  doctor: [{ required: true, message: '大夫不能为空', trigger: ['change', 'blur'] }],
  totalCost: [{ type: 'number',  required: true, message: '总费用不能为空', trigger: ['change', 'blur'] }],
  partner: [{ required: true, message: '陪同人不能为空', trigger: ['change', 'blur'] }],
  prescribe: [{ required: true, message: '处理及医嘱不能为空', trigger: ['change', 'blur'] }],
  diagnosis: [{ required: true, message: '诊断结果不能为空', trigger: ['change', 'blur'] }],
  typeName: [{ required: true, message: '就医类型不能为空', trigger: ['change', 'blur'] }],
  visitingTime: [{ required: true, message: '就诊时间不能为空', trigger: ['change', 'blur'] }]
}
})
const { form, queryPersonParams, queryHealthRecordParams, rules} = toRefs(data)


onLoad((option) => {
    form.value.id = option.id
     flag.value = option.flag
     if(flag.value==null){
      if(form.value.id!=null){
      title.value="就医记录-修改"
     }else{
      title.value="就医记录-新增"
     }
     }else{
      title.value="就医记录-复制"
     }
    getData()
})
onReady(() => {
     form.value.visitingTime = 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() {
      
      // 药品来源
      
    if(form.value.id!=null){
      getDoctorRecord(form.value.id).then(res => {
        listPerson(queryPersonParams.value).then((response) => {
     personList.value = [response.rows] 
      queryHealthRecordParams.value.personId=res.data.personId
      listHealthRecord(queryHealthRecordParams.value).then((response) => {  
        healthRecordList.value = [response.rows] 
      })
     })
        form.value = res.data   
            // 就医类型
           getDicts('doctor_type').then(result => {
            typeList.value =[result.data] 
          form.value.typeName=dictStr(form.value.type, result.data)
         })
      })
      
    }else{
 // 就医类型
 getDicts('doctor_type').then(res => {
        typeList.value =[res.data] 
      })
    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
      queryHealthRecordParams.value.personId=response.rows[0].id
      listHealthRecord(queryHealthRecordParams.value).then((response) => {  
        healthRecordList.value = [response.rows] 
        if(response.rows.length>0){
      form.value.healthRecordName= response.rows[0].name
      form.value.healthRecordId = response.rows[0].id
    }
      })
     }
     })

    }
}

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] 
        if(response.rows.length>0){
      form.value.healthRecordName= response.rows[0].name
      form.value.healthRecordId = response.rows[0].id
    }
  showPerson.value = false
})
      
}
function handlePersonCancel() {
     showPerson.value = false
  }

function handHealthRecord() {
      if (healthRecordList.value[0].length === 0) {
        proxy.$refs['uToast'].show({
          message: '健康档案为空  ', type: 'warning'
        })
      } else {
        showHealthRecord.value = true
      }
   }
function   handHealthRecordConfirm(e) {
      form.value.healthRecordName = e.value[0].name
      form.value.healthRecordId = e.value[0].id
      showHealthRecord.value = false
}
function handHealthRecordCancel() {
     showHealthRecord.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  selectDate() {
      datePickShow.value = true
      proxy.$refs['visitingTimeRef'].innerValue = new Date().getTime()
  }
function datePickConfirm(e) {
      form.value.visitingTime = dayjs(e.value).format("YYYY-MM-DD HH:mm:ss")
      datePickShow.value = false
  }
function submit() {
      proxy.$refs['uForm'].validate().then(() => {
        if (form.value.id != null) {
        if(flag.value==null){
          updateDoctorRecord(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '修改成功', complete() {
              uni.navigateTo({ url: `/pages/health/doctorRecord/list` })
            }
          })
        })
          }else {
            form.value.id == null
            addDoctorRecord(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '新增成功', complete() {
              uni.navigateTo({ url: `/pages/health/doctorRecord/list` })
            }
          })
        })
          }
        }else {
          addDoctorRecord(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '新增成功', complete() {
              uni.navigateTo({ url: `/pages/health/doctorRecord/list` })
            }
          })
        })
        }
      })
    }
</script>

<style lang="scss" scoped>
page {
  height: 100%;
  overflow: auto;
}
.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;
    }
  }
}
</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;
}
</style>