<template>
  <page-layer>
    <template #header>
      <el-select v-model="headerParam.logType" style="width: 80px" @change="headerParam.infno = null">
        <el-option label="住院" :value="1"></el-option>
        <el-option label="门诊" :value="2"></el-option>
      </el-select>
      <el-select v-model="headerParam.infno" style="width: 145px" clearable>
        <el-option v-for="itm in currentInfnos" :key="itm.code" :value="itm.code" :label="itm.name"></el-option>
      </el-select>
      <el-date-picker
          v-model="dateRange"
          type="daterange"
          :shortcuts="setlShtcuts"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 220px"
      ></el-date-picker>
      <el-input v-model="headerParam.patNo" clearable placeholder="住院号/门诊ID" style="width: 110px"></el-input>
      <el-input v-model="headerParam.times" clearable placeholder="住院/门诊次数" style="width: 110px"></el-input>
      <el-divider direction="vertical"></el-divider>
      <el-button type="primary" icon="Search" @click="fetchSiLogs(true)">检索</el-button>
      <el-divider direction="vertical"></el-divider>
      <el-tag type="info" effect="dark" size="small" v-show="tipMessage">{{ tipMessage }}</el-tag>
    </template>
    <template #main>
      <el-table :data="logs" :height="tableHeight" border highlight-current-row :row-class-name="tableRowClassName">
        <el-table-column prop="msgid" label="报文ID" width="260"></el-table-column>
        <el-table-column prop="insuplcAdmdvs" label="参保区划" width="80"></el-table-column>
        <el-table-column prop="infno" label="功能号" width="60"></el-table-column>
        <el-table-column prop="infname" label="功能号名称" width="120"></el-table-column>
        <el-table-column prop="opter" label="操作员" width="80"></el-table-column>
        <el-table-column prop="opterName" label="操作员姓名" width="80"></el-table-column>
        <el-table-column prop="createDatetime" label="操作时间" width="150"></el-table-column>
        <el-table-column prop="patNo" label="患者ID" width="80"></el-table-column>
        <el-table-column prop="times" label="次数" width="60"></el-table-column>
        <el-table-column label="结果" width="60">
          <template #default="scope">
            <span v-html="coloredResult(scope.row.infcode)"></span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button type="info" circle icon="View" @click="formatBodyResult(scope.row.msgid)" title="查看"></el-button>
            <el-button type="primary" circle icon="Download" @click="exportBodyResultTxt(scope.row)" title="下载"></el-button>
            <el-button v-if="showRecoveryTrade(scope.row.infno)" type="danger" circle icon="Refresh" @click="recoveryTrade(scope.row)" title="冲正"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="headerParam.currentPage"
          :page-sizes="[15, 30, 45, 60]"
          :page-size="headerParam.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalSize"
          style="margin-top: 5px"
      ></el-pagination>
      <el-drawer v-model="showFormatModal" :with-header="false" :size="drawerWidth">
        <div :style="formattedStyle">
          <div :style="formattedChildStyle">
            <div :style="leftPreCopyStyle">
              <el-button icon="Document" text @click="copyLogBodyResult(1)">复制</el-button>
            </div>
            <pre :style="preStyle" class="formatted-body">{{ formattedBody }}</pre>
          </div>
          <div :style="formattedChildStyle">
            <div style="position: absolute; top: 20px; right: 50px">
              <el-button icon="Document" text @click="copyLogBodyResult(2)">复制</el-button>
            </div>
            <pre :style="preStyle" class="formatted-result">{{ formattedResult }}</pre>
          </div>
        </div>
      </el-drawer>
      <textarea style="opacity: 0; position: fixed" id="copyArea"></textarea>
    </template>
  </page-layer>
</template>

