<template>
  <page-layer>
    <template #header>
      <el-select v-model="queryParam.status" style="width: 88px" @change="data.list = []">
        <el-option v-for="item in statuses" :key="item.code" :label="item.name" :value="item.code"></el-option>
      </el-select>
      &nbsp;
      <el-select v-model="queryParam.delFlag" style="width: 80px" @change="data.list = []">
        <el-option v-for="item in delFlags" :key="item.code" :label="item.name" :value="item.code"></el-option>
      </el-select>
      &nbsp;
      <el-select v-model="queryParam.type" style="width: 120px" @change="queryTypeChanged">
        <el-option v-for="item in types" :key="item.code" :label="item.name" :value="item.code"></el-option>
      </el-select>
      &nbsp;&nbsp;编码：
      <el-input v-model="queryParam.code" clearable style="width: 100px"></el-input>
      &nbsp;&nbsp;名称：
      <el-input v-model="queryParam.name" clearable style="width: 160px"></el-input>
      <el-divider direction="vertical"></el-divider>
      <span v-if="queryParam.status === 0">
        模糊查询：
        <el-switch v-model="fuzzy" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
        &nbsp;
      </span>
      <el-button icon="Search" type="primary" @click="search">检索</el-button>&nbsp; <el-button type="danger" @click="syncInjryMtch">同步工伤匹配</el-button>&nbsp;
      <span v-if="queryParam.status === 0 && queryParam.type >= 3">
        <el-button icon="Refresh" type="warning" @click="syncNewServiceOrItem"> 同步新增{{ queryParam.type === 3 ? '项目' : '耗材' }} </el-button>
      </span>
      <span v-if="queryParam.status === 1">
        <el-button icon="Upload" type="primary" @click="beforeUploadMatch">上传匹配关系</el-button>
        <el-button icon="Download" type="primary" @click="exportExcel">导出EXCEL</el-button>
      </span>
    </template>
    <template #main>
      <el-table :data="data.list" :height="tableHeight" stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column label="编码" prop="code"></el-table-column>
        <el-table-column label="名称" prop="name"></el-table-column>
        <el-table-column v-if="queryParam.type === 1" label="大小包装" prop="serial"></el-table-column>
        <el-table-column v-if="queryParam.type < 3" label="剂型" prop="dosage"></el-table-column>
        <el-table-column label="单位" prop="unit"></el-table-column>
        <el-table-column v-if="queryParam.type !== 3" label="规格" prop="specification"></el-table-column>
        <el-table-column v-if="queryParam.type === 3" label="内涵" prop="discription"></el-table-column>
        <el-table-column v-if="queryParam.type === 3" label="标准编码" prop="standardCode"></el-table-column>
        <el-table-column v-if="queryParam.type === 3" label="价格" prop="price"></el-table-column>
        <el-table-column v-if="queryParam.type < 3" label="批准文号" prop="approvalNumber"></el-table-column>
        <el-table-column v-if="queryParam.type !== 3" label="生产厂家" prop="factory"></el-table-column>
        <el-table-column v-if="queryParam.type === 3" label="地方名称" prop="localName"></el-table-column>
        <el-table-column v-if="queryParam.status === 1" label="国家名称" prop="nationalName"></el-table-column>
        <el-table-column v-if="queryParam.status === 1" label="国家代码" prop="nationalCode"></el-table-column>
        <el-table-column v-if="queryParam.status === 1" label="开始时间" prop="startTime"></el-table-column>
        <el-table-column v-if="queryParam.status === 1" label="结束时间" prop="endTime"></el-table-column>
        <el-table-column v-if="queryParam.status === 1" label="是否已上传">
          <template #default="scope">
            {{ cptYesOrNo(scope.row.uploadedFlag) }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button icon="Edit" text @click="modifyLocalItem(scope.row)">修改</el-button>
            <el-button v-if="queryParam.status === 1" icon="RefreshLeft" text @click="rvkUploadMatch(scope.row)">撤销匹配上传 </el-button>
            <el-button v-if="queryParam.status === 0" icon="Aim" text @click="beforeMatch(scope.row)"> 匹配 </el-button>
            <el-button v-else icon="Close" text @click="deleteMatch(scope.row)">取消匹配</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          :current-page="queryParam.currentPage"
          :page-size="queryParam.pageSize"
          :page-sizes="[15, 30, 45, 70, 100]"
          :total="data.total"
          layout="total, sizes, prev, pager, next, jumper"
          style="margin-top: 5px"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      ></el-pagination>
      <el-dialog v-model="showNationalList" width="80%">
        <div class="data-title">HIS数据</div>
        <el-descriptions :column="4" border>
          <el-descriptions-item>
            <template #label> 编码</template>
            {{ data.row.code }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label> 名称</template>
            {{ data.row.name }}
          </el-descriptions-item>
          <el-descriptions-item v-if="queryParam.type !== 3">
            <template #label> 大小包装</template>
            {{ data.row.serial === '01' ? '大包装' : '小包装' }}
          </el-descriptions-item>
          <el-descriptions-item v-if="queryParam.type !== 3">
            <template #label> 剂型</template>
            {{ data.row.dosage }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label> 单位</template>
            {{ data.row.unit }}
          </el-descriptions-item>
          <el-descriptions-item v-if="queryParam.type === 3">
            <template #label> 标准编码</template>
            {{ data.row.standardCode }}
          </el-descriptions-item>
          <el-descriptions-item v-if="queryParam.type === 3">
            <template #label> 价格</template>
            {{ data.row.price }}
          </el-descriptions-item>
          <el-descriptions-item v-if="queryParam.type !== 3">
            <template #label> 规格</template>
            {{ data.row.specification }}
          </el-descriptions-item>
          <el-descriptions-item v-if="queryParam.type === 3">
            <template #label> 内涵</template>
            {{ data.row.discription }}
          </el-descriptions-item>
          <el-descriptions-item v-if="queryParam.type !== 3">
            <template #label> 批准文号</template>
            {{ data.row.approvalNumber }}
          </el-descriptions-item>
          <el-descriptions-item v-if="queryParam.type !== 3">
            <template #label> 生产厂家</template>
            {{ data.row.factory }}
          </el-descriptions-item>
        </el-descriptions>
        <div class="data-title">国家数据</div>
        <el-input v-show="queryParam.type === 3" v-model="discription" clearable style="width: 300px">
          <template #prepend>内涵过滤</template>
        </el-input>
        <el-input v-show="queryParam.type === 1 || queryParam.type === 4" v-model="factory" clearable style="width: 300px">
          <template #prepend>厂家过滤</template>
        </el-input>
        <el-divider v-show="queryParam.type === 4" direction="vertical"></el-divider>
        <el-input v-show="queryParam.type === 4" v-model="certiNo" clearable style="width: 320px">
          <template #prepend>注册证号过滤</template>
        </el-input>
        <el-input v-model="nationalCode" clearable style="width: 320px">
          <template #prepend>国家代码</template>
        </el-input>
        <el-table :data="cptNationalItems" :height="dialogTableHeight" stripe>
          <el-table-column label="国家代码" prop="nationalCode"></el-table-column>
          <el-table-column label="国家名称" prop="nationalName"></el-table-column>
          <el-table-column v-if="queryParam.type === 1" label="剂型" prop="actualDosage"></el-table-column>
          <el-table-column v-if="queryParam.type === 1" label="规格" prop="specifications"></el-table-column>
          <el-table-column v-if="queryParam.type === 1" label="包装材质" prop="packingMaterial"></el-table-column>
          <el-table-column v-if="queryParam.type === 1" label="生产厂家" prop="factory"></el-table-column>
          <el-table-column v-if="queryParam.type === 1" label="批准文号" prop="approvalNumber"></el-table-column>
          <el-table-column v-if="queryParam.type === 1" label="药品本位码" prop="drugStandardCode"></el-table-column>
          <el-table-column v-if="queryParam.type === 3" label="项目内涵" prop="projectConnotation"></el-table-column>
          <el-table-column v-if="queryParam.type === 3" label="除外内容" prop="exclusions"></el-table-column>
          <el-table-column v-if="queryParam.type === 3" label="计价单位" prop="valuationUnit"></el-table-column>
          <el-table-column v-if="queryParam.type === 3" label="项目说明" prop="projectDescription"></el-table-column>
          <el-table-column v-if="queryParam.type === 4" label="医保通用名" prop="siName"></el-table-column>
          <el-table-column v-if="queryParam.type === 4" label="材质" prop="material"></el-table-column>
          <el-table-column v-if="queryParam.type === 4" label="耗材企业" prop="factory"></el-table-column>
          <el-table-column label="开始时间" prop="startTime"></el-table-column>
          <el-table-column label="结束时间" prop="endTime"></el-table-column>
          <el-table-column label="状态">
            <template #default="scope">
              <div v-html="filterMatchedCount(scope.row.matchedCount)"></div>
            </template>
          </el-table-column>
          <el-table-column label="匹配">
            <template #default="scope">
              <el-button circle icon="Pointer" type="success" @click="doMatch(scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="height: 12px"></div>
      </el-dialog>
      <el-dialog
          title="耗材查询"
          v-model="showSuppliesQueryForm"
          width="420px">
        <div style="background: lightblue; color:black; padding: 4px; border-radius: 4px">
          小提示：每次查询只需填写一项条件。如果填写了多项，程序也只会根据优先级最高的一项来查询。
          <div style="margin-top: 8px">
            优先级：国家编码 > 注册证号 > 耗材名称
          </div>
        </div>
        <div style="width: 300px;margin-top: 16px">
          国家编码：<el-input v-model="currentSupplyRow.nationalCode" placeholder="耗材国家编码 - 精准查询" clearable style="width: 200px"></el-input>
        </div>
        <div style="width: 300px;margin-top: 8px">
          注册证号：<el-input v-model="currentSupplyRow.approvalNumber" placeholder="耗材注册证号 - 精准查询" clearable style="width: 200px"></el-input>
        </div>
        <div style="width: 300px;margin-top: 8px">
          耗材名称：<el-input v-model="currentSupplyRow.fuzzyName" placeholder="耗材名称 - 模糊查询" clearable style="width: 200px"></el-input>
        </div>
        <template #footer>
          <el-button type="info" icon="Close" @click="showSuppliesQueryForm = false">取消</el-button>
          <el-button type="primary" icon="Search" @click="getNationalItems">查询</el-button>
        </template>
      </el-dialog>
      <el-drawer v-model="showModifyLocalItem" direction="rtl" title="项目修改">
        <div style="padding: 20px">
          <el-input v-model="data.row.name" clearable size="small">
            <template #prepend>项目名称</template>
          </el-input>
          <div v-if="queryParam.type === 4">
            <el-input v-model="data.row.specification" class="mt-12" clearable size="small">
              <template #prepend>项目规格</template>
            </el-input>
            <el-input v-model="data.row.factory" class="mt-12" clearable size="small">
              <template #prepend>生产厂家</template>
            </el-input>
          </div>
          <div v-if="queryParam.type === 3">
            <el-input v-model="data.row.price" class="mt-12" clearable size="small">
              <template #prepend>项目金额</template>
            </el-input>
            <el-input v-model="data.row.unit" class="mt-12" clearable size="small">
              <template #prepend>项目单位</template>
            </el-input>
            <el-input v-model="data.row.standardCode" class="mt-12" clearable size="small">
              <template #prepend>标准编码</template>
            </el-input>
            <div class="m-prepend">项目内涵</div>
            <el-input v-model="data.row.discription" class="mt-4" clearable rows="3" size="small" type="textarea"></el-input>
          </div>
          <div class="drawer-footer">
            <el-button icon="Close" size="small" @click="cancelModify">取消</el-button>
            <el-button icon="Check" size="small" type="primary" @click="confirmModify"> 保存</el-button>
          </div>
        </div>
      </el-drawer>
      <el-dialog v-model="showUploadPrm" title="请填写以下参数" width="20%">
        <div style="height: 8px"></div>
        <el-date-picker v-model="uploadPrm.beginDate" format="YYYY-MM-DD" placeholder="开始日期" value-format="YYYY-MM-DD"></el-date-picker>
        <div style="height: 8px"></div>
        <el-date-picker v-model="uploadPrm.endDate" format="YYYY-MM-DD" placeholder="结束日期" value-format="YYYY-MM-DD"></el-date-picker>
        <div style="height: 16px"></div>
        <el-button icon="Check" type="primary" @click="executeUploadMatch">确定上传</el-button>
      </el-dialog>
    </template>
  </page-layer>
</template>

<script setup name="NationalSiMatch">
import { reactive, ref } from '@vue/reactivity'
import {
  asyncNewNameForServicesOrItems,
  cancelMatch,
  executeMatch,
  selectLocalItems,
  selectNationalItems,
  synchronizeInjuryMatch,
  updateLocalItem,
} from '@/api/dictionary/national-match'
import store from '@/store'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed } from '@vue/runtime-core'
import { cptYesOrNo } from '@/utils/computed'
import { revokeCatalogueContrast, uploadCatalogueContrast } from '@/api/medical-insurance/si-manage'
import { Export } from '@/utils/ExportExcel'
import { clone } from '@/utils/clone'
import PageLayer from "@/layout/PageLayer";

const windowSize = store.state.app.windowSize
const tableHeight = windowSize.h - 50
const dialogTableHeight = tableHeight * 0.8 - 160
const statuses = initStatuses()
const delFlags = initDelFlags()
const types = initTypes()
const factory = ref('')
const certiNo = ref('')
const nationalCode = ref('')
const discription = ref('')
const fuzzy = ref(false)
const data = reactive({
  total: 0,
  list: [],
  row: {},
  national: [],
})
const selections = ref([])
const showUploadPrm = ref(false)
const uploadPrm = reactive({
  type: '',
  beginDate: '',
  endDate: '',
})

const cptNationalItems = computed(() => {
  if (queryParam.type === 1) {
    return data.national.filter((item) => {
      return item.factory.indexOf(factory.value) !== -1 && item.nationalCode.indexOf(nationalCode.value) !== -1
    })
  } else if (queryParam.type === 3) {
    return data.national.filter((item) => {
      return item.projectConnotation.indexOf(discription.value) !== -1 && item.nationalCode.indexOf(nationalCode.value) !== -1
    })
  } else if (queryParam.type === 4) {
    return data.national.filter((item) => {
      return item.factory.indexOf(factory.value) !== -1 && item.nationalCode.indexOf(nationalCode.value) !== -1
    })
  } else {
    return data.national.filter((item) => {
      return true
    })
  }
})

const queryParam = reactive({
  status: 0,
  delFlag: 0,
  type: 1,
  code: null,
  name: null,
  pageSize: 30,
  currentPage: 1,
  isExport: false,
})

const queryTypeChanged = (val) => {
  data.list = []
  data.national = []
  fuzzy.value = val === 4;
}

const search = () => {
  queryParam.isExport = false
  selectLocalItems(queryParam)
    .then((res) => {
      data.total = res.total
      data.list = res.list
    })
    .catch(() => {
      data.list = []
    })
}

const handleSizeChange = (val) => {
  queryParam.pageSize = val
  search()
}
const handleCurrentChange = (val) => {
  queryParam.currentPage = val
  search()
}

const syncNewServiceOrItem = () => {
  asyncNewNameForServicesOrItems().then((res) => {
    ElMessage({
      type: 'success',
      message: res,
      duration: 2000,
      showClose: true,
    })
    search()
  })
}

const showModifyLocalItem = ref(false)
const modifyLocalItem = (row) => {
  if (row.uploadedFlag === 1) {
    ElMessage({
      message: '请先撤销匹配上传再修改。',
      type: 'warning',
      showClose: true,
    })
    return
  }
  data.row = row
  showModifyLocalItem.value = true
}
const cancelModify = () => {
  showModifyLocalItem.value = false
  search()
}
const confirmModify = () => {
  updateLocalItem(data.row).then((res) => {
    ElMessage({
      type: 'success',
      message: res,
      duration: 2000,
      showClose: true,
    })
    showModifyLocalItem.value = false
  })
}

const showNationalList = ref(false)
const showSuppliesQueryForm = ref(false)
const currentSupplyRow = ref({})

const beforeMatch = (row) => {
  if(queryParam.type === 4) {
    currentSupplyRow.value = clone(row)
    currentSupplyRow.value.fuzzyName = null
    showSuppliesQueryForm.value = true
  } else {
    if (fuzzy.value) {
      ElMessageBox.prompt('请调整关联查询的名称：', '提示', {
        inputValue: row.name,
        confirmButtonText: '查询',
        cancelButtonText: '取消',
      })
          .then(({ value }) => {
            row.fuzzyName = value
            getNationalItems(row)
          })
          .catch(() => {})
    } else {
      row.fuzzyName = row.name
      getNationalItems(row)
    }
  }
}

const getNationalItems = (row) => {
  if (queryParam.type === 4) {
    row = currentSupplyRow.value
  }
  selectNationalItems(row)
    .then((res) => {
      factory.value = ''
      data.row = row
      data.national = res
      showNationalList.value = true
      showSuppliesQueryForm.value = false
    })
    .catch((e) => {
      if (e === '没有符合条件的国家目录。') {
        ElMessageBox.prompt('没有符合条件的国家目录，请输入国家编码进行手动匹配：', '提示', {
          inputValue: null,
          confirmButtonText: '匹配',
          cancelButtonText: '取消',
          inputPattern: /\S/,
          inputErrorMessage: '国家编码不能为空',
        })
          .then(({ value }) => {
            data.row = row
            data.row.nationalCode = value
            executeMatch(data.row).then((res) => {
              search()
              ElMessage({
                type: 'success',
                message: res,
                duration: 2000,
                showClose: true,
              })
            })
          })
          .catch(() => {})
      }
    })
}

const filterMatchedCount = (count) => {
  return count > 0 ? '<span style="color: red">已被匹配</span>' : '<span style="color: green">未被匹配</span>'
}

const doMatch = (row) => {
  const header =
    '<div style="font-weight: bold">选中的数据为：</div><div style="color: #409EFF">' +
    '本院名称：' +
    data.row.name +
    '</div>' +
    '<div style="color:red">' +
    '<div>' +
    '国家名称：' +
    row.nationalName +
    '</div>' +
    '<div>' +
    '国家代码：' +
    row.nationalCode +
    '</div>' +
    '</div>'

  const medOnly =
    '<div style="color: #409EFF; margin-top: 8px">' +
    '本院规格：' +
    data.row.specification +
    '</div>' +
    '<div style="color:red">' +
    '<div>' +
    '注册规格：' +
    row.makeRegisteredSpecification +
    '</div>' +
    '<div>' +
    '实际规格：' +
    row.makeActualSpecification +
    '</div>' +
    '</div>'

  const srvcOnly = '<div style="color: #409EAA">' + '地方名称：' + row.localMedicalServiceName + '</div>'

  const supplyOnly = '<div style="color: #409EAA">' + '注册证号：' + row.registrationCertificateNo + '</div>'

  const end = '<div style="font-weight: bold"d>是否确认匹配？</div>'

  let msg = ''
  if (queryParam.type === 3) {
    msg = header + srvcOnly + end
  } else if (queryParam.type === 4) {
    msg = header + supplyOnly + end
  } else {
    msg = header + medOnly + end
  }

  ElMessageBox.confirm(msg, '提示', {
    dangerouslyUseHTMLString: true,
    type: 'warning',
    confirmButtonText: '确认匹配',
    cancelButtonText: '取消',
  })
    .then(() => {
      data.row.nationalCode = row.nationalCode
      data.row.nationalName = row.nationalName
      executeMatch(data.row).then((res) => {
        search()
        showNationalList.value = false
        ElMessage({
          type: 'success',
          message: res,
          duration: 2000,
          showClose: true,
        })
      })
    })
    .catch({})
}

const deleteMatch = (row) => {
  if (row.uploadedFlag === 1) {
    ElMessage({
      message: '请先撤销匹配上传再取消匹配。',
      type: 'warning',
      showClose: true,
    })
    return
  }
  cancelMatch(row).then((res) => {
    ElMessage({
      type: 'success',
      message: res,
      duration: 2000,
      showClose: true,
    })
    search()
  })
}

const handleSelectionChange = (val) => {
  selections.value = val
}

const beforeUploadMatch = () => {
  if (selections.value.length === 0) {
    ElMessage({
      message: '请选择要上传的条目！',
      type: 'warning',
      showClose: true,
    })
    return
  }
  uploadPrm.type = queryParam.type
  showUploadPrm.value = true
}

const executeUploadMatch = () => {
  if (!uploadPrm.beginDate || !uploadPrm.endDate) {
    ElMessage({
      message: '请填写开始日期和结束日期。',
      type: 'warning',
      showClose: true,
    })
    return
  }
  uploadPrm.list = selections
  uploadCatalogueContrast(uploadPrm).then((res) => {
    ElMessage({
      message: res,
      type: 'success',
      showClose: true,
    })
    showUploadPrm.value = false
  })
}

const rvkUploadMatch = (row) => {
  uploadPrm.type = queryParam.type
  uploadPrm.chargeCode = row.code
  uploadPrm.nationalCode = row.nationalCode
  revokeCatalogueContrast(uploadPrm).then((res) => {
    ElMessage({
      message: res,
      type: 'success',
      showClose: true,
    })
  })
}

const syncInjryMtch = () => {
  synchronizeInjuryMatch().then((res) => {
    ElMessage({
      message: res,
      type: 'success',
      showClose: true,
    })
  })
}

const exportExcel = () => {
  queryParam.isExport = true
  selectLocalItems(queryParam).then((res) => {
    queryParam.isExport = false
    const fields = {
      code: '院内码',
      name: '院内名称',
      nationalCode: '国家编码',
      nationalName: '国家名称',
      startTime: '开始日期',
      endTime: '结束日期',
      localName: '地方编码',
      unit: '单位',
      serial: '大小包装',
      dosage: '剂型',
      specification: '规格',
      approvalNumber: '注册证号',
      factory: '厂家',
      discription: '内涵',
      standardCode: '标准编码',
      price: '价格',
    }
    Export(res.list, fields, '已匹配数据')
  })
}

function initStatuses() {
  return [
    { code: 0, name: '未匹配' },
    { code: 1, name: '已匹配' },
  ]
}

function initDelFlags() {
  return [
    { code: 0, name: '启用' },
    { code: 1, name: '停用' },
  ]
}

function initTypes() {
  return [
    { code: 1, name: '西药/中成药' },
    { code: 2, name: '中草药' },
    { code: 3, name: '项目' },
    { code: 4, name: '耗材' },
  ]
}
</script>

<style scoped>
.data-title {
  padding: 8px 0;
  font-size: 16px;
  color: #333;
  font-weight: bold;
}

.mt-4 {
  margin-top: 4px;
}

.mt-12 {
  margin-top: 12px;
}

.m-prepend {
  margin-top: 12px;
  height: 28px;
  line-height: 28px;
  background-color: #f5f7fa;
  color: #909399;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 0 20px;
}

.drawer-footer {
  margin-top: 16px;
  width: 100%;
  text-align: end;
}
</style>
