<template>
  <el-drawer
    v-model="dialogVisible"
    :title="title"
    resizable
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :destroy-on-close="true"
    size="70%"
    :before-close="handleClosed"
  >
    <div class="attack-risk-form">
      <h1 class="form-title">机构服务范围及收费标准（附件）</h1>
      <!-- 基本信息 -->
      <el-row :gutter="40">
        <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" class="row">
          <text>长者姓名</text>
          <search-the-elderly
            ref="selectElderRef"
            :disabled="isDetail"
            @update_elder="elderUp"
            v-model="dataForm.elderName"
            :tId="dataForm.tenantId"
          />
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" class="row">
          <text>档案号</text>
          <el-input v-if="!isDetail" v-model="dataForm.contractNumber" disabled />
          <el-text v-else disabled="">{{ dataForm.contractNumber }}</el-text>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" class="row">
          <text>入院日期</text>
          <el-input
            v-if="!isDetail"
            :model-value="
              dayjs(dataForm.checkInTime).format('YYYY-MM-DD') == 'Invalid Date'
                ? ''
                : dayjs(dataForm.checkInTime).format('YYYY-MM-DD')
            "
            disabled
          />
          <el-text v-else disabled="">{{
            dayjs(dataForm.checkInTime).format('YYYY-MM-DD')
          }}</el-text>
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" class="row">
          <text>床位号</text>
          <el-input v-if="!isDetail" v-model="dataForm.bedNumber" disabled />
          <el-text v-else disabled="">{{ dataForm.bedNumber }}</el-text>
        </el-col>
      </el-row>

      <el-row :gutter="40">
        <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" class="row">
          <text>记录人</text>
          <el-input :disabled="isDetail" v-model="form.recorder" />
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" class="row">
          <text>记录日期</text>
          <el-date-picker
            :disabled="isDetail"
            v-model="form.recordDate"
            type="date"
            style="width: 100%"
          />
        </el-col>
      </el-row>

      <!-- 内容区域 -->
      <div class="form-body">
        <ServiceChargingStandardsBody
          ref="bodyRef"
          v-model="serviceChargingForm"
          :is-text-mode="isDetail"
        />
      </div>
    </div>

    <template #footer>
      <el-button @click="handleClosed">关闭</el-button>
      <el-button type="success" size="small" v-show="isDetail" @click="handlePrint"
        >打印/导出</el-button
      >
      <el-button
        style="margin-left: 22px; margin-right: 30px"
        v-loading="formLoading"
        type="primary"
        v-show="!isDetail"
        @click="submitForm"
        >确定</el-button
      >
    </template>
  </el-drawer>

  <Teleport to="body">
    <div v-if="isPrint" class="print-container">
      <div class="print-org-name">{{ orgName }}</div>
      <ServiceChargingStandardsBody v-model="serviceChargingForm" :is-text-mode="true" />
    </div>
  </Teleport>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, nextTick } from 'vue'

import dayjs from 'dayjs'
import ServiceChargingStandardsBody from '../components/ServiceChargingStandardsBody.vue'
import { useUserStore } from '@/store/modules/user'
import { findLabelById } from '@/utils/dict'

import {
  serviceChargingStandards_create,
  serviceChargingStandards_update,
  serviceChargingStandards_getById
} from '@/api/elderly/contracts'
const message = useMessage()
const { t } = useI18n()
const userStore = useUserStore()
const title = ref('')
const dialogVisible = ref(false)
const formLoading = ref(false)
const selectElderRef = ref()
const bodyRef = ref()
const isDetail = ref(false)
const isPrint = ref(false)
const orgName = computed(
  () =>
    findLabelById(userStore.getOrgTenant?.options || [], dataForm.value.tenantId) ||
    userStore.getTenantName ||
    ''
)
let dataForm = ref({
  id: undefined,
  elderName: '',
  elderId: '',
  bedNumber: '',
  checkInTime: '',
  contractNumber: '',
  tenantId: undefined
})

const elderUp = (e) => {
  dataForm.value.elderName = e.elderName
  dataForm.value.elderId = e.id
  dataForm.value.bedNumber = e.bedName || ''
  dataForm.value.checkInTime = e.checkInTime
  dataForm.value.contractNumber = e.contractNumber || e.fileNumber
  serviceChargingForm.value.elderName = e.elderName
}

const serviceChargingForm = ref({
  elderName: '',
  signatorySign: '',
  signDate: ''
})

const form = reactive({
  recorder: '',
  recordDate: ''
})

