<template>
  <page-layer>
    <template #header>
      数据源：
      <el-radio-group v-model="hisWjwMatchEntity.label" @change="fetchDataByLabel">
        <el-radio label="department">科别</el-radio>
        <el-radio label="anaesthesia">麻醉方式</el-radio>
        <el-radio label="diagnose">国临诊断</el-radio>
        <el-radio label="surgery">国临手术操作</el-radio>
        <el-radio label="surgery_chargeCode">手术收费项目</el-radio>
      </el-radio-group>
      <el-button style="margin-left: 50px" type="primary" icon="Refresh" @click="fetchDataByLabel">刷新数据</el-button>
    </template>
    <template #main>
      <div style="display: flex; height: 100%; width: 100%">
        <div style="height: 100%; width: 45%">
          <div style="display: flex">
            <el-input prefix-icon="Search" placeholder="输入拼音、编码或名称以进行检索" v-model="hisInput"
                      clearable></el-input>
            <el-select v-if="hisWjwMatchEntity.label === 'surgery_chargeCode'" v-model="currentStatus">
              <el-option :value="0" label="未匹配"></el-option>
              <el-option :value="1" label="已匹配"></el-option>
              <el-option :value="2" label="全部"></el-option>
            </el-select>
          </div>
          <el-table :data="filterHisList.slice((hisCurrentPage - 1) * 30, hisCurrentPage * 30)"
                    height="500" highlight-current-row stripe @row-click="handleClickHisRow">
            <el-table-column type="index" label="序号"></el-table-column>
            <el-table-column prop="code" label="编码" width="90"></el-table-column>
            <el-table-column prop="name" label="名称"></el-table-column>
            <el-table-column label="状态" width="100">
              <template #default="scope">
                <span v-html="makeMatchStatus(scope.row.wjwCode, scope.row.chargeCode)"></span>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
              @current-change="handleHisPageChange"
              :current-page="hisCurrentPage"
              :page-size="30"
              layout="total, prev, pager, next"
              :total="filterHisList.length"
              style="margin-top: 5px"
          ></el-pagination>
        </div>
        <div class="match-info-box">
          <div>
            <div class="his">
              <div>{{ hisMatchTextNote }}：</div>
              <div class="code">{{ hisWjwMatchEntity.code }}</div>
            </div>
            <div class="wjw">
              <div>{{ wjwMatchTextNote }}：</div>
              <div v-if="hisWjwMatchEntity.label === 'surgery_chargeCode'">
                <div v-for="(item,index) in hisWjwMatchEntity.chargeCode" :key="index" style="display: flex; align-items: center; padding: 2px 0">
                  <div :title="hisWjwMatchEntity.chargeName[index]" style="margin-right: 4px">{{ item }}</div>
                  <div><el-button type="danger" icon="Delete" plain title="删除" circle @click="deleteMatchItem(index)"></el-button></div>
                </div>
              </div>
              <div v-else class="code">{{ hisWjwMatchEntity.wjwCode }}</div>
            </div>
            <el-button v-if="currentHisRow.wjwCode || (currentHisRow.chargeCode && currentHisRow.chargeCode.length > 0)"
                       icon="Close" type="danger"
                       @click="revokeMatch">
              撤销匹配
            </el-button>
            <div style="margin-top: 4px"></div>
            <el-button v-if="!currentHisRow.wjwCode" icon="Check" type="success" @click="executeMatch" :disabled="manageMatchState">
              匹配
            </el-button>
            <div style="margin-top: 4px"></div>
            <el-button v-if="hisWjwMatchEntity.label === 'surgery_chargeCode' && currentStatus === 1"
                       icon="Download" type="warning" @click="exportExcel">
              导出
            </el-button>
          </div>
        </div>
        <div style="height: 100%; width: 45%">
          <el-input prefix-icon="Search" placeholder="输入拼音、编码或名称以进行检索" v-model="wjwInput"
                    clearable></el-input>
          <el-table
              ref="wjwTableRef"
              :data="filterWjwList.slice((wjwCurrentPage - 1) * 30, wjwCurrentPage * 30)"
              highlight-current-row
              stripe
              height="500"
              @row-click="handleClickWjwRow"
              v-loading="disableWjwTable"
              element-loading-background="rgba(0, 0, 0, 0.1)"
              element-loading-text="如需重新匹配，请先【撤销匹配】"
              element-loading-spinner="null"
              element-loading-custom-class="m-loading-text"
          >
            <el-table-column type="index" label="序号"></el-table-column>
            <el-table-column prop="code" label="编码" width="90"></el-table-column>
            <el-table-column prop="name" label="名称"></el-table-column>
            <el-table-column v-if="hisWjwMatchEntity.label === 'diagnose' || hisWjwMatchEntity.label === 'surgery'"
                             prop="similarity" label="目标相似度"></el-table-column>
          </el-table>
          <el-pagination
              @current-change="handleWjwPageChange"
              :current-page="hisCurrentPage"
              :page-size="30"
              layout="total, prev, pager, next"
              :total="filterWjwList.length"
              style="margin-top: 5px"
          ></el-pagination>
        </div>
      </div>
    </template>
  </page-layer>
