<!-- 委托方情况报告详情 -->
<script name="SituationReportDetail" lang="ts" setup>
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import type{ ISituationReportInfo } from './customer-report'
import useUserStore from '@/store/modules/user'
import { saveReviewNotice, updateReviewNotice } from '@/api/resource/reviewNotice'
import type { IDictType } from '@/commonInterface/resource-interface'
import { getDictByCode } from '@/api/system/dict'

// 从路由中传过来的参数
const type = ref<string>('')
const id = ref<string>('')

const userInfo = useUserStore()
const route = useRoute()
const router = useRouter()
const title = ref('')

// 关键字段是否可以编辑
const keyFieldsDisable = ref<boolean>(true)

const reportFormRef = ref()

const reportInfo = ref<ISituationReportInfo>({
  id: '',
  customerName: '',
  labCode: '',
  labCodeName: '',
  reportNo: '',
  reportName: '委托方情况报告',
  customerAdvice: '',
  customerAdviceHandle: '',
  conclusion: '',
  createUserId: '',
  createUserName: '',
  createTime: '',
})

const reportFormRules = ref({
  labCode: [{ required: true, message: '实验室代码不能为空，请选择', trigger: ['change', 'blur'] }],
  customerName: [{ required: true, message: '委托方不能为空', trigger: 'blur' }],
  customerAdvice: [{ required: true, message: '委托方反馈意见不能为空，请选择', trigger: 'blur' }],
  customerAdviceHandle: [{ required: true, message: '对委托方意见的处理不能为空', trigger: 'blur' }],
  conclusion: [{ required: true, message: '结论不能为空', trigger: 'blur' }],
}) // 表单验证规则

// 字典值
const labCodeDict = ref<IDictType[]>([])

// 逻辑

// 保存至草稿箱
const saveNoticeInfo = () => {
  reportInfo.value.createTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss') // 创建时间改为提交时间
  saveReviewNotice(reportInfo.value).then((res) => {
    if (res.code === 200) {
      // 提示保存成功
      ElMessage.success('保存成功')
      // 设置返回的委托方id和委托方编号
      reportInfo.value.reportNo = res.data.reportNo
      reportInfo.value.id = res.data.id
      id.value = res.data.id

      type.value = 'detail'
    }
    else {
      // 提示失败信息
      ElMessage.error(`保存失败：${res.message}`)
    }
  })
}

// 编辑
const updateNoticeInfo = () => {
  updateReviewNotice(reportInfo.value).then((res) => {
    if (res.code === 200) {
      // 提示保存成功
      ElMessage.success('保存成功')
    }
    else {
      // 提示失败信息
      ElMessage.error(`保存失败：${res.message}`)
    }
  })
}

// 新建时保存后的处理 获取返回的id
const saveButtonHandler = async () => {
  if (!reportFormRef) { return }

  await reportFormRef.value.validate((valid: boolean, fields: any) => {
    if (valid === true) {
      ElMessageBox.confirm(
        '确认保存吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then(() => {
        if (type.value === 'create') {
          saveNoticeInfo()
        }
        else if (type.value === 'update') {
          updateNoticeInfo()
        }
      })
    }
  })
}

const getLabCodeDict = async () => {
  // 先从缓存中获取
  if (sessionStorage.getItem('bizLabCode') === null || sessionStorage.getItem('bizLabCode') === undefined) {
    // 缓存中没有则调用接口查询
    await getDictByCode('bizLabCode').then((res) => {
      if (res.code === 200) {
        labCodeDict.value = res.data
        sessionStorage.setItem('bizLabCode', JSON.stringify(labCodeDict.value)) // 放到缓存中
      }
    })
  }
  else {
    labCodeDict.value = JSON.parse(sessionStorage.getItem('bizLabCode')!)
  }
}

// 关闭
const resetForm = () => {
  sessionStorage.removeItem('situationReportInfo') // 返回列表时 将缓存中的数据删除
  router.go(-1)
}

