<template>
  <Dialog v-model="dialogVisible" title="护理日志补录" width="80%" @close="handleClosed">
    <el-form :model="dataForm" ref="formRef">
      <el-row :gutter="20">
        <el-col :span="4" :xs="24">
          <el-form-item label="长者姓名">{{ dataForm.elderName }}</el-form-item>
        </el-col>
        <el-col :span="4" :xs="24">
          <el-form-item label="床位号">{{ dataForm.bedName }}</el-form-item>
        </el-col>
        <el-col :span="4" :xs="24">
          <el-form-item label="护理等级">{{ dataForm.nursingGrade }}</el-form-item>
        </el-col>
        <el-col :span="4" :xs="24">
          <el-form-item label="护理日期">{{ dataForm.nursingDate }}</el-form-item>
        </el-col>
        <el-col :span="4" :xs="24">
          <el-form-item label="护理人员">
            <el-select v-model="dataForm.caregiverId" placeholder="请选择" @change="handleChangeNurse">
              <el-option v-for="item in nurseList" :key="item.id" :label="item.nickname" :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-table :data="dataForm.nursingLogRecords" border height="55vh">
        <el-table-column label="项目分类" prop="categoryName" width="180" align="center"/>
        <el-table-column label="项目名称" prop="nurseItemName" width="150" align="center"/>
        <el-table-column label="频次" prop="frequency" width="120" align="center"/>
        <el-table-column label="形式" prop="frequencyUnit" width="120" align="center">
          <template #default="scope">
            {{ getDictLabel(DICT_TYPE.NURSING_FREQUENCY_TYPE, scope.row.frequencyUnit) }}
          </template>
        </el-table-column>
        <el-table-column label="补录时间" align="center">
          <template #default="scope">
            <el-scrollbar>
              <div class="flex-time">
                <span v-for="(item, index) in scope.row.records" :key="index" class="flex-time mr2 mb2">
                  <TgTimePicker style="width: 120px;" v-model="item.tempTime" @change="handleChange(item)"/>
                  <Icon icon="ep:circle-close-filled" class="ml1 icon" @click="handleDel(scope.row, index)"/>
                </span>
                <el-button type="primary" @click="handleAdd(scope.row)">添加</el-button>
              </div>
            </el-scrollbar>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <template #footer>
      <el-button @click="handleClosed">关闭</el-button>
      <el-button v-loading="formLoading" type="primary" @click="submitForm">确定</el-button
      >
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DICT_TYPE, getDictLabel } from '@/utils/dict'
import { supplementNursingLog, getNurseGroupByElderId, getNursingLogDetails } from '@/api/elderly/nursing'
import { formatTime } from '@/utils'
defineOptions({ name: 'NurseLogForm' })
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const dialogVisible = ref(false)
const formLoading = ref(false)
const state = reactive({
  dataForm:{
    id: '',
    elderId: '',
    elderName: '',
    nursingDate: '',
    count: '',
    bedName: '',
    nursingGrade: '',
    caregiverId: '',
    caregiver: '',
    nursingLogRecords: []
  }
})
const { dataForm } = toRefs(state)

const resetFormField =  reactive({ ...dataForm.value })
const formRef = ref()

const nurseList = ref<{id: string, nickname: string}[]>([])
/** 打开弹窗 */
const open = async (row) => {
  dialogVisible.value = true
  // 根据长者获取护理分组人员
  const res = await getNurseGroupByElderId(row.elderId)
  nurseList.value = res

  dataForm.value.elderName = row.elderName
  dataForm.value.bedName = row.bedName
  dataForm.value.nursingGrade = row.nursingGrade
  dataForm.value.elderId = row.elderId
  dataForm.value.nursingDate = row.nursingDate
  dataForm.value.id = row.id
  
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const handleAdd = (row) => {
  row.records.push({
    ...row,
    records: undefined,
    nursingLogId: dataForm.value.id,
    caregiverId: dataForm.value.caregiverId,
    caregiver: dataForm.value.caregiver,
    nursingPlanItemId: row.id,
    tempTime: '',
    id: undefined
  })
}
const handleDel = (row, index: number) => {
  row.records.splice(index, 1)
}

const handleChangeNurse = (val) => {
  const obj: any = nurseList.value.find(item => item.id == val)
  dataForm.value.caregiver = obj.nickname
  getDetail()
}

const handleChange = (item) => {
  item.nursingTime = Date.parse(dataForm.value.nursingDate + ' ' + item.tempTime)
}

const handleClosed = () => {
  dataForm.value = { ...resetFormField }
  dialogVisible.value = false
}

const getDetail = async () => {
  // 获取补录详情
  const result = await getNursingLogDetails({elderId: dataForm.value.elderId, nursingLogId: dataForm.value.id})
  
  result.map(item=>{
    item.records.map(r => {
      r.id = undefined
      if(r.nursingTime){
        r.tempTime = formatTime(new Date(r.nursingTime), 'HH:mm:ss')
      }
    })
  })
  dataForm.value.nursingLogRecords = result
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const params = JSON.parse(JSON.stringify(dataForm.value))
    const arr = []
    params.nursingLogRecords.map(item=>{
      if(item.records && item.records.length > 0){
        arr.push(...item.records)
      }
    })
    params.nursingLogRecords = arr
    const res = await supplementNursingLog(params)
    if (res) {
      message.success(t('common.updateSuccess'))
      handleClosed()
      // 发送操作成功的事件
      emit('success')
    }
  } finally {
    formLoading.value = false
  }
}
</script>
<style lang="scss" scoped>
.flex-time{
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .icon{
    cursor: pointer;
  }
}
</style>
