Newer
Older
xc-business-system / src / views / resource / customer / situationReport / detail.vue
<!-- 委托方情况报告详情 -->
<script name="SituationReportDetail" lang="ts" setup>
import { ElLoading, ElMessage, ElMessageBox, dayjs } from 'element-plus'
import type { ICustomerQuestionnaireInfo, IListQuery } from '../questionnaire/customer-questionnaire'
import type { ICustomerSatisfaction, ISituationReportInfo } from './customer-report'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import type { IDictType } from '@/commonInterface/resource-interface'
import useUserStore from '@/store/modules/user'
import { detailSituationReport, getStream, saveSituationReport, updateSituationReport } from '@/api/resource/situationReport'
import { getDictByCode } from '@/api/system/dict'
import { getQuestionnaireList } from '@/api/resource/questionnaire'
import FilterQuestionnaire from '@/views/resource/common/filterQuestionnaire.vue'
import { exportFile } from '@/utils/exportUtils'
import { printPdf } from '@/utils/printUtils'
// 从路由中传过来的参数
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 refQuestionnaireFilter = ref()

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

const quesQuery = ref<IListQuery>({
  customerName: '', // 填写单位
  writerName: '',
  writeTimeStart: '',
  writeTimeEnd: '',
  sendTimeStart: '',
  sendTimeEnd: '',
  offset: 1,
  limit: 2000,
})

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 customerListXc = ref<ICustomerSatisfaction[]>([])
const customerListHk = ref<ICustomerSatisfaction[]>([])
const satisfactionColumns = ref<TableColumn[]>([
  { text: '委托方名称', value: 'customerName', align: 'center' },
  { text: '时间', value: 'proposeTime', align: 'center', width: '240' },
  { text: '评分', value: 'score', align: 'center', width: '240' },
])

const customerSelectedXc = ref<ICustomerSatisfaction[]>([])
const customerSelectedHk = ref<ICustomerSatisfaction[]>([])

const xcMultiSelect = (e: any) => {
  customerSelectedXc.value = e
}

const hkMultiSelect = (e: any) => {
  customerSelectedHk.value = e
}

const addEditableRow = () => {
  refQuestionnaireFilter.value.showOrHideFilterDialog(true)
}

const delSatisfaction = () => {
  if (customerSelectedXc.value.length === 0 && customerSelectedHk.value.length === 0) {
    ElMessage.warning('请至少选择一行')
    return
  }
  // 前端界面删除
  customerListXc.value = customerListXc.value.filter(item => customerSelectedXc.value.includes(item) === false)
  customerListHk.value = customerListHk.value.filter(item => customerSelectedHk.value.includes(item) === false)
}

// 根据委托方名称查询满意度调查表
// 暂时不用
const searchQuestionnaire = () => {
  if (reportInfo.value.customerName !== '') {
    reportInfo.value.customerName = reportInfo.value.customerName.replace(',', ',')
    const customerList = reportInfo.value.customerName.split(',')
    customerList.forEach((customer: string) => {
      quesQuery.value.customerName = customer
      getQuestionnaireList(quesQuery.value).then((res) => {
        if (res.code === 200) {
          customerListXc.value = []
          customerListHk.value = []
          res.data.rows.forEach((item: ICustomerQuestionnaireInfo) => {
            if (item.writeStatus === '已提交') {
              if (item.labCode === 'X') {
                customerListXc.value.push({
                  id: item.id,
                  labCode: item.labCode,
                  customerName: item.customerName,
                  proposeTime: item.writeTime,
                })
              }
              else if (item.labCode === 'H') {
                customerListHk.value.push({
                  id: item.id,
                  labCode: item.labCode,
                  customerName: item.customerName,
                  proposeTime: item.writeTime,
                })
              }
            }
          })
        }
      })
    })
  }
}

// 保存至草稿箱
const saveReportInfo = () => {
  reportInfo.value.createTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss') // 创建时间改为提交时间
  saveSituationReport(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'
      keyFieldsDisable.value = true
    }
    else {
      // 提示失败信息
      ElMessage.error(`保存失败:${res.message}`)
    }
  })
}

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

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

  reportInfo.value.customerList = []
  customerListXc.value.forEach((item) => {
    reportInfo.value.customerList.push(item)
  })
  customerListHk.value.forEach((item) => {
    reportInfo.value.customerList.push(item)
  })

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