<script setup name="LogAnalyse">
import { computed, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import { setlShtcuts } from '@/data/shortcuts'
import { infnos } from '@/data/index'
import { selectSiLogs, selectSiLogBody } from '../../../api/medical-insurance/si-log'
import { recoveryTradePermission } from '../../../utils/permission'
import { autoRecoveryTrade } from '../../../api/medical-insurance/si-manage'
import { getDateRangeFormatDate } from '../../../utils/date'
import { ElMessage, ElMessageBox } from 'element-plus'
import PageLayer from "@/layout/PageLayer";
const store = useStore()
const windowSize = store.state.app.windowSize
const tableHeight = windowSize.h - 85
const dateRange = ref(null)

const fullWidth = window.innerWidth
const drawerWidth = fullWidth * 0.66

const formattedStyle = {
  display: 'flex',
  height: window.innerHeight + 'px',
}

const formattedChildStyle = {
  width: drawerWidth / 2 - 10 + 'px',
  padding: '0 10px 0 10px',
}

const preStyle = {
  width: drawerWidth / 2 - 60 + 'px',
  height: window.innerHeight - 50 + 'px',
  overflowY: 'auto',
}

const leftPreCopyStyle = {
  position: 'absolute',
  top: '20px',
  left: drawerWidth / 2 - 100 + 'px',
}

const currentInfnos = computed(() => {
  return infnos[headerParam.logType]
})

const headerParam = reactive({
  begntime: null,
  endtime: null,
  logType: 1,
  infno: null,
  patNo: null,
  times: null,
  needCalTips: null,
  pageSize: 30,
  currentPage: 1,
})
const tipMessage = ref(null)
const logs = ref([])
const handleSizeChange = (val) => {
  headerParam.pageSize = val
  fetchSiLogs(false)
}
const handleCurrentChange = (val) => {
  headerParam.currentPage = val
  fetchSiLogs(false)
}
const showFormatModal = ref(false)
const formattedBody = ref(null)
const formattedResult = ref(null)
const formatBodyResult = (msgid) => {
  selectSiLogBody(msgid).then((res) => {
    formattedBody.value = JSON.stringify(JSON.parse(res.body), null, 2)
    formattedResult.value = JSON.stringify(JSON.parse(res.result), null, 2)
    showFormatModal.value = true
  })
}

const totalSize = ref(0)

const fetchSiLogs = (needCalTips) => {
  headerParam.needCalTips = needCalTips
  if (dateRange.value) {
    const dtrge = getDateRangeFormatDate(dateRange.value)
    headerParam.begntime = dtrge.startTime
    headerParam.endtime = dtrge.endTime
  }
  selectSiLogs(headerParam)
    .then((res) => {
      logs.value = res.list
      totalSize.value = res.total
      if (needCalTips) {
        tipMessage.value = res.tipMessage
      }
    })
    .catch(() => {
      logs.value = []
      totalSize.value = 0
      tipMessage.value = null
    })
}

const tableRowClassName = ({ row }) => {
  if (row.infcode === 0) {
    return 'success-row'
  }
  return 'danger-row'
}

const coloredResult = (infcode) => {
  return infcode === 0 ? '<span style="color: green">成功</span>' : '<span style="color: red">失败</span>'
}

const copyLogBodyResult = (flag) => {
  const copyArea = document.getElementById('copyArea')
  copyArea.value = flag === 1 ? formattedBody.value : formattedResult.value
  copyArea.select()
  document.execCommand('Copy')
  ElMessage({
    message: '复制成功',
    type: 'success',
    duration: 2500,
    showClose: true,
  })
}

const exportBodyResultTxt = (row) => {
  selectSiLogBody(row.msgid).then((res) => {
    let str = '参数：\r\n' + res.body + '\r\n\r\n' + '返回：\r\n' + res.result
    let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str)
    let link = document.createElement('a')
    link.href = uri
    link.download = `【功能号：${res.infno}，${row.infname}】报文详细.txt`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  })
}

const recoveriableInfnos = ['2207', '2208', '2401', '2304', '2305']
const showRecoveryTrade = (infno) => {
  return recoveryTradePermission() && recoveriableInfnos.indexOf(infno) !== -1
}

const recoveryTrade = (row) => {
  ElMessageBox.confirm('冲正将取消医保中心接收到的本次交易，请慎重使用！', '警告', {
    type: 'warning',
  }).then(() => {
    const params = {
      psnNo: row.psnNo,
      omsgid: row.msgid,
      oinfno: row.infno,
    }
    autoRecoveryTrade(params).then((res) => {
      ElMessage({
        type: 'success',
        message: res,
        duration: 2500,
        showClose: true,
      })
    })
  })
}
</script>

<style scoped>
pre {
  white-space: pre-wrap;
  word-wrap: break-word;
}
.formatted-body {
  background: #9acbfc7a;
  border-radius: 8px;
  padding: 10px;
}
.formatted-result {
  background: #c8ffad7a;
  border-radius: 8px;
  padding: 10px;
}
:deep(.el-table .success-row) {
  background: #e7ffdb7a;
}
:deep(.el-table .danger-row) {
  background: #fdd5d586;
}
</style>