</template>

<script setup name="HisWjwMatch">
import {selectMatchableDataByLabel, executeMatchAction, fetchSimilarities} from '@/api/dictionary/his-wjw-match'
import {ElMessage} from 'element-plus'
import PageLayer from "@/layout/PageLayer";
import {Export} from "@/utils/ExportExcel";

let wjwTableRef = $ref(null)

let hisInput = $ref('')
let wjwInput = $ref('')

let hisList = $ref([])
let wjwList = $ref([])

let currentHisRow = $ref({})
let currentStatus = $ref(0)
const hisWjwMatchEntity = reactive({
  code: null,
  wjwCode: null,
  chargeCode: [],
  chargeName: [],
  label: 'department',
})

const hisLabel = ['department', 'anaesthesia']
const hisMatchTextNote = computed(() => {
  return hisLabel.indexOf(hisWjwMatchEntity.label) !== -1 ? '当前HIS编码' : '当前国临编码'
})
const wjwMatchTextNote = computed(() => {
  if (hisWjwMatchEntity.label === 'surgery_chargeCode') {
    return '当前收费编码'
  }
  return hisLabel.indexOf(hisWjwMatchEntity.label) !== -1 ? '当前卫健委编码' : '当前医保编码'
})

const disableWjwTable = computed(() => {
  return currentHisRow.wjwCode !== null && currentHisRow.wjwCode !== undefined
})

const filterHisList = computed(() => {
  return hisList.filter((item) => {
    if (currentStatus === 0) {
      return (!item.chargeCode || item.chargeCode.length === 0) &&
          (item.code.indexOf(hisInput) > -1 || item.name.indexOf(hisInput) > -1 || item.pyCode.indexOf(hisInput.toUpperCase()) > -1)
    } else if (currentStatus === 1) {
      return (item.chargeCode && item.chargeCode.length > 0) &&
          (item.code.indexOf(hisInput) > -1 || item.name.indexOf(hisInput) > -1 || item.pyCode.indexOf(hisInput.toUpperCase()) > -1)
    } else {
      return item.code.indexOf(hisInput) > -1 || item.name.indexOf(hisInput) > -1 || item.pyCode.indexOf(hisInput.toUpperCase()) > -1
    }
  })
})

const hisCurrentPage = ref(1)
const wjwCurrentPage = ref(1)
const handleHisPageChange = (val) => {
  hisCurrentPage.value = val
}
const handleWjwPageChange = (val) => {
  wjwCurrentPage.value = val
}

const filterWjwList = computed(() => {
  return wjwList.filter((item) => {
    return item.code.indexOf(wjwInput) > -1 || item.name.indexOf(wjwInput) > -1 || item.pyCode.indexOf(wjwInput.toUpperCase()) > -1
  })
})

const fetchDataByLabel = () => {
  selectMatchableDataByLabel(hisWjwMatchEntity.label).then((res) => {
    hisList = res.hisList
    wjwList = res.wjwList
    currentHisRow = {}
    currentSimilarityKey = null
    hisWjwMatchEntity.code = null
    hisWjwMatchEntity.wjwCode = null
    hisWjwMatchEntity.chargeCode = []
    hisWjwMatchEntity.chargeName = []
  })
}

let currentSimilarityKey = $ref(null)
const handleClickHisRow = (row) => {
  if (row.code !== currentHisRow.code) {
    hisWjwMatchEntity.wjwCode = null
    hisWjwMatchEntity.chargeCode = []
    hisWjwMatchEntity.chargeName = []
    hisWjwMatchEntity.code = row.code
    currentHisRow = row
    if (row.wjwCode) {
      hisWjwMatchEntity.wjwCode = row.wjwCode
      for (let i = 0; i < wjwList.length; i++) {
        if (wjwList[i].code === row.wjwCode) {
          wjwInput = wjwList[i].name
          wjwTableRef.setCurrentRow(wjwList[i])
          break
        }
      }
    } else if (row.chargeCode) {
      hisWjwMatchEntity.chargeCode = row.chargeCode
      hisWjwMatchEntity.chargeName = row.chargeName
    } else {
      if (hisWjwMatchEntity.label === 'department' || hisWjwMatchEntity.label === 'anaesthesia') {
        wjwInput = row.name.length > 3 ? row.name.substring(0, 2) : row.name.substring(0, 1)
      } else if (hisWjwMatchEntity.label === 'diagnose' || hisWjwMatchEntity.label === 'surgery') {
        if (row.code !== currentSimilarityKey) {
          currentSimilarityKey = row.code
          const key = '%' + row.code.split('.')[0].replace('*', '') + '%'
          fetchSimilarities(hisWjwMatchEntity.label, row.name, key).then((res) => {
            wjwList = res
          })
        }
      }
    }
  }
}