const questionnaireSelectedHandler = (rows: ICustomerQuestionnaireInfo[]) => {
  refQuestionnaireFilter.value.showOrHideFilterDialog(false)

  rows.forEach((row) => {
    if (row.labCode === 'X') {
      const existList = customerListXc.value.filter(xc => xc.id === row.id)
      if (existList.length === 0) {
        customerListXc.value.push(row)
      }
    }
    else if (row.labCode === 'H') {
      const existList = customerListHk.value.filter(hk => hk.id === row.id)
      if (existList.length === 0) {
        customerListHk.value.push(row)
      }
    }
  })
}

const disSatisfByLabCode = () => {
  detailSituationReport({ id: reportInfo.value.id }).then((res) => {
    if (res.code === 200) {
      customerListXc.value = res.data.xCustomerList
      customerListHk.value = res.data.hCustomerList
    }
  })
}

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')!)
      disSatisfByLabCode()
      break
    case 'detail':
      title.value = '委托方情况报告(详情)'
      id.value = params.id

      reportInfo.value = JSON.parse(sessionStorage.getItem('situationReportInfo')!)
      disSatisfByLabCode()
      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 = ''
    }
  }
})

// --------------------------------导出word、pdf、打印----------------------------------------------------
const stream = ref()
const streamNormal = ref(true) // 流是否正常
// 获取流
const fetchStream = async (isPdf = true) => {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(255, 255, 255, 0.6)',
  })
  const res = await getStream({ id: id.value, pdf: isPdf })
  stream.value = res.data
  loading.close()
}

// 打印Word
const printToWord = () => {
  fetchStream(false).then(() => {
    if (streamNormal.value) {
      exportFile(stream.value, '委托方意见登记表.doc')
    }
  })
}

// 导出PDF
const printToPDF = () => {
  fetchStream().then(() => {
    if (streamNormal.value) {
      exportFile(new Blob([stream.value]), '委托方意见登记表.pdf')
    }
  })
}

// 打印
const printClickedHandler = () => {
  fetchStream().then(() => {
    if (streamNormal.value) {
      const blobUrl = URL.createObjectURL(stream.value)
      printPdf(blobUrl)
    }
  })
}

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="printClickedHandler">
              打印
            </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-col>

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

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

          <el-col :span="6">
            <el-form-item label="拟制时间">
              <el-input v-model="reportInfo.createTime" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
      </detail-page>

      <detail-block title="">
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="委托方名称" prop="customerName">
              <el-input v-model="reportInfo.customerName" placeholder="委托方名称,多个委托方用,隔开" :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" placeholder="请输入委托方反馈的意见" :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" placeholder="请输入对委托方意见的处理" :clearable="true" :disabled="type === 'detail'" />
            </el-form-item>
          </el-col>
        </el-row>
      </detail-block>

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

        <el-table :data="customerListXc" border style="width: 100%;" @selection-change="xcMultiSelect">
          <el-table-column v-if="type !== 'detail'" type="selection" align="center" width="38" />
          <el-table-column align="center" label="序号" width="80" type="index" />
          <el-table-column
            v-for="item in satisfactionColumns"
            :key="item.value"
            :prop="item.value"
            :label="item.text"
            :width="item.width"
            align="center"
          >
            <template #default="scope">
              <span v-if="!scope.row.editable">{{ scope.row[item.value] }}</span>
              <el-input v-else v-model="scope.row[item.value]" :autofocus="true" :placeholder="`${item.text}`" class="input" />
            </template>
          </el-table-column>
        </el-table>
      </table-container>

      <table-container title="二、海口实验室情况">
        <el-table :data="customerListHk" border style="width: 100%;" @selection-change="hkMultiSelect">
          <el-table-column v-if="type !== 'detail'" type="selection" align="center" width="38" />
          <el-table-column align="center" label="序号" width="80" type="index" />
          <el-table-column
            v-for="item in satisfactionColumns"
            :key="item.value"
            :prop="item.value"
            :label="item.text"
            :width="item.width"
            align="center"
          >
            <template #default="scope">
              <span v-if="!scope.row.editable">{{ scope.row[item.value] }}</span>
              <el-input v-else v-model="scope.row[item.value]" :autofocus="true" :placeholder="`${item.text}`" class="input" />
            </template>
          </el-table-column>
        </el-table>
      </table-container>

      <detail-block 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>
      </detail-block>
    </el-form>

    <filter-questionnaire ref="refQuestionnaireFilter" @record-selected="questionnaireSelectedHandler" />
  </app-container>
</template>