const initDialog = (params: any) => {
  // 从路由中获取参数
  type.value = params.type
  id.value = params.id !== undefined ? params.id : ''

  switch (params.type) {
    case 'create' :
      title.value = '委托方情况报告（新增）'

      sessionStorage.removeItem('situationReportInfo')

      reportInfo.value.createUserId = userInfo.id
      reportInfo.value.createUserName = userInfo.name
      reportInfo.value.createTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')

      // 新建时组别代码和实验室代码可以编辑
      keyFieldsDisable.value = false
      break
    case 'update':
      title.value = '委托方情况报告（编辑）'

      reportInfo.value = JSON.parse(sessionStorage.getItem('situationReportInfo')!)
      break
    case 'detail':
      title.value = '委托方情况报告（详情）'
      id.value = params.id

      reportInfo.value = JSON.parse(sessionStorage.getItem('situationReportInfo')!)
      keyFieldsDisable.value = true
      break
    default:
      title.value = ''
      keyFieldsDisable.value = true
      break
  }
}

const initDict = () => {
  getLabCodeDict()
}

// 监听 显示中文
watch(() => reportInfo.value.labCode, (newVal) => {
  labCodeDict.value = JSON.parse(sessionStorage.getItem('bizLabCode')!)

  if (labCodeDict.value.length > 0) {
    const targetList = labCodeDict.value.filter(item => item.value === newVal)
    if (targetList.length > 0) {
      reportInfo.value.labCodeName = targetList[0].name
    }
    else {
      reportInfo.value.labCodeName = ''
    }
  }
})

onMounted(() => {
  initDict()
  initDialog(route.query)
})
</script>

<template>
  <app-container>
    <el-form ref="reportFormRef" :model="reportInfo" :rules="reportFormRules" label-position="right" label-width="125px" border stripe>
      <detail-page :title="`${title}`">
        <template #btns>
          <template v-if="type === 'detail'">
            <el-button type="primary" @click="printToWord">
              导出Word
            </el-button>
            <el-button type="primary" @click="printToPDF">
              导出PDF
            </el-button>
            <el-button type="primary" @click="printNotice">
              打印
            </el-button>
          </template>

          <el-button v-else type="primary" @click="saveButtonHandler">
            保存
          </el-button>
          <el-button type="info" @click="resetForm()">
            关闭
          </el-button>
        </template>

        <el-row :gutter="24">
          <!-- 第一行 第一列 -->
          <el-col :span="6">
            <el-form-item label="实验室代码" prop="labCode">
              <el-select v-model="reportInfo.labCode" placeholder="请选择实验室代码" :disabled="keyFieldsDisable" style="width: 100%;">
                <el-option v-for="dict in labCodeDict" :key="dict.id" :label="dict.name" :value="dict.value" />
              </el-select>
              <el-input v-model="reportInfo.labCodeName" type="hidden" />
            </el-form-item>

            <el-form-item label="拟制人">
              <el-input v-model="reportInfo.createUserId" type="hidden" />
              <el-input v-model="reportInfo.createUserName" :readonly="true" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="报告单编号">
              <el-input v-model="reportInfo.reportNo" placeholder="报告单编号，保存后自动生成" :disabled="true" />
            </el-form-item>

            <el-form-item label="拟制时间">
              <el-input v-model="reportInfo.createTime" :readonly="true" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="报告单名称">
              <el-input v-model="reportInfo.reportName" :readonly="true" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
      </detail-page>

      <table-container title="">
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="委托方名称" prop="customerName">
              <el-input v-model="reportInfo.customerName" :clearable="true" :disabled="type === 'detail'" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="委托方反馈意见" prop="customerAdvice">
              <el-input v-model="reportInfo.customerAdvice" :clearable="true" :disabled="type === 'detail'" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="对意见的处理" prop="customerAdviceHandle">
              <el-input v-model="reportInfo.customerAdviceHandle" :clearable="true" :disabled="type === 'detail'" />
            </el-form-item>
          </el-col>
        </el-row>
      </table-container>

      <table-container title="一、西昌实验室情况">
        <template v-if="type !== 'detail'" #btns-right>
          <el-button type="primary" @click="addEditableRow('staff')">
            增加行
          </el-button>
          <el-button type="info" @click="delCustomerStaffRecords">
            删除行
          </el-button>
        </template>
      </table-container>

      <table-container title="二、海口实验室情况">
        <template v-if="type !== 'detail'" #btns-right>
          <el-button type="primary" @click="addEditableRow('staff')">
            增加行
          </el-button>
          <el-button type="info" @click="delCustomerStaffRecords">
            删除行
          </el-button>
        </template>
      </table-container>

      <table-container title="">
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="结论" prop="conclusion">
              <el-input v-model="reportInfo.conclusion" :clearable="true" :disabled="type === 'detail'" />
            </el-form-item>
          </el-col>
        </el-row>
      </table-container>
    </el-form>
  </app-container>
</template>