const handleClickWjwRow = (row) => {
  if (hisWjwMatchEntity.label === 'surgery_chargeCode') {
    if (hisWjwMatchEntity.chargeCode.indexOf(row.code) === -1) {
      hisWjwMatchEntity.chargeCode.push(row.code)
      hisWjwMatchEntity.chargeName.push(row.name)
    }
  } else {
    hisWjwMatchEntity.wjwCode = row.code
    hisWjwMatchEntity.wjwName = row.name
  }
}

const deleteMatchItem = (index) => {
  hisWjwMatchEntity.chargeCode.splice(index, 1)
  hisWjwMatchEntity.chargeName.splice(index, 1)
}

const makeMatchStatus = (wjwCode, chargeCode) => {
  return (wjwCode || (chargeCode && chargeCode.length > 0)) ? '<span style="color:green">已匹配</span>' : '<span style="color:red">未匹配</span>'
}

const manageMatchState = computed(() => {
  return hisWjwMatchEntity.wjwCode === null && hisWjwMatchEntity.chargeCode.length === 0
})

const executeMatch = () => {
  if (hisWjwMatchEntity.label === 'department' || hisWjwMatchEntity.label === 'anaesthesia') {
    hisWjwMatchEntity.targetCodeColumn = 'wjw_code'
    hisWjwMatchEntity.targetNameColumn = null
  } else if (hisWjwMatchEntity.label === 'surgery_chargeCode') {
    hisWjwMatchEntity.targetCodeColumn = 'charge_code'
    hisWjwMatchEntity.targetNameColumn = 'charge_name'
  }else {
    hisWjwMatchEntity.targetCodeColumn = 'yb_code'
    hisWjwMatchEntity.targetNameColumn = 'yb_name'
  }
  executeMatchAction(hisWjwMatchEntity).then((res) => {
    currentHisRow.wjwCode = hisWjwMatchEntity.wjwCode
    currentHisRow.chargeCode = hisWjwMatchEntity.chargeCode
    currentHisRow.chargeName = hisWjwMatchEntity.chargeName
    ElMessage({
      message: res,
      type: 'success',
      duration: 2500,
      showClose: true,
    })
  })
}

const revokeMatch = () => {
  hisWjwMatchEntity.wjwCode = null
  hisWjwMatchEntity.wjwName = null
  if (hisWjwMatchEntity.label === 'department' || hisWjwMatchEntity.label === 'anaesthesia') {
    hisWjwMatchEntity.targetCodeColumn = 'wjw_code'
    hisWjwMatchEntity.targetNameColumn = null
  } else if (hisWjwMatchEntity.label === 'surgery_chargeCode') {
    hisWjwMatchEntity.chargeCode = []
    hisWjwMatchEntity.chargeName = []
    hisWjwMatchEntity.targetCodeColumn = 'charge_code'
    hisWjwMatchEntity.targetNameColumn = 'charge_name'
  } else {
    hisWjwMatchEntity.targetCodeColumn = 'yb_code'
    hisWjwMatchEntity.targetNameColumn = 'yb_name'
  }
  executeMatchAction(hisWjwMatchEntity).then((res) => {
    currentHisRow.wjwCode = null
    currentHisRow.chargeCode = []
    currentHisRow.chargeName = []
    wjwTableRef.setCurrentRow(null)
    ElMessage({
      message: res,
      type: 'success',
      duration: 2500,
      showClose: true,
    })
  })
}

const exportExcel = () => {
  const fields = {
    code: '手术操作编码',
    name: '手术操作名称',
    chargeCodeString: '匹配收费编码',
    chargeNameString: '匹配收费名称',
  }
  Export(filterHisList.value, fields, '已匹配数据')
}

onMounted(() => {
  fetchDataByLabel()
})
</script>

<style lang="scss">
.match-info-box {
  height: 80%;
  display: flex;
  align-items: center;
  justify-content: center;

  .his {
    color: green;
    padding-bottom: 6px;
  }

  .wjw {
    color: blue;
    padding-top: 7px;
    border-top: 1px solid gray;
    margin-bottom: 12px;
  }

  .code {
    font-weight: bold;
    font-size: 14px;
    padding: 2px 0;
    &:hover {
      border: 1px solid green;
    }
  }
}

.el-loading-spinner .el-loading-text {
  font-weight: bold !important;
  color: #ff1212 !important;
}
</style>