const open = async (tenantId, id?: any, detail: boolean = false) => {
  resetForm()
  dialogVisible.value = true
  dataForm.value.tenantId = tenantId
  isDetail.value = detail
  if (id) {
    title.value = detail ? '详情-机构服务范围及收费标准' : '编辑-机构服务范围及收费标准'
    dataForm.value.id = id
    await loadServiceChargingData(id)
  } else {
    title.value = '新增-机构服务范围及收费标准'
  }
}

const loadServiceChargingData = async (id: number) => {
  try {
    const res = await serviceChargingStandards_getById(id)
    if (res) {
      dataForm.value.elderName = res.elderName || ''
      dataForm.value.elderId = res.elderId || ''
      dataForm.value.bedNumber = res.bedNumber || ''
      form.recorder = res.recorder || ''
      form.recordDate = res.recordDate ? dayjs(res.recordDate).toDate() : ''
      if (res.content) {
        try {
          const contentData = JSON.parse(res.content)
          serviceChargingForm.value = { ...serviceChargingForm.value, ...contentData }
        } catch (e) {
          console.error('解析机构服务范围及收费标准内容失败', e)
        }
      }
      await selectElderRef.value?.upData(res.elderName, res.elderId)
    }
  } catch (error) {
    message.error('加载数据失败')
  }
}

defineExpose({ open })

const emit = defineEmits(['success'])
const submitForm = async () => {
  if (formLoading.value) {
    return
  }
  formLoading.value = true
  try {
    const bodyForm = bodyRef.value?.form || serviceChargingForm.value
    const content = JSON.stringify({ ...bodyForm })
    const tempParams = {
      id: dataForm.value.id,
      elderId: dataForm.value.elderId,
      elderName: dataForm.value.elderName,
      bedNumber: dataForm.value.bedNumber,
      recorder: form.recorder,
      recordDate: form.recordDate ? dayjs(form.recordDate).format('YYYY-MM-DD') : '',
      content: content,
      signYi: bodyForm.signatorySign || '',
      signBing: '',
      signDate: bodyForm.signDate || '',
      tenantId: dataForm.value.tenantId
    }

    let res
    if (dataForm.value.id) {
      res = await serviceChargingStandards_update(tempParams)
    } else {
      res = await serviceChargingStandards_create(tempParams)
    }
    if (res) {
      message.success(dataForm.value.id ? t('common.updateSuccess') : t('common.createSuccess'))
      dialogVisible.value = false
      emit('success')
    }
  } finally {
    setTimeout(() => {
      formLoading.value = false
    }, 500)
  }
}

const resetForm = () => {
  dataForm.value = {
    id: undefined,
    elderName: '',
    elderId: '',
    bedNumber: '',
    checkInTime: '',
    contractNumber: '',
    tenantId: undefined
  }
  form.recorder = ''
  form.recordDate = ''
  serviceChargingForm.value = {
    elderName: '',
    signatorySign: '',
    signDate: ''
  }
}

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

const handlePrint = async () => {
  isPrint.value = true
  await nextTick()
  await new Promise((resolve) => setTimeout(resolve, 1500))
  window.print()
  setTimeout(() => {
    isPrint.value = false
  }, 500)
}
</script>

<style scoped lang="scss">
.form-title {
  text-align: center;
  font-size: 20px;
  width: 100%;
  margin-bottom: 20px;
}

.attack-risk-form {
  max-width: 1200px;
  margin: 0 auto;
  background: #fff;

  .form-body {
    border: 1px solid #333;
    padding: 15px;
  }
}
.row {
  margin-bottom: 12px;
  display: flex;
  flex-direction: row;
  align-items: center;
  text {
    text-align: right;
    margin-right: 4px;
    width: 82px;
  }
}
</style>

<style lang="scss">
.print-container {
  display: none;
}

@media print {
  html,
  body {
    background: #fff !important;
    margin: 0 !important;
    padding: 0 !important;
    overflow: visible !important;
  }

  body > *:not(.print-container) {
    display: none !important;
  }

  body > .print-container {
    display: block !important;
  }

  .print-container .print-org-name {
    text-align: start;
    font-size: 14px;
    margin-bottom: 12px;
  }

  .print-container > *:not(.print-org-name) {
    width: 210mm !important;
    max-width: none !important;
    margin: 0 !important;
    padding: 0 !important;
    box-sizing: border-box !important;
  }

  @page {
    size: 210mm 297mm;
    margin: 16mm;
  }
}
</style>